Pytest参数化测试报告中tuple期望值不显示,如何配置展示实际值
Pytest参数化测试显示tuple参数值的实现方案
该需求可以直接实现,共有三种常用实现方式:
方案1:通过parametrize的ids参数自定义标识
这是最通用的方案,无需修改全局配置,仅需要给参数化装饰器添加ids参数即可,修改后的代码示例如下:
@pytest.mark.parametrize( 'test_input, expected', [ ('12:00 AM', (0, 0)), ('12:01 AM', (0, 1)), ('11:59 AM', (11, 58)) ], # 自动将所有参数转为字符串作为用例标识 ids=lambda x: str(x) ) def test_params(test_input, expected): assert time_calculator.convert_12h_to_24(test_input) == expected
修改后运行输出会直接展示tuple的实际取值:
test_time_converter.py::test_params[12:00 AM-(0, 0)] PASSED test_time_converter.py::test_params[12:01 AM-(0, 1)] PASSED test_time_converter.py::test_params[11:59 AM-(11, 58)] FAILED
方案2:通过pytest.param单独指定单条用例标识
如果需要给不同用例自定义备注,可以用pytest.param为每条用例单独设置id:
@pytest.mark.parametrize( 'test_input, expected', [ pytest.param('12:00 AM', (0, 0), id="零点边界测试"), pytest.param('12:01 AM', (0, 1), id="凌晨1分测试"), pytest.param('11:59 AM', (11, 58), id="上午边界测试"), ] ) def test_params(test_input, expected): assert time_calculator.convert_12h_to_24(test_input) == expected
方案3:修改全局配置自动展示所有参数值
不需要修改测试代码,在项目根目录的pytest配置文件(pytest.ini/pyproject.toml任选其一)添加配置即可全局生效:
- 对于pytest.ini文件:
[pytest] disable_test_id_escaping_and_forfeit_all_rights_to_community_support = True
- 对于pyproject.toml文件:
[tool.pytest.ini_options] disable_test_id_escaping_and_forfeit_all_rights_to_community_support = true
开启配置后,pytest会自动将所有非字符串类型的参数转为字符串展示,不会再生成expected0这类占位标识。
内容的提问来源于stack exchange,提问作者algot
相关产品推荐
相关产品推荐

