[英]pytest test parameterization override
I am currently parametrizing all of my testcases using pytest_generate_tests
and this works well.我目前正在使用pytest_generate_tests
参数化我的所有测试用例,这很好用。
What I'd like to do now is override this behavior for a specific test.我现在想做的是为特定测试覆盖此行为。 If I try and use the pytest.mark.parametrize
decorator on the test itself, I get a ValueError: duplicate
error which is understandable as I'm now trying to parametrize the test in two places.如果我尝试在测试本身上使用pytest.mark.parametrize
装饰器, pytest.mark.parametrize
收到ValueError: duplicate
错误,这是可以理解的,因为我现在试图在两个地方对测试进行参数化。
Is there a way I can override the "default" parameterization for this one test case?有没有办法可以覆盖这个测试用例的“默认”参数化?
I can achieve this by doing something like the below but its a very hacky way to do it:我可以通过执行以下操作来实现这一点,但这是一种非常hacky的方法:
def pytest_generate_tests(metafunc):
fixture_modes = ['mode1', 'mode2']
if 'fixture' in metafunc.fixturenames:
fixture = metafunc.config.getoption('fixture')
if fixture:
fixture_modes = [fixture]
if metafunc.function.__name__ != 'func_to_skip':
metafunc.parametrize('fixture_mode', fixture_modes, indirect=True)
Is there a better way to do this?有一个更好的方法吗?
You can check whether a test defines its own parametrize marker for fixture_mode
, for example例如,您可以检查测试是否为fixture_mode
定义了自己的参数化标记
def pytest_generate_tests(metafunc):
fixture_modes = ['spam', 'eggs']
mark = metafunc.definition.get_closest_marker('parametrize')
if not mark or 'fixture_mode' not in mark.args[0]:
metafunc.parametrize('fixture_mode', fixture_modes, indirect=True)
Now, an explicit parametrization will override the default one:现在,显式参数化将覆盖默认参数化:
def test_spam(fixture_mode):
...
@pytest.mark.parametrize('fixture_mode', (1, 2, 3))
def test_eggs(fixture_mode):
...
test_spam
will get the default parametrization, test_eggs
a custom one: test_spam
将获得默认参数化, test_eggs
自定义参数化:
test_mod.py::test_spam[spam]
test_mod.py::test_spam[eggs]
test_mod.py::test_eggs[1]
test_mod.py::test_eggs[2]
test_mod.py::test_eggs[3]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.