[英]test flask app using pytest can't find fixture client
我有一個簡單的燒瓶應用程序,我想使用 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.
我嘗試了很多不同的東西。 我更新pip
為這個項目的virtualenvironment
,並更新了pytest
和pytest-flask
。 但沒有一個工作。
我能夠通過以下測試:
virtualenvironment
pytest-flask
刪除了pytest
和pytest-flask
。flask-pytest
的包我刪除了它(在env
)virtualenvironment
再次安裝它們。 我不知道這與測試有什么關系,但它有效。 唯一不同的是我沒有安裝所說的flask-pytest
東西。
您需要刪除不正確的client fixture
(請參閱pytest-flask
的實現以獲得正確的)。
之后您需要在virtualenv
pytest-flask
安裝pytest-flask
和pytest
,您最好刪除系統范圍內的以避免混淆。
之后,您應該能夠運行您的測試。
我只是有同樣的問題。 解決方案是:
pip uninstall pytest-flask
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.