pytest:以DRY方式参数化夹具



使用Pytest fixture,我正在寻找一种将设置重写传递到应用程序fixture的方法,这样我就可以测试不同的设置,而不必定义不同的fixture。

在为Flask创建测试时,我使用的一种常见模式是初始化应用程序和数据库,如下所示。请注意,db设备将app设备硬编码为参数。

from myapp import create_app
@pytest.fixture
def app():
settings_override = {}  # By setting values here, I can pass in different Flask config variables
app = create_app(settings_override)
return app
@pytest.fixture
def db(app):
do_something_to_create_the_database(app)  # app needed for context
yield db

然后,许多测试可能会使用上面定义的固定装置,例如.

def test_my_application_1(db, app):
...
def test_my_application_2(db, app):
...

假设我想用不同的设置初始化应用程序fixture,假设我可以将这些设置传递到上面定义的create_app((函数中。在每次测试的基础上,如何连接appdb固定装置,以便我可以将设置覆盖传递到app固定装置?有没有一种方法可以在测试用例级别参数化夹具,这样我就可以将不同的设置传递给夹具?

# for this test, I want to pass the BAZ=True setting to the app fixture. 
def test_my_application_1(db, app):
...
# for this test, I want to pass FOO=BAR setting to the app fixture
def test_my_application_2(db, app):
...

我很感激你能给我的任何建议。

更新:使用@mrbean bremen的解决方案

感谢@MrBean Bremen提供的优雅解决方案。通过使用hasattr进行轻微修改,我能够扩展解决方案以接受参数重写或接受默认值。

@pytest.fixture(scope='function')
def app(request):
settings_override = {
'SQLALCHEMY_DATABASE_URI': "sqlite:///:memory:",
}
params = request.param if hasattr(request, 'param') else {}
return create_app({**settings_override, **params})

@pytest.fixture(scope='function')
def db(app):
with app.app_context():
....

def test_without_params(db, app):
...

@pytest.mark.parametrize("app", [{'DEBUG': True}], indirect=True)
def test_with_overrides(db, app):
...

您可以尝试将设置作为字典参数传递给fixture,如下所示:

import pytest
from myapp import create_app
@pytest.fixture
def app(request):
settings_override = {
'SQLALCHEMY_DATABASE_URI': "sqlite:///:memory:",
}
params = request.param if hasattr(request, 'param') else {}
return create_app({**settings_override, **params})
@pytest.fixture
def db(app):
do_something_to_create_the_database(app)
yield db
def test_my_application_no_override_params(db, app):
...
@pytest.mark.parametrize("app", [{'BAZ': True}], indirect=True)
def test_my_application_1(db, app):
...
@pytest.mark.parametrize("app", [{'FOO': 'BAR'}], indirect=True)
def test_my_application_2(db, app):
...

request对象允许fixture访问请求的测试上下文,并且可以用作任何fixture中的参数
pytest.mark.parametrize装饰器中的indirect=True参数将参数传递给request对象的可选param属性,因此这本质上是对fixture本身进行参数化。

更新:
我添加了@JoeJ提出的有用的添加(hasattr的使用(,这使得在没有额外参数的情况下使用测试成为可能。

最新更新