【问题标题】:How to test Flask view context and templates using pytest?如何使用 pytest 测试 Flask 视图上下文和模板?
【发布时间】:2019-07-12 11:28:58
【问题描述】:

我正在将 pytest 与 Flask 一起使用,并想测试我的视图和模板,但我不清楚如何最好地做到这一点。

我知道我可以测试 HTML 输出的内容,例如:

def test_my_view(test_client):
    # test_client is a fixture representing app.test_client()
    response = test_client.get("/my-url")
    assert b"<h1>My page title</h1>" in response.data

但有些事情我不确定该怎么做:

  1. 如何测试视图正在使用哪个模板?

  2. 如何测试视图发送到模板的上下文? (例如检查login_formLoginForm 的一个实例)

  3. 如果我想测试是否存在更复杂的 HTML 标记,例如具有正确 action 属性的 &lt;form&gt; 标记,是检查整个标记是否存在的唯一方法(例如987654326@) 即使我不关心其他属性?假设页面上还有其他表单,我怎么能只检查action

【问题讨论】:

    标签: flask pytest


    【解决方案1】:

    我已经意识到 1 和 2 可以通过类似于 this question 中的解决方案来解决,稍作改动以用于 pytest。

    假设我们有这个 Flask 视图:

    from flask import render_template
    from app import app
    
    @app.route("/my/view")
    def my_view():
        return render_template("my/template.html", greeting="Hello!")
    

    我们想测试调用该 URL 是否使用了正确的模板,并且传递了正确的上下文数据。

    首先,创建一个可复用的fixture:

    from flask import template_rendered
    import pytest
    
    @pytest.fixture
    def captured_templates(app):
        recorded = []
    
        def record(sender, template, context, **extra):
            recorded.append((template, context))
    
        template_rendered.connect(record, app)
        try:
            yield recorded
        finally:
            template_rendered.disconnect(record, app)
    

    我还有一个 test_client 夹具用于在测试中发出请求(类似于 testapp fixture in Flask Cookiecuttertest_client fixture in this tutorial)。

    然后编写你的测试:

    def test_my_view(test_client, captured_templates):
        response = test_client.get("/my/view")
    
        assert len(captured_templates) == 1
    
        template, context = captured_templates[0]
    
        assert template.name = "my/template.html"
    
        assert "greeting" in context
        assert context["greeting"] == "Hello!"
    

    请注意,captured_templates 中可能有多个元素,具体取决于您的视图的作用。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-15
    • 2019-02-08
    • 1970-01-01
    • 2020-05-27
    • 1970-01-01
    • 1970-01-01
    • 2014-07-22
    • 2015-11-22
    相关资源
    最近更新 更多