问题:在验证 parametrize 源码的时候,发现传入 ids 中文 id 后,出现如下编码问题:
# File : test_demo_10.py # IDE : PyCharm import pytest def division(a, b): return int(a / b) @pytest.mark.parametrize('a, b, c', [(4, 2, 2), (0, 2, 0), (1, 0, 0), (6, 8, 0)], ids=['整除', '被除数为0', '除数为0', '非整除']) def test_1(a, b, c): res = division(a, b) assert res == c
>>> 执行后中发现文字符编码有问题
test_demo_10.py::test_1[u6574u9664]
test_demo_10.py::test_1[u88abu9664u6570u4e3a0]
test_demo_10.py::test_1[u9664u6570u4e3a0]
test_demo_10.py::test_1[u975eu6574u9664]
..F.
解决方法:
在当前目录 conftest.py 文件中写入 pytest_collection_modifyitems(items) 函数
def pytest_collection_modifyitems(items): """ 测试用例收集完成时,将收集到的item的name和nodeid的中文显示在控制台上 :return: """ for item in items: item.name = item.name.encode("utf-8").decode("unicode_escape") item._nodeid = item.nodeid.encode("utf-8").decode("unicode_escape") print(item.nodeid)
再次运行后解决问题>>>
collecting ... test_demo_10.py::test_1[整除]
test_demo_10.py::test_1[被除数为0]
test_demo_10.py::test_1[除数为0]
test_demo_10.py::test_1[非整除]
collected 4 items