使用Python + pytest + Selenium + Allure框架,实现测试用例执行完成后自动发送测试报告和结果到飞书、企业微信和钉钉。方案包括完整的代码示例、分步解释和配置说明。

整体框架设计

  • 核心工具
    • pytest:测试运行器,管理测试用例执行和钩子(hook)。
    • Selenium:Web UI自动化驱动,模拟浏览器操作。
    • Allure:生成美观的HTML测试报告,支持历史数据和图表。
    • 消息平台集成:通过Webhook API发送消息到飞书、企业微信和钉钉。
  • 工作流程
    1. 使用pytest运行测试用例,生成Allure原始报告数据。
    2. 在pytest会话结束时,自动生成Allure HTML报告。
    3. 解析报告获取测试摘要(如总用例数、通过率)。
    4. 调用各平台Webhook发送摘要和报告链接。
  • 项目结构
    project/
    ├── conftest.py              # pytest配置文件,定义钩子和消息发送逻辑
    ├── test_example.py          # 示例测试用例文件
    ├── utils/                   # 工具类目录
    │   ├── message_sender.py    # 消息发送函数实现
    │   └── report_parser.py     # 报告解析函数
    ├── allure-report/           # Allure生成的HTML报告(自动创建)
    └── requirements.txt         # 依赖库列表
    

依赖安装

首先,安装所有必需的Python库。创建 requirements.txt 文件:

pytest
selenium
allure-pytest
requests
pytest-html
webdriver-manager

运行命令安装:

pip install -r requirements.txt

详细代码实现

1. 测试用例文件 (test_example.py)

这是一个简单的Selenium测试用例示例,测试百度搜索功能。使用pytest风格编写。

import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

@pytest.fixture(scope="function")
def driver():
    # 初始化Chrome浏览器
    service = Service(ChromeDriverManager().install())
    driver = webdriver.Chrome(service=service)
    driver.maximize_window()
    yield driver
    driver.quit()  # 测试结束后关闭浏览器

def test_baidu_search(driver):
    """测试百度搜索功能"""
    driver.get("https://www.baidu.com")
    search_box = driver.find_element(By.ID, "kw")
    search_box.send_keys("pytest selenium")
    search_box.submit()
    assert "pytest" in driver.title, "页面标题未包含'pytest'"
2. pytest配置文件 (conftest.py)

这是核心文件,定义钩子函数,在测试结束后生成Allure报告并发送消息。

import pytest
import subprocess
import os
from utils.report_parser import parse_allure_report
from utils.message_sender import send_to_feishu, send_to_wecom, send_to_dingtalk

def pytest_sessionfinish(session, exitstatus):
    """pytest会话结束钩子:生成报告并发送消息"""
    # 生成Allure报告
    allure_results_dir = "allure-results"
    allure_report_dir = "allure-report"
    if not os.path.exists(allure_results_dir):
        os.makedirs(allure_results_dir)
    
    # 生成HTML报告
    subprocess.run(f"allure generate {allure_results_dir} -o {allure_report_dir} --clean", shell=True)
    
    # 解析报告获取摘要
    summary = parse_allure_report(allure_report_dir)
    
    # 发送消息到各平台
    webhook_urls = {
        "feishu": "YOUR_FEISHU_WEBHOOK_URL",  # 替换为实际飞书Webhook URL
        "wecom": "YOUR_WECOM_WEBHOOK_URL",    # 替换为实际企业微信Webhook URL
        "dingtalk": "YOUR_DINGTALK_WEBHOOK_URL" # 替换为实际钉钉Webhook URL
    }
    
    message = f"UI自动化测试完成!\n{summary}"
    send_to_feishu(webhook_urls["feishu"], message)
    send_to_wecom(webhook_urls["wecom"], message)
    send_to_dingtalk(webhook_urls["dingtalk"], message)
3. 报告解析工具 (utils/report_parser.py)

解析Allure报告,提取测试摘要(如总用例数、通过率)。

import os
import json

def parse_allure_report(report_dir):
    """解析Allure报告目录,返回摘要字符串"""
    # 读取Allure的widgets/summary.json文件
    summary_path = os.path.join(report_dir, "widgets", "summary.json")
    if not os.path.exists(summary_path):
        return "报告解析失败:未找到summary.json"
    
    with open(summary_path, "r", encoding="utf-8") as f:
        data = json.load(f)
    
    # 提取关键指标
    total = data["statistic"]["total"]
    passed = data["statistic"]["passed"]
    failed = data["statistic"]["failed"]
    broken = data["statistic"]["broken"]
    passed_rate = (passed / total) * 100 if total > 0 else 0
    
    # 构建摘要
    report_url = "http://localhost:8080/index.html"  # 假设报告部署在本地服务器
    summary = (
        f"总用例数: {total}\n"
        f"通过: {passed} | 失败: {failed} | 中断: {broken}\n"
        f"通过率: {passed_rate:.2f}%\n"
        f"报告链接: {report_url}"  # 实际中替换为部署后的URL
    )
    return summary
4. 消息发送工具 (utils/message_sender.py)

实现发送消息到飞书、企业微信和钉钉的函数。

import requests
import json

def send_to_feishu(webhook_url, message):
    """发送消息到飞书机器人"""
    headers = {"Content-Type": "application/json"}
    payload = {
        "msg_type": "text",
        "content": {"text": message}
    }
    response = requests.post(webhook_url, headers=headers, data=json.dumps(payload))
    return response.status_code == 200

def send_to_wecom(webhook_url, message):
    """发送消息到企业微信机器人"""
    headers = {"Content-Type": "application/json"}
    payload = {
        "msgtype": "text",
        "text": {"content": message}
    }
    response = requests.post(webhook_url, headers=headers, data=json.dumps(payload))
    return response.status_code == 200

def send_to_dingtalk(webhook_url, message):
    """发送消息到钉钉机器人"""
    headers = {"Content-Type": "application/json"}
    payload = {
        "msgtype": "text",
        "text": {"content": message}
    }
    response = requests.post(webhook_url, headers=headers, data=json.dumps(payload))
    return response.status_code == 200

配置说明

  1. Webhook URL设置

    • 飞书:在飞书群聊中添加机器人,获取Webhook URL,替换 conftest.py 中的 YOUR_FEISHU_WEBHOOK_URL
    • 企业微信:在企业微信应用中创建机器人,获取Webhook URL,替换 YOUR_WECOM_WEBHOOK_URL
    • 钉钉:在钉钉群聊中添加自定义机器人,获取Webhook URL,替换 YOUR_DINGTALK_WEBHOOK_URL
    • 确保URL保密,不要提交到版本控制。
  2. Allure报告部署

    • 生成的报告在 allure-report 目录,本地查看可用 allure open allure-report
    • 生产环境中,建议部署到Web服务器(如Nginx),并更新 report_parser.py 中的 report_url 为实际访问链接。
  3. 运行测试

    • 执行测试并生成Allure原始数据:
      pytest --alluredir=allure-results
      
    • 测试结束后,钩子会自动调用,生成HTML报告并发送消息。

高级优化建议

  • 错误处理:在 message_sender.py 中添加重试机制和日志记录,处理网络异常。
  • 报告附件:如果需要发送报告文件(如压缩包),修改钩子函数添加文件上传逻辑(需平台API支持)。
  • 安全增强:使用环境变量存储Webhook URL,避免硬编码。
  • 并发支持:结合 pytest-xdist 实现并行测试,提升效率。
  • 自定义消息:在 report_parser.py 中扩展解析逻辑,添加详细失败用例列表。

注意事项

  • 环境要求:确保已安装Java(Allure依赖),并配置好ChromeDriver。
  • 调试:如果消息发送失败,检查Webhook URL和网络权限;使用 pytest -s 查看详细日志。
  • 扩展性:本框架易于集成其他工具(如Jenkins),实现CI/CD流水线。

通过这个方案,测试完成后会自动发送摘要到指定平台,提高团队协作效率。如果有特定需求(如自定义报告内容),可进一步调整代码!

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐