Pytest 不在测试报告中显示元组值

Pytest does not display tuple values in test report

我有一个参数化的 pytest 测试并使用元组作为预期值。

如果我 运行 测试,这些值不会显示,自动生成的值 (expected0...expectedN) 会显示在报告中。

是否可以在输出中显示元组值?

测试样本:

@pytest.mark.parametrize('test_input, expected',
                         [
                             ('12:00 AM', (0, 0)),
                             ('12:01 AM', (0, 1)),
                             ('11:59 AM', (11, 58))
                         ])
def test_params(test_input, expected):
    assert time_calculator.convert_12h_to_24(test_input) == expected

输出:

test_time_converter.py::test_params[12:00 AM-expected0] PASSED
test_time_converter.py::test_params[12:01 AM-expected1] PASSED
test_time_converter.py::test_params[11:59 AM-expected2] FAILED

应用此 ,您可以自定义 ids 属性:

PARAMS = [
    ('12:00 AM', (0, 0)),
    ('12:01 AM', (0, 1)),
    ('11:59 AM', (11, 58))
]

def get_ids(params):
    return [f'{a}-{b}' for a, b in params]

@pytest.mark.parametrize('test_input, expected', PARAMS, ids=get_ids(PARAMS))
def test_params_format(test_input, expected):
    assert expected != (11, 58)

另一种选择是将元组定义为字符串并使它们成为 indirect parameters,虽然不是那么优雅。这会在 conftest.py 中调用一个简单的固定装置,它可以 eval 将字符串返回到元组,然后再将它们传递给测试函数。

@pytest.mark.parametrize(
    'test_input, expected',
    [
        ('12:00 AM', '(0, 0)'),
        ('12:01 AM', '(0, 1)'),
        ('11:59 AM', '(11, 58)')
    ],
    indirect=["expected"])
def test_params(test_input, expected):
    assert expected != (11, 58)

conftest.py:

from ast import literal_eval

@pytest.fixture
def expected(request):
    return literal_eval(request.param)

literal_eval is more secure than eval. See here.

输出(两种解决方案):

test_print_tuples.py::test_params[12:00 AM-(0, 0)] PASSED
test_print_tuples.py::test_params[12:01 AM-(0, 1)] PASSED 
test_print_tuples.py::test_params[11:59 AM-(11, 58)] FAILED