本文最后更新于:2024年1月14日 晚上

Pytest 执行过测试任务后我们需要查看整体测试情况,本文记录使用 pytest 生成测试报告的几种方法。

简介

  • Pytest 生成测试报告有几种方法,本文以 mtutils 库中的测试代码为例,分别尝试几种测试报告的使用

ResultLog

  • pytest 自带测试报告输出功能
  • 该功能在 pytest 6.1 以后的版本中被删除

使用方法

  • 在 pytest 命令中加入参数
1
--resultlog = path-to-log.txt

示例

1
pytest --resultlog=./log.txt test-dir

pytest-HTML

  • pytest-HTML 是一个 python 包,用于生成 pytest 测试结果的HTML报告

安装测试包

1
pip3 install pytest-html

使用方法

  • 在 pytest 命令中加入参数
1
--html=report.html

示例

1
pytest .\tests --html=report.html
  • 在浏览器打开该文件

JunitXML

  • 可以选择生成 XML 文件显示日志

使用方法

  • 在 pytest 命令中加入参数
1
--junitxml=./log.xml 

示例

1
pytest .\tests --junitxml=./log.xml 
  • 得到 xml 文件
1
<?xml version="1.0" encoding="utf-8"?><testsuites><testsuite name="pytest" errors="0" failures="0" skipped="0" tests="4" time="1.132" timestamp="2022-06-16T10:48:47.656215" hostname="VVD"><testcase classname="tests.test_utils.test_utils" name="test_get_list_from_list" time="0.001" /><testcase classname="tests.test_utils.test_utils" name="test_segment_intersection" time="0.001" /><testcase classname="tests.test_utils.test_utils" name="test_concat_generator" time="0.002" /><testcase classname="tests.test_utils.test_utils" name="test_get_mac_address" time="0.002" /></testsuite></testsuites>
  • 在 wps 中打开

allure

配置 java 环境

1
java --version

返回java 版本表示 java 环境配置成功

1
2
3
4
C:\Users\Administrator>java --version
java 18.0.1.1 2022-04-22
Java(TM) SE Runtime Environment (build 18.0.1.1+2-6)
Java HotSpot(TM) 64-Bit Server VM (build 18.0.1.1+2-6, mixed mode, sharing)

下载 allure

1
allure --version

正常返回 allure 版本表明配置成功

1
2
C:\Users\Administrator>allure --version
2.18.1

安装 allure

1
pip install allure-pytest 

使用方法

  • 生成 allure 报告内容,在 pytest 命令中加入参数
1
--alluredir=reports-dir
  • 生成报告内容后,用 allure 命令解析并查看报告
1
allure serve reports-dir

示例

  • 生成 allure 测试报告到 reports/allure 文件夹
1
pytest .\tests\  --alluredir=reports/allure
  • 显示 allure 报告
1
allure serve reports\allure
  • 报告效果

Coverage

  • Coverage 包可以辅助 pytest 查看代码运行级别的覆盖率并生成直观的 html 测试报告
  • pytest-cov 是pytest的一个插件,其本质是引用 python coverage 库用来统计代码覆盖率
  • 新版 pytest 默认已经自带,手动安装
1
pip install pytest-cover

使用方法

  • 在 pytest 命令中加入 --cov=.\code\ 参数,用于统计制定文件夹中的代码运行覆盖率,该参数指向的是被测试的代码,不是测试代码
  • 在 pytest 命令中加入 --cov-report=html 参数输出 html 报告

示例

  • mtutils 库中的测试代码为例
1
pytest --cov=.\lib\ .\tests\ --cov-report=html
  • 运行完成后生成了 htmlcov 文件夹,其中包含了覆盖率的 html 网页报告
  • 报告效果

  • 点击指定文件可以查看代码运行覆盖情况

  • 红线表明未被覆盖到的代码

参考资料



文章链接:
https://www.zywvvd.com/notes/coding/python/python-pytest/report/pytest-report/


“觉得不错的话,给点打赏吧 ୧(๑•̀⌄•́๑)૭”

微信二维码

微信支付

支付宝二维码

支付宝支付

Python 测试框架 pytest —— 生成测试报告
https://www.zywvvd.com/notes/coding/python/python-pytest/report/pytest-report/
作者
Yiwei Zhang
发布于
2022年6月16日
许可协议