gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 16:44:56 25 4
gpt4 key购买 nike

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

最佳答案

应用此 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 中调用一个简单的固定装置,它可以在将字符串传递给测试函数之前将它们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

关于python - Pytest 不在测试报告中显示元组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69653733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com