当脚本文件命名为test_xx.py和用例使用test开头时,运行代码pycharm会自动识别到以unittest方式运行
如果要以pytest方式运行,需要修改设置默认的运行器:file->Setting->Tools->Python Integrated Tools->Testing->Default test runner->选择pytest
修改完成之后,删除所有的unittest运行配置
再次右键执行,查看都会显示pytest运行器
这种情况有两种情况:
查看参数是否拼写正确使用的插件是否安装 未安装可以使用 pip install pytest-repeat 进行安装,安装对应插件,在进行使用 问题三:parametrize 参数化时使用ids时控制台中文不能正常显示,显示为unicode编码样式(不是乱码)现象:参数用例描述有中文时,在控制台输出会显示unicode编码,中文不能正常显示
解决办法:在conftest.py文件使用pytest_collection_modifyitems 钩子函数,对输出的 item.name 和 item.nodeid 重新编码
再次执行,查看结果:
现象:HTML报告里面用例标题中文显示乱码
解决方案:修改pytest-html目录下的plugin.py里面test_id编码方式,修改路径为:../site-packages/pytest_html/plugin.py
修改代码为:
将 self.test_id = report.nodeid.encode("utf-8").decode("unicode_escape")
修改为: self.test_id = re.sub(r'(\u[sS]{4})', lambda x: x.group(1).encode("utf-8").decode("unicode-escape"), report.nodeid)
plugin.py 文件 140 行左右
class TestResult: def __init__(self, outcome, report, logfile, config): # self.test_id = report.nodeid.encode("utf-8").decode("unicode_escape") self.test_id = re.sub(r'(\u[sS]{4})', lambda x: x.group(1).encode("utf-8").decode("unicode-escape"), report.nodeid) if getattr(report, "when", "call") != "call": self.test_id = "::".join([report.nodeid, report.when]) self.time = getattr(report, "duration", 0.0) self.outcome = outcome self.additional_html = [] self.links_html = [] self.self_contained = config.getoption("self_contained_html") self.logfile = logfile self.config = config self.row_table = self.row_extra = None再次通过命令行生成HTML报告:pytest -v -s --html=reports.html --self-contained-html test_params.py
现象:每次运行脚本,都会将上一次日志覆盖
解决方案:修改日志写入模式,mode="a"
通过修改源码的写入方式可以保存所有执行日志,改成 a 模式修改文件位置 ../Lib/site-packages/_pytest/logging.py将 552行 的 self.log_file_handler = _FileHandler(log_file, mode="w", encoding="UTF-8")修改为:self.log_file_handler = _FileHandler(log_file, mode="a", encoding="UTF-8")问题六:pytest.ini 配置每天生成一个日志文件
解决方案:修改 pytest下的 logging 模块,主要是给文件名拼接一个日期信息
修改文件位置 ../Lib/site-packages/_pytest/logging.pypytest.ini 配置:
logging.py 修改:
代码
注意在logging文件import time模块 import timelog_file_s = log_file.partition('.')log_file = log_file_s[0]+time.strftime('_%Y_%m_%d', time.localtime(time.time()))+log_file_s[1]+log_file_s[2] 问题七:pytest.ini 文件存放路径问题
注意:pytest.ini 特别建议放到项目根目录,如果不放在根目录,注意里面 testpaths、norecursedirs 和log_file 与路径相关的参数配置
pytest.ini 里面配置路径查找方法,已 pytest.ini 文件所在路径为根路径,继续往下查找
以上为内容纯属个人理解,如有不足,欢迎各位大神指正,转载请注明出处!
如果觉得文章不错,欢迎关注微信公众号,微信公众号每天推送相关测试技术文章