【问题标题】:Pytest flask live_server: can't freeze timePytest flask live_server:无法冻结时间
【发布时间】:2019-07-25 12:45:21
【问题描述】:

我正在尝试使用 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

我可以在日志中看到我的应用程序以正确的冻结时间启动。但是当测试运行时,我可以看到查询端点是用实际的当前时间完成的。看来夹具live_server 重置了当前时间。

你遇到过这个问题吗?

【问题讨论】:

  • patch_datetime_now 夹具的外观如何?
  • 抱歉,只是调试会话的剩余部分。我删除了它,很好。

标签: python flask pytest freezegun


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-08
    • 2021-03-11
    • 1970-01-01
    • 2023-02-25
    • 1970-01-01
    • 1970-01-01
    • 2019-01-04
    相关资源
    最近更新 更多