【问题标题】:Is there a way to test if flask template contains a link?有没有办法测试烧瓶模板是否包含链接?
【发布时间】:2018-11-23 12:00:49
【问题描述】:

我一直在测试路由是否存在使用

def test_index(self):
    r = self.app.get("/")
    self.assertEqual(200, r.status_code, "Status code was not 'OK'.")

我的模板有一个指向另一个页面的超链接。有没有办法测试这是否存在?

【问题讨论】:

  • 您是否使用url_for() 制作链接?
  • 是的,我使用 url_for()

标签: python python-2.7 unit-testing testing flask


【解决方案1】:

好吧,如果您正在测试模板,那么您呈现的每个模板都是对某个路由的请求的结果。如果您使用url_for()在模板中渲染url,那么如果url指向不存在的路由,它将引发BuildError,并且服务器将返回状态码500。因此,您不需要解析如果您只是检查路线,请手动使用模板进行测试。

例子:

from flask import Flask, render_template_string

app = Flask(__name__)

@app.route('/index')
def index():
    return render_template_string("""
        {{ url_for('index') }}
        {{ url_for('blabla') }}
    """)


def test_index(self):
    r = self.app.get("/index")
    self.assertEqual(200, r.status_code, "Status code was not 'OK'.")

这将导致 routing.BuildError: Could not build url for endpoint 'blabla'. Did you mean 'static' instead? 错误,导致您的测试失败。

我希望这个解释足够清楚!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-27
    • 2021-01-17
    • 1970-01-01
    • 2013-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多