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

2024-05-28 18:36:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个参数化的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

Tags: pytestinput参数timepytestparamsam
1条回答
网友
1楼 · 发布于 2024-05-28 18:36:12

应用此answer,可以自定义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中调用一个简单的fixture,该fixture可以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

相关问题 更多 >

    热门问题