我正在尝试使用pytest-flask为Flask应用程序实现单元测试。我的查询的输出取决于当前时间。
为了一致的单元测试,我尝试冻结时间。我习惯了冻结tried,所以这是我尝试过的:
# Session for scope, otherwise server is reloaded everytime
@pytest.fixture(scope="session")
@freeze_time("2018-04-15")
def app():
os.environ["FLASK_ENV"] = "development"
app = create_app()
# http://flask.pocoo.org/docs/1.0/api/#flask.Flask.test_client
app.testing = True
return app
@pytest.mark.usefixtures("live_server")
class TestLiveServer:
# Freeze time to get consistent output.
@freeze_time("2018-04-15")
def test_export(self):
q = "Chocapic"
r = requests.post(
url_for("query_direct", _external=True), json={"query": q}
)
print(r.text)
export_path = os.path.join("tests", "fake_responses", q)
with open(export_path, "w") as outfile:
json.dump(r.json(), outfile, indent=4)
with open(export_path, "r") as infile:
data = json.load(infile)
assert r.json() == data
我可以在日志中看到我的应用程序是以适当的冻结时间启动的。但是当测试运行时,我可以看到查询端点是用实际的当前时间完成的。看起来fixture live_server
重置了当前时间。
你遇到过这个问题吗?
发布于 2020-10-07 09:09:06
根据the documentation的说法,liver_server
装置在一个单独的进程中运行应用程序。也许,Freezegun不能在其他进程中发挥作用,只能在当前进程中发挥作用。
您真的需要实时服务器吗?我在没有实时服务器的情况下运行所有的测试。
也许你可以把你的测试分成两组?使用Freezegun可以在没有实时服务器的情况下获得可重现的响应,并且只使用实时服务器测试您需要实时服务器做的任何事情(Javascript?硒?)。
https://stackoverflow.com/questions/54979277
复制相似问题