为什么 pytest 在测试 Flask 应用程序时找不到 'client' fixture?

Why can't pytest find the 'client' fixture when testing a Flask app?

我有一个简单的 flask 应用程序,我想使用 pytest 对其进行测试。

我的conftest.py:

@pytest.fixture
def app(self):
    app = create_app(TestingConfig)

    return app

我的test_view.py:

class TestMainView:

def test_ping(self, client):
    res = client.get(url_for('main.index'))
    assert res.status_code == 200

当我 运行 测试使用 pytest 时,它会抛出一条错误消息:

fixture 'client' not found
>       available fixtures: app, cache, capfd, capfdbinary, caplog, capsys, capsysbinary, doctest_namespace, monkeypatch, pytestconfig, record_xml_property, recwarn, tmpdir, tmpdir_factory
>       use 'pytest --fixtures [testpath]' for help on them.

我有另一个测试文件,我在其中测试默认配置并通过:

class TestTestingClass(object):
app = create_app(TestingConfig)

def test_app_is_test(self):
    ''' test the test enviroment is set okay and works'''
    assert self.app.config['SECRET_KEY'] == 'something hard'
    assert self.app.config['DEBUG'] == True
    assert self.app.config['TESTING'] == True
    assert current_app is not None
    assert self.app.config['SQLALCHEMY_DATABASE_URI'] == 'sqlite:////tmp/testing.db'

编辑: 通过更改为:

,我能够通过空测试

conftest.py:

@pytest.fixture
def app():
    app = create_app(TestingConfig)

    return app


@pytest.fixture
def client(app):
    return app.test_client()

和我的测试文件:

def test_index(client):
   assert True

但是,我仍然无法通过 test_index 如果它是:

def test_index(client):
   assert client.get(url_for('main.index')).status_code == 200

但这一次,我收到一条错误消息:

RuntimeError: Attempted to generate a URL without the application context being pushed. This has to be executed when application context is available.

我尝试了很多不同的东西。我为这个项目的 virtualenvironment 更新了 pip 并更新了 pytestpytest-flask。但是 none 确实有效。

我通过了测试:

  • virtualenvironment 中删除了 pytestpytest-flask
  • 删除了我在系统范围内安装的它们。
  • 奇怪的是,我有一个名为 flask-pytest 的包,我删除了它(在 env 中)
  • 在系统范围内再次安装它们。
  • virtualenvironment 上再次安装它们。

我不知道这对测试有什么影响,但它确实有效。唯一不同的是我没有安装所说的 flask-pytest 东西。

您需要删除不正确的 client fixture(正确的请参见 pytest-flask 的实施)。

之后你需要在 virtualenv 里面安装 pytest-flaskpytest,你最好删除系统范围的以避免混淆。

之后你应该可以运行你的测试了。

我刚遇到同样的问题。解决方案是:

pip uninstall pytest-flask