在 pytest 中配对参数化和固定装置

Pairing parameterisation and fixtures in pytest

我有一个 python 包,用于检查存储在 Excel 文件中的数据格式。有各种不同的工作表可以检查不同的格式,在我的 pytest 设置中,我有一些示例文件,预计会抛出不同类型的错误或通过。因为这些文件在多个测试中重复使用,所以我将它们作为固定装置放在 conftest.py:

@pytest.fixture(scope='module', params=['good', 'bad'])
def example_excel_files(request):

    if request.param == 'good':
        wb = openpyxl.load_workbook(good_file_path, read_only=True)
        return wb
    elif request.param == 'bad':
        wb = openpyxl.load_workbook(bad_file_path, read_only=True)
        return wb

我想要做的是在不同的测试中使用这个夹具,但指定特定测试的预期值是什么作为测试的参数化,以将测试信息与测试一起保存。举个例子:

@pytest.mark.parametrize(
    'expected_values',
    [(0, 20), 
     (30, 20)
      ]
)
def test_this_function(example_excel_files, expected_values):

    n_errors, n_rows = expected_values
    output = this_function(example_excel_files['worksheet'])

    assert output.n_errors == n_errors
    assert output.n_rows == n_rows

就目前而言,这会为每个夹具参数值重复每个参数化(第 1 行好,第 2 行好,第 1 行不好,等等)。我想要做的是将夹具和参数化配对,以便使用 good 检查第一组示例,使用 bad 检查第二组示例。有没有简单的方法?

你可以在这里使用indirect parametrization to add the fixture parameters to the test parameters instead of directly providing them in the fixture. Specifically, you can use indirect parametrization on particular arguments

为此,您必须从夹具中删除参数并将它们作为间接参数添加到参数化中,例如类似于:

@pytest.fixture(scope='module')  # params removed
def example_excel_files(request):
    if request.param == 'good':
        wb = openpyxl.load_workbook(good_file_path, read_only=True)
        return wb
    elif request.param == 'bad':
        wb = openpyxl.load_workbook(bad_file_path, read_only=True)
        return wb


@pytest.mark.parametrize(
    'example_excel_files, expected_values',
    [('good', (0, 20)), ('bad', (30, 20))],  # added params
    indirect=['example_excel_files']  # take actual params from fixture
)
def test_this_function(example_excel_files, expected_values):
    n_errors, n_rows = expected_values
    output = this_function(example_excel_files['worksheet'])

    assert output.n_errors == n_errors
    assert output.n_rows == n_rows

这样,您直接将示例文件与各自的预期结果配对,并且每对只会得到一个测试。