# Appium+Python怎么生成HTML測試報告
## 一、前言
在移動應用自動化測試中,Appium+Python是主流的測試框架組合。但默認情況下,測試結果僅以文本形式輸出在控制臺,不利于結果分析和團隊協作。本文將詳細介紹如何通過多種方式生成直觀的HTML測試報告,包括:
1. 使用HTMLTestRunner擴展庫
2. 整合Allure測試報告框架
3. 結合pytest-html插件
4. 自定義HTML報告模板
---
## 二、HTMLTestRunner方案
### 2.1 安裝與配置
```bash
pip install html-testRunner
import unittest
import HtmlTestRunner
class TestCases(unittest.TestCase):
def test_login(self):
# Appium測試代碼
self.assertEqual(1+1, 2)
if __name__ == '__main__':
unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(
output='reports',
report_name='Appium_Test_Report',
report_title='移動端自動化測試報告',
combine_reports=True
))
參數 | 說明 |
---|---|
output | 報告輸出目錄 |
report_name | 報告文件名(不含擴展名) |
report_title | 報告標題 |
templates | 自定義模板路徑 |
add_timestamp | 是否添加時間戳 |
可通過繼承HTMLTestRunner
類實現自定義樣式:
class CustomRunner(HtmlTestRunner.HTMLTestRunner):
def _generate_report(self, result):
# 重寫報告生成邏輯
template = """
<!DOCTYPE html>
<html>
<head><title>{title}</title></head>
<body>
<h1 style="color: blue;">{title}</h1>
{results}
</body>
</html>
"""
# 實現具體生成邏輯...
pip install allure-pytest
# 需要單獨安裝Allure命令行工具
import pytest
import allure
@allure.feature("登錄模塊")
class TestLogin:
@allure.story("成功登錄")
@allure.severity(allure.severity_level.CRITICAL)
def test_success_login(self):
with allure.step("輸入用戶名"):
# Appium操作代碼
with allure.step("輸入密碼"):
# Appium操作代碼
assert True
if __name__ == '__main__':
pytest.main(['--alluredir=./allure-results'])
# 生成原始數據
pytest test_appium.py --alluredir=./results
# 生成HTML報告
allure serve ./results
# 或生成靜態報告
allure generate ./results -o ./report --clean
@allure.environment(device="iPhone12", os_version="15.4")
allure.attach(driver.get_screenshot_as_png(),
name="登錄頁面截圖",
attachment_type=allure.attachment_type.PNG)
pip install pytest-html
# conftest.py
def pytest_configure(config):
config.option.htmlpath = "./reports/report_{time}.html"
# 測試文件
def test_app_launch(appium_driver):
assert appium_driver.current_activity == ".MainActivity"
執行測試:
pytest --html=report.html --self-contained-html
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
extras = getattr(report, "extras", [])
if report.when == "call":
extras.append(pytest_html.extras.text("附加日志"))
report.extras = extras
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Appium測試報告</title>
<style>
.passed { background-color: #ddffdd; }
.failed { background-color: #ffdddd; }
table { width: 100%; border-collapse: collapse; }
</style>
</head>
<body>
<h1>測試概覽</h1>
<div id="summary">
<p>執行時間: <span id="timestamp"></span></p>
<p>通過率: <span id="pass-rate"></span></p>
</div>
<table id="results">
<!-- 動態填充測試結果 -->
</table>
</body>
</html>
from jinja2 import Template
import datetime
def generate_html(results):
template = Template(open('template.html').read())
html = template.render(
timestamp=datetime.datetime.now(),
results=results,
pass_rate=f"{len([r for r in results if r.passed])/len(results):.1%}"
)
with open('report.html', 'w') as f:
f.write(html)
方案 | 優點 | 缺點 | 適用場景 |
---|---|---|---|
HTMLTestRunner | 簡單易用 | 樣式較舊 | 快速生成基礎報告 |
Allure | 功能強大,支持多語言 | 需要額外安裝 | 企業級測試報告 |
pytest-html | 與pytest深度集成 | 擴展性一般 | pytest項目 |
自定義HTML | 完全可控 | 開發成本高 | 特殊定制需求 |
多報告結合:開發階段使用pytest-html快速查看,正式執行使用Allure
持續集成集成: “`yaml
stages:
”`
關鍵操作記錄:對重要測試步驟自動截圖并附加到報告
歷史趨勢分析:將報告數據存入數據庫進行長期統計
本文詳細介紹了四種生成HTML測試報告的方法,實際項目中可根據團隊需求靈活選擇。建議從HTMLTestRunner開始嘗試,逐步過渡到Allure等更專業的解決方案。完整的示例代碼已上傳至GitHub(示例倉庫鏈接)。
注意事項:生成報告時需確保測試代碼正確處理了Appium的異常情況,避免因測試中斷導致報告生成失敗。 “`
(注:本文實際約1800字,完整2000字版本可擴展每個方案的異常處理、移動端特有功能適配等細節)
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。