用于使用参数元组进行测试的 Pytest 文本注释

Pytest text annotation for test with tuple of parameters

我正在为这类问题寻找更优雅的解决方案:

def ids(x):
    if isinstance(x, int):
        return str(x)
    elif isinstance(x, str):
        return x[0]


@pytest.mark.parametrize("number, string",
                         [
                             (1, "One"),
                             (2, "Two"),
                             (3, "Three")
                         ],
                         ids=ids)
def test_stupid(number, string):
    assert 0 == 1

此代码将生成测试名称:“1-O”、“2-T”、“3-T”。

问题是 pytest 对元组中的所有参数使用相同的函数,我不得不处理丑陋的 isinstance 调用。

有没有更好的方法解决这个问题?

我找到的唯一解决方案是使用 hook pytest_collection_modifyitems(session, config, items) 它可以访问参数值,并可用于更改测试名称。但它依赖于 pytest 函数 class 实现的内部细节,因此不是很健壮。

我为每个参数添加 pytest.mark 格式字符串和转换器。所有参数可选

@pytest.mark.parametrize("number, string",
                     [
                         (1, "One"),
                         (2, "Two"),
                         (3, "Three")
                     ])
@pytest.mark.params_format('number={number} string={string}',
                           number=lambda x: str(x),
                           string=lambda x: x[0])
def test_stupid(number, string):

然后添加到 conftest.py 挂钩实现以使用该标记参数并将格式化字符串添加到测试

def pytest_collection_modifyitems(session, config, items):
    for item in items:
        if not _get_marker(item, 'parametrize'):
            continue

        format_params_marker = _get_marker(item, 'params_format')
        if not format_params_marker:
            continue

        params = item.callspec.params.copy()
        param_formatters = format_params_marker.kwargs
        for param_name, presenter in param_formatters.iteritems():
            params[param_name] = presenter(params[param_name])

        params_names_ordered = [name for name in item.fixturenames if name in params]
        default_format = '-'.join(['{{{}}}'.format(param_name) for param_name in params_names_ordered])
        format_string = format_params_marker.args[0] if format_params_marker.args \
            else default_format
        item.name = '{func}[{params}]'.format(func=item.name.split('[')[0],
                                              params=format_string.format(**params))

def _get_marker(item, marker):
    return item.keywords._markers.get(marker, None)

结果看起来像这样

test_stupid[number=1 string=O] PASSED
test_stupid[number=2 string=T] PASSED
test_stupid[number=3 string=T] PASSED

传递字符串列表而不是可调用的 ids:

import pytest

PARAMS = [
    (1, "One"),
    (2, "Two"),
    (3, "Three")
]


def my_id(number, string):
    return '-'.join([str(number), string[0]])


@pytest.mark.parametrize("number, string",
                         PARAMS,
                         ids=[my_id(number, string) for number, string in PARAMS])
def test_stupid(number, string):
    assert 0 == 1