
当编写的代码越来越多,所i有的用例都放在 test_cases 目录,如果要执行所有的用例。 可以在这个目录上右键执行,执行test_cases 下所有的文件。
运行,可以看到执行的结果。
执行了test_cases下面所有的用例。
通过python调用pytest方法来执行
如果要执行指定的文件,也可以通过调用pytest模块中提供的方法来执行。
import pytestif __name__ == '__main__':# 通过调用pytest 内置的方法来运行所有的测试用例pytest.main([r'test_cases\test_data_case.py',r'test_cases\test_others.py'])
只运行r’test_cases\test_data_case.py’,r’test_cases\test_others.py’ 这两个文件中的测试用例。
默认生成的测试报告在命令行中,显示也比较简单,当关闭pycharm的时候 生成的报告也没有了。
pytest-html 测试报告
参考地址: https://pytest-html.readthedocs.io/en/latest/
pytest-html 是pytest的一个插件,可以用来生成html测试报告。
安装插件

打开设置,找到python解释器,点击【+】 进行安装
搜 pytest-html 进行安装
安装成功之后,可以看到对应的信息
使用
根据官网的使用说明
https://pytest-html.readthedocs.io/en/latest/user_guide.html
直接在代码中添加这两个选项即可。
import pytestif __name__ == '__main__':# 通过调用pytest 内置的方法来运行所有的测试用例pytest.main([r'test_cases\test_data_case.py',r'test_cases\test_others.py','--html=report.html','--self-contained-html'])
再次运行,可以看到执行结果。
生成了html 报告文件。打开文件可以看到
打开报告,可以看到。
改进
每次生成的测试报告最好放到一个单独的目录,比如放在 reports 目录下。
import pytestimport osp1 = os.path.abspath(__file__)p2 = os.path.dirname(p1)reports = os.path.join(p2,'reports')# 创建目录if not os.path.exists(reports):os.mkdir(reports)htmlfile = os.path.join(reports,'report.html')if __name__ == '__main__':# 通过调用pytest 内置的方法来运行所有的测试用例pytest.main([r'test_cases\test_data_case.py',r'test_cases\test_others.py',f'--html={htmlfile}','--self-contained-html'])
执行完成之后,可以看到文件已经生成在 reports 目录下。
每次运行 都会将之前的报告覆盖掉,可以想办法将报告文件 每次生成的时候给一个唯一的文件名,这样的话就不会重复。
使用时间模块,可以将每次运行的时候记录当前时间,以时间命名。
import pytestimport osimport time # 日期时间模块p1 = os.path.abspath(__file__)p2 = os.path.dirname(p1)reports = os.path.join(p2,'reports')# 创建目录if not os.path.exists(reports):os.mkdir(reports)#转换当前时间 %Y 年 %m 月 %d 日 %H 小时 %M 分钟 %S 秒current_time = time.strftime("%Y_%m_%d_%H_%M_%S")htmlfile = os.path.join(reports,f'report_{current_time}.html')if __name__ == '__main__':# 通过调用pytest 内置的方法来运行所有的测试用例pytest.main([r'test_cases\test_data_case.py',r'test_cases\test_others.py',f'--html={htmlfile}','--self-contained-html'])
执行完成之后,可以看到效果,可以看到之前的历史执行记录。
