首页 > 解决方案 > Pytest:继承夹具参数

问题描述

我有一个固定装置,它充当一个开关来参数化测试以在两种状态(在线/离线)下运行。如果测试处于离线模式,这还会将自定义标记应用于测试。

@pytest.fixture(
    params=['online', pytest.param('offline', marks=pytest.mark.jira('388', '828', '833', '918'))]
)
def network(request):
    """ A switch parameter that parametrizes test for testing online and offline functionality. """
    return request.param

我有一个测试,如果测试也在离线模式下运行,我希望附加额外的参数。由于我没有使用network夹具,因此不包括标记(但我希望它们是)。

@pytest.mark.smoke
@pytest.mark.jira('387', '772', '1009')
@pytest.mark.parametrize('network', ['online', pytest.param('offline', marks=pytest.mark.jira('1036'))])
def test_crud(network):
    ...

我的问题是,如何将夹具标记和@pytest.mark.parametrize标记应用到测试中?

标签: pythonparameterspytestfixtures

解决方案


我通过添加解决了这个问题

def pytest_runtest_setup(item):
    if item.callspec.params.get('network') == 'offline':
        item.add_marker(pytest.mark.jira('388', '828', '833', '918'))

添加到每个测试中conftest.py并移除network夹具。@pytest.mark.parametrize('network', ...)


推荐阅读