溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Appium+Python怎么生成html測試報告

發布時間:2022-04-25 10:42:19 來源:億速云 閱讀:254 作者:iii 欄目:大數據
# Appium+Python怎么生成HTML測試報告

## 一、前言

在移動應用自動化測試中,Appium+Python是主流的測試框架組合。但默認情況下,測試結果僅以文本形式輸出在控制臺,不利于結果分析和團隊協作。本文將詳細介紹如何通過多種方式生成直觀的HTML測試報告,包括:

1. 使用HTMLTestRunner擴展庫
2. 整合Allure測試報告框架
3. 結合pytest-html插件
4. 自定義HTML報告模板

---

## 二、HTMLTestRunner方案

### 2.1 安裝與配置

```bash
pip install html-testRunner

2.2 基礎用法示例

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
    ))

2.3 核心參數說明

參數 說明
output 報告輸出目錄
report_name 報告文件名(不含擴展名)
report_title 報告標題
templates 自定義模板路徑
add_timestamp 是否添加時間戳

2.4 高級定制

可通過繼承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>
        """
        # 實現具體生成邏輯...

三、Allure報告方案

3.1 環境準備

pip install allure-pytest
# 需要單獨安裝Allure命令行工具

3.2 測試代碼改造

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'])

3.3 生成報告

# 生成原始數據
pytest test_appium.py --alluredir=./results

# 生成HTML報告
allure serve ./results

# 或生成靜態報告
allure generate ./results -o ./report --clean

3.4 報告增強技巧

  1. 添加設備信息:
@allure.environment(device="iPhone12", os_version="15.4")
  1. 附加截圖:
allure.attach(driver.get_screenshot_as_png(), 
             name="登錄頁面截圖",
             attachment_type=allure.attachment_type.PNG)

四、pytest-html方案

4.1 快速開始

pip install pytest-html

4.2 基礎使用

# 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

4.3 報告定制

@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

五、自定義HTML報告

5.1 基本結構設計

<!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>

5.2 Python生成邏輯

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 完全可控 開發成本高 特殊定制需求

七、最佳實踐建議

  1. 多報告結合:開發階段使用pytest-html快速查看,正式執行使用Allure

  2. 持續集成集成: “`yaml

    Jenkins配置示例

    stages:

    • stage: Test steps:
      • sh “pytest –alluredir=./results”
      • allure serve ./results

    ”`

  3. 關鍵操作記錄:對重要測試步驟自動截圖并附加到報告

  4. 歷史趨勢分析:將報告數據存入數據庫進行長期統計


八、總結

本文詳細介紹了四種生成HTML測試報告的方法,實際項目中可根據團隊需求靈活選擇。建議從HTMLTestRunner開始嘗試,逐步過渡到Allure等更專業的解決方案。完整的示例代碼已上傳至GitHub(示例倉庫鏈接)。

注意事項:生成報告時需確保測試代碼正確處理了Appium的異常情況,避免因測試中斷導致報告生成失敗。 “`

(注:本文實際約1800字,完整2000字版本可擴展每個方案的異常處理、移動端特有功能適配等細節)

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女