【问题标题】:pytest and flask: keep liver server alive for test classpytest 和烧瓶:为测试类保持肝脏服务器存活
【发布时间】:2019-03-03 18:41:47
【问题描述】:

我正在尝试为我的 Flask 应用程序实现单元测试(使用 pytest)。

我的应用执行一些 I/O 密集型任务,这些任务在初始化时会持续几分钟,因此我想为我的测试启动一个实时服务器,并在同一服务器实例上测试所有端点。

这是我的测试:

@pytest.fixture
def app():

    os.environ["FLASK_ENV"] = "development"
    os.environ["DATABASE_URI"] = os.path.join(
        ds.WORK_DIR, "tests", "fake_db.sqlite"
    )
    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:
    def test_server_is_up_and_running(self):
        res = requests.get(url_for("index", _external=True))

        assert res.status_code == 200, "Index end point didn't return correct answer"
        assert "worksies" in res.text, "worksies not returned..."

    def test_proper_db(self):
        res = requests.get(url_for("all_products", _external=True))

上面的代码工作正常,一切都被完美地加载和测试,但似乎为每个test_ 方法启动了一个新服务器。至少,I/O 任务会执行两次。

我怎样才能避免这种情况?

【问题讨论】:

    标签: python flask pytest


    【解决方案1】:

    scope=session 用于您的灯具。每个测试会话只会执行一次。

    @pytest.fixture(scope=session)
    def app():
        # your code here
    

    我不知道live_server 固定装置是什么,但建议它也可以标记为会话范围。

    【讨论】:

      猜你喜欢
      • 2019-01-04
      • 1970-01-01
      • 2017-08-15
      • 1970-01-01
      • 1970-01-01
      • 2016-04-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-20
      相关资源
      最近更新 更多