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



我有一个Flask站点,我正在使用pytest进行测试。我想测试一些视图是否正确设置了flask.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]

这不是一个理想的答案,因为它不能确保测试的视图只设置一个闪存消息,但目前我将用替换与闪存消息相关的assert

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

最新更新