Is it possible to skip a test generated from multiple @pytest.mark.parametrize lines?

孤街醉人 提交于 2021-02-11 14:41:42

问题


I have a pytest test function with multiple @pytest.mark.parametrize lines. The values for each parameterised variable can take either 0 or 1. Some of the combination generated cannot happen and should be skipped i.e. in my example when subcontact takes the value 0 and when fast track takes the value 1, it should be skipped. Is it possible to achieve this with the multiple @pytest.mark.parametrize fixture?

I attempted this with the code below but no tests were reported as skipped when I ran the tests.

@pytest.mark.parametrize('prospect', [0, 1])
@pytest.mark.parametrize('client', [0, 1])
@pytest.mark.parametrize('subcontact', [0, 1])
@pytest.mark.parametrize('default', [0, 1])
@pytest.mark.parametrize('primary_contact', [0, 1])
@pytest.mark.parametrize('fast_track', [0, pytest.param(1, marks=pytest.mark.skipif('subcontact' == 0,
                                                                                    reason='Cannot happen'))])
def test_prospect_registration(prospect, client, subcontact, default,
                               primary_contact,
                               fast_track):
    pass

回答1:


The easiest possibililty is probably to skip the specific test inside the test body:

...
def test_prospect_registration(prospect, client, subcontact, default,
                               primary_contact,
                               fast_track):
    if fast_track == 1 and subcontact == 0:
        pytest.skip('Cannot happen')
    ...

You could also do the skipping in a fixture based on th test name (the parameters are listed from the last mark.parametrize decorator up):

import re

@pytest.fixture(autouse=True)
def skip_unwanted(request):
    if re.match(r'test_prospect_registration\[1-.*-.*-.0.*-.*\]', item.name)
        pytest.skip('Cannot happen')

or you could do the same in pytest_collection_modifyitems:

conftest.py

def pytest_collection_modifyitems(config, items):
    for item in items:
        if re.match(r'test_prospect_registration\[1-.*-.*-.0.*-.*\]', item.name):
            item.add_marker('skip')


来源:https://stackoverflow.com/questions/63256204/is-it-possible-to-skip-a-test-generated-from-multiple-pytest-mark-parametrize-l

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!