Pytest之重运行及生成测试报告
以下主要介绍Pytest的重运行及生成测试报告。
重运行
在做UI自动化,如Selenuim或者Appium时,遇到某些元素未能及时显示,导致点击失败,如果加上重跑,那么将有效提高报告的准确性。
在Pytest中,可以使用pytest-rerunfailures
用来失败用例重跑。
安装pytest-rerunfailures
安装命令:
pip install pytest-rerunfailures
使用说明
@pytest.mark.flaky(reruns=重试次数, reruns_delay=次数之间的延时设置(单位:秒))
举个栗子
重试次数test_demo.py
1 2 3 4 | import pytest @pytest .mark.flaky(reruns = 2 ) def test_demo(): assert 3 = = 4 |
运行结果为:
指定重运行等待时间:
1 2 3 4 | import pytest @pytest .mark.flaky(reruns = 2 ,reruns_delay = 2 ) def test_demo(): assert 3 = = 4 |
运行结果为:
生成测试报告
pytest-html生成报告
pytest使用pytest-html
插件生成测试报告。
① 安装pytest-html
安装命令:
pip install pytest-html
② 举个栗子
现有用例如下:
test_demo.py
1 2 3 4 5 | import pytest @pytest .mark.flaky(reruns = 2 ,reruns_delay = 2 ) def test_demo(): assert 3 = = 4 |
test_demo1.py
1 2 3 4 5 | class TestDemo: def test_demo01( self ): print ( "这是test_demo01" ) def test_demo02( self ): print ( "这是test_demo02" ) |
命令行输入:pytest --html=report.html
运行之后,会生成report.html,用浏览器打开report.html,如下:
allure生成报告
用pytest-html生成的报告稍微简单和丑了一点,我们可以使用更强大的工具allure
,allure测试报告框架帮助你轻松实现"高大上"报告展示。
01 安装allure
①从github上下载allure,下载传送门为:
https://github.com/allure-framework/allure2/releases
如下所示,选择”Download“下载即可:
② 下载完后,解压到项目根目录下。
③ 安装allure插件
安装命令:
pip install allure-pytest
④ 添加环境变量:将allure-2.13.5\bin的目录路径添加到环境变量。
02 举个栗子
① 现有用例如下:
test_demo.py
1 2 3 4 5 | import pytest @pytest .mark.flaky(reruns = 2 ,reruns_delay = 2 ) def test_demo(): assert 3 = = 4 |
test_demo1.py
1 2 3 4 5 | class TestDemo: def test_demo01( self ): print ( "这是test_demo01" ) def test_demo02( self ): print ( "这是test_demo02" ) |
② 在项目根目录下新建目录report。
③ 在命令行输入:pytest -s -q --alluredir ./report,在report目录下会生成一些json格式的。
④ 在report目录下,新建目录html,用于存放html报告。
⑤ 命令行输入allure generate ./report -o ./report/html,生成了最终的html报告。
⑥用浏览器打开index.html文件,效果如下:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?