pytest 测试报告生成方案有哪些?
在 pytest 中,除了 Allure 和 HTMLTestRunner,还有许多其他生成测试报告的方法和插件。以下是一些常用的方案及其特点:
1. pytest-html(官方推荐)
特点:轻量级、易集成,生成独立的 HTML 报告。
安装:
pip install pytest-html |
使用:
pytest --html=report.html --self-contained-html |
示例报告:
2. pytest-cov(代码覆盖率报告)
特点:统计测试覆盖率,支持 HTML、XML 等格式。
安装:
pip install pytest-cov |
使用:
pytest --cov=your_project --cov-report html |
示例报告:
3. pytest-xdist(分布式测试报告)
特点:并行执行测试,生成汇总报告。
安装:
pip install pytest-xdist |
使用:
pytest -n auto --html=report.html # 自动检测 CPU 核心数并行执行 |
4. pytest-reportlog(JSON 格式报告)
特点:生成结构化的 JSON 报告,便于后续处理。
使用:
pytest --reportlog=report.json |
5. pytest-sugar(美化控制台输出)
特点:美化测试执行过程的控制台输出,不生成文件报告。
安装:
pip install pytest-sugar |
示例输出:
6. pytest-rerunfailures(失败重试报告)
特点:自动重试失败的测试用例,并在报告中标记。
安装:
pip install pytest-rerunfailures |
使用:
pytest --reruns 3 --html=report.html # 失败重试 3 次 |
7. pytest-bdd(行为驱动开发报告)
特点:基于 Gherkin 语法,生成 BDD 风格的测试报告。
安装:
pip install pytest-bdd |
示例测试用例:
# features/login.feature Scenario: 登录成功 Given 用户已注册 When 用户输入正确的用户名和密码 Then 登录成功 |
8. pytest-json-report(JSON 报告)
特点:生成详细的 JSON 格式报告。
安装:
pip install pytest-json-report |
使用:
pytest --json-report --json-report-file=report.json |
9. pytest-testmon(增量测试报告)
特点:只运行变更的测试,生成增量报告。
安装:
pip install pytest-testmon |
使用:
pytest --testmon # 首次运行会记录状态 pytest --testmon # 后续只运行变更的测试 |
10. 自定义插件
特点:根据需求开发自定义报告插件。
示例代码:
# conftest.py import pytest @pytest.hookimpl(tryfirst=True, hookwrapper=True) def pytest_runtest_makereport(item, call): outcome = yield report = outcome.get_result()
if report.when == 'call': print(f"测试 {item.nodeid} 结果: {report.outcome}") |
对比与选择建议
插件 | 报告格式 | 特点 | 适用场景 |
pytest-html | HTML | 简单易用,适合基础报告 | 日常测试 |
allure-pytest | HTML | 功能丰富,支持步骤、附件 | 正式项目、对外展示 |
pytest-cov | HTML/XML | 代码覆盖率统计 | 质量保障、合规要求 |
pytest-xdist | 汇总报告 | 并行测试 | 大型项目、性能优化 |
pytest-bdd | BDD 风格 | 业务与技术对齐 | 敏捷开发、需求沟通 |
组合使用示例
同时生成 HTML 报告和覆盖率报告:
pytest --html=report.html --cov=your_project --cov-report html |
根据项目需求,你可以选择单一插件或组合使用多种插件来满足不同的报告需求。