pytest测试后清除烧瓶会话闪存消息

时间:2020-02-19 14:40:17

标签: flask

我有一个正在使用pytest测试的Flask网站。我想测试某些视图是否正确设置了flask.flash条消息。我可以这样做,但是Flash消息在两次测试之间仍然存在,我希望它们可以清除。

我有这个test_client固定装置:

@pytest.fixture(scope="session")
def app():
    # create_app() returns a configured Flask app:
    app = create_app("testing")
    with app.test_request_context():
        yield app

@pytest.fixture(scope="session")
def test_client(app):
    with app.test_client() as c:
        yield c

我有这样的测试:

from flask import session

def test_my_redirect_view(test_client):
    "It should redirect and set the correct flash message"
    response = test_client.get("/my/path", follow_redirects=False)

    assert response.status_code == 302
    assert response.location == "http://localhost/a/different/url"

    assert "_flashes" in session
    assert len(session["_flashes"]) == 1
    assert session["_flashes"][0][0] == "warning"
    assert session["_flashes"][0][1] == "My error message"

正如我所说,假设我的视图设置了此Flash消息并正确重定向,则此测试通过。但是随后的类似测试将失败,因为随后len(session["_flashes"])将是2,因为它具有来自两个测试视图的消息。

我尝试在每次测试结束时执行此操作,但是没有明显效果:

    del session["_flashes"][0]

1 个答案:

答案 0 :(得分:0)

这不是一个理想的答案,因为它不能确保被测试的视图仅设置一条即显消息,但现在我将与该显存消息有关的assert行替换为:

    assert ("warning", "My error message") in session["_flashes"]