gpt4 book ai didi

python - Pytest flask live_server : can't freeze time

转载 作者:行者123 更新时间:2023-12-04 16:45:02 30 4
gpt4 key购买 nike

我正在尝试使用 pytest-flask 为 Flask 应用程序实现单元测试。我的查询输出取决于当前时间。

为了一致的单元测试,我试图卡住时间。我习惯了 freezegun,所以这是我尝试过的:

# 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 重置了当前时间。

你遇到过这个问题吗?

最佳答案

根据the documentation liver_server fixture 在单独的进程中运行应用程序。可能,Freezegun 无法在其他进程中发挥作用,只能在当前进程中发挥作用。

您真的需要实时服务器吗?我在没有实时服务器的情况下运行所有​​测试。

也许您可以将测试分成两组?使用 Freezegun 在没有实时服务器的情况下获得可重现的响应,并且仅使用实时服务器来测试您需要实时服务器的任何内容(Javascript?Selenium?)。

关于python - Pytest flask live_server : can't freeze time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54979277/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com