pytest集成钉钉或企业微信通知的核心做法是编写一个自定义插件,利用pytest的`pytest_sessionfinish`钩子在测试结束后发送http post请求。你需要在项目中创建一个包含`conftest.py`和通知逻辑模块的文件结构,并在其中实现基于`requests`库的消息推送代码,这样每次运行测试后就能自动将结果推送到对应的im群组。

如何配置钉钉机器人的Webhook地址并发送Markdown格式消息
要成功向钉钉群发送通知,必须获取正确的Webhook URL,并使用特定的JSON Payload结构。钉钉机器人支持文本、Markdown和活动卡片等消息类型,其中Markdown格式能更好地展示测试结果(如通过/失败统计)。发送时需注意签名校验(如果是安全设置开启的状态)以及Content-Type必须为application/json。

import requests
import json
def send_dingtalk_notification(webhook_url, title, passed, failed, error):
total = passed + failed + error
# 构建Markdown内容
markdown_content = f"### Pytest 测试结果\n"
markdown_content += f"> **总计**: {total} \n"
markdown_content += f"> **通过**: {passed} \n"
markdown_content += f"> **失败**: {failed} \n"
markdown_content += f"> **错误**: {error} \n"
payload = {
"msgtype": "markdown",
"markdown": {
"title": title,
"text": markdown_content
}
}
headers = {'Content-Type': 'application/json'}
response = requests.post(webhook_url, data=json.dumps(payload), headers=headers)
return response.json()
如何解析pytest的XML报告以提取详细的失败用例信息
仅仅知道总数是不够的,通常还需要知道具体哪个用例失败了。可以通过解析pytest生成的junitxml报告文件来获取详细的失败列表。使用Python内置的`xml.etree.ElementTree`库可以方便地遍历XML节点,提取失败的用例名称和错误日志,然后将这些信息追加到通知消息中,以便开发人员快速定位问题。

import xml.etree.ElementTree as ET
def parse_junit_xml(xml_file_path):
tree = ET.parse(xml_file_path)
root = tree.getroot()
failures = []
errors = []
for testcase in root.findall('testcase'):
failure = testcase.find('failure')
error = testcase.find('error')
if failure is not None:
failures.append({
'name': testcase.get('name'),
'message': failure.text.strip() if failure.text else 'Unknown'
})
elif error is not None:
errors.append({
'name': testcase.get('name'),
'message': error.text.strip() if error.text else 'Unknown'
})
return len(failures), len(errors), failures, errors
当Webhook请求返回400或403状态码时应该如何处理异常
在实际集成中,网络波动、Webhook地址错误或签名验证失败都会导致HTTP请求报错。如果直接抛出异常,可能会中断后续的CI/CD流程。因此,需要在通知函数中加入try-except块,捕获`requests.exceptions.RequestException`。当发生错误时,建议打印日志到控制台或写入本地文件,而不是让程序崩溃,确保测试主流程的稳定性。











