当我们对测试用例进行参数化时,使用@pytest.mark.parametrize的ids参数自定义测试用例的标题,当标题中有中文时,控制台和测试报告中会出现Unicode编码问题,这看起来特别像乱码,我们想让中文正常展示出来,需要用到pytest框架的钩子函数pytest_collection_modifyitems。
先看问题:
# file_name: test_parametrize.py
import pytest
def return_user():
return [('lwjnicole', '12345'), ('nicole', '123111')]
class Test_D:
@pytest.mark.parametrize("username,password",
return_user(),
ids=[
"输入正确的用户名、密码,登录成功",
"输入错误的用户名、密码,登录失败"
])
def test_login(self, username, password):
print("username = {}, password = {}".format(username, password))
assert username == "lwjnicole"
if __name__ == '__main__':
pytest.main(['-s', 'test_parametrize.py'])
编辑器中运行上面代码的结果:

从上面的结果中可以看到用例的标题中文展示为Unicode编码。
使用钩子函数pytest_collection_modifyitems解决:
items ?是一个存储?item ?对象的列表,?item ?对象中有两个属性:一个是测试用例的路径?nodeid ?,另一个是测试用例的用例名?name
在项目的根目录下,新建 conftest.py 文件,然后添加如下代码:
# file_name: conftest.py
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")
然后再次执行下测试用例,运行结果:

从上面的结果中可以看到用例的标题以中文正常展示了,问题得到解决。
我这里给你们分享一下我所积累和真理的文档和学习资料有需要是领取就可以了
1、学习思路和方法
这个大纲涵盖了目前市面上企业百分之99的技术,这个大纲很详细的写了你该学习什么内容,企业会用到什么内容。总共十个专题足够你学习

2、想学习却无从下手,该如何学习?
这里我准备了对应上面的每个知识点的学习资料、可以自学神器,已经项目练手。


3、软件测试/自动化测试【全家桶装】学习中的工具、安装包、插件....



4、有了安装包和学习资料,没有项目实战怎么办,我这里都已经准备好了往下看

最后送上一句话: 世界的模样取决于你凝视它的目光,自己的价值取决于你的追求和心态,一切美好的愿望,不在等待中拥有,而是在奋斗中争取。 如果我的博客对你有帮助、如果你喜欢我的文章内容,请 “点赞” “评论” “收藏” 一键三连哦!

|