正在开发一个计划用于多个项目的django可重用软件包。我已经使用pytest来构建测试套件,我在pytest中使用参数化帮助来运行多个配置的单个测试。
然而,我想使用不同的设置组合运行我的所有测试
available_backends = [
'django_profile.auth_backends.drf.RestFramework',
'django_profile.auth_backends.kong.Kong',
]
def pytest_generate_tests(metafunc):
# if 'stringinput' in metafunc.fixturenames:
if 'auth_backend' in metafunc.fixturenames:
metafunc.parametrize(
'auth_backend',
available_backends
)
@pytest.fixture(params=['auth_backend', ])
def auth_backend(request, settings):
settings.DJANGO_PROFILE_AUTH_BACKEND = request.auth_backend
return settings
我尝试了上述方法,但这也意味着我必须在每个测试用例中添加auth_backend
,我不相信这是理想的。任何人都可以推荐一种方法让我使用不同的设置组合运行我的所有测试?
此致
答案 0 :(得分:2)
请你试试:
https://docs.pytest.org/en/latest/fixture.html#parametrizing-fixtures
如果没有,你能尝试使用它吗?
@pytest.fixture(scope='session', params=[
'django_profile.auth_backends.drf.RestFramework',
'django_profile.auth_backends.kong.Kong',
])
def auth_backend(request, settings):
settings.DJANGO_PROFILE_AUTH_BACKEND = request.param
yield settings
答案 1 :(得分:1)
您可以覆盖每个测试的设置。
django文档: Overriding settings
例如:
from django.test import TestCase
class LoginTestCase(TestCase):
def test_login(self):
# First check for the default behavior
response = self.client.get('/sekrit/')
self.assertRedirects(response, '/accounts/login/?next=/sekrit/')
# Then override the LOGIN_URL setting
with self.settings(LOGIN_URL='/other/login/'):
response = self.client.get('/sekrit/')
self.assertRedirects(response, '/other/login/?next=/sekrit/')
或用于装饰器
from django.test import TestCase, override_settings
class LoginTestCase(TestCase):
@override_settings(LOGIN_URL='/other/login/')
def test_login(self):
response = self.client.get('/sekrit/')
self.assertRedirects(response, '/other/login/?next=/sekrit/')
答案 2 :(得分:0)
最终,我找到了一种方法,可以将不同的设置传递给所有测试,而无需在每个测试中指定夹具。以下是一个工作示例
# conftest.py
@pytest.yield_fixture(params=available_backends)
def settings(request, settings):
if request.param not in available_backends:
raise ValueError('auth_backend {} not implemented.'.format(request.param))
wrapper = SettingsWrapper()
settings.DJANGO_PROFILE_AUTH_BACKEND = request.param
yield wrapper
wrapper.finalize()
# setup.cfg
usefixtures = settings