在 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 |
根據項目需求,你可以選擇單一插件或組合使用多種插件來滿足不同的報告需求。