简体   繁体   中英

pytest test parameterization override

I am currently parametrizing all of my testcases using pytest_generate_tests and this works well.

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.

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:

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

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_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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM