- 16 个业务模块,856 个测试用例,40 个 E2E 测试 - 单一 React 19 前端 + PlatformSwitcher 二合一切换 - Flask 后端支持 scenario/dcloud_module/dcloud_e2e/dcloud_all 四种任务类型 - E2E 测试面板:API 全链路(8条) + UI 点击(3条) + 分步测试(3个) - SSE 实时日志流 + 飞书告警 + 定时调度 - 完整还原原 ToB 平台 TestPanel E2E 模块
180 lines
5.1 KiB
Python
180 lines
5.1 KiB
Python
#!/usr/bin/env python
|
|
"""
|
|
测试结果分析脚本
|
|
|
|
分析 pytest 生成的 JUnit XML 报告,输出测试统计信息。
|
|
|
|
使用方式:
|
|
python scripts/analyze_test_results.py
|
|
|
|
环境变量:
|
|
REPORT_DIR: 报告目录,默认 reports/
|
|
"""
|
|
import os
|
|
import sys
|
|
import xml.etree.ElementTree as ET
|
|
from pathlib import Path
|
|
from typing import Dict, Any
|
|
|
|
|
|
def parse_junit_xml(file_path: Path) -> Dict[str, Any]:
|
|
"""解析 JUnit XML 文件
|
|
|
|
Args:
|
|
file_path: XML 文件路径
|
|
|
|
Returns:
|
|
Dict[str, Any]: 测试统计信息
|
|
"""
|
|
try:
|
|
tree = ET.parse(file_path)
|
|
root = tree.getroot()
|
|
|
|
# 获取测试套件
|
|
test_suite = root.find('testsuite') or root
|
|
|
|
stats = {
|
|
'total': int(test_suite.get('tests', 0)),
|
|
'passed': int(test_suite.get('tests', 0)) - int(test_suite.get('failures', 0)) - int(test_suite.get('errors', 0)) - int(test_suite.get('skipped', 0)),
|
|
'failed': int(test_suite.get('failures', 0)),
|
|
'errors': int(test_suite.get('errors', 0)),
|
|
'skipped': int(test_suite.get('skipped', 0)),
|
|
'time': float(test_suite.get('time', 0)),
|
|
}
|
|
|
|
# 收集失败测试
|
|
failed_tests = []
|
|
for testcase in test_suite.findall('.//testcase'):
|
|
failure = testcase.find('failure')
|
|
error = testcase.find('error')
|
|
if failure is not None or error is not None:
|
|
failed_tests.append({
|
|
'name': testcase.get('name'),
|
|
'classname': testcase.get('classname'),
|
|
'message': (failure or error).get('message', '')[:100]
|
|
})
|
|
|
|
stats['failed_tests'] = failed_tests
|
|
|
|
return stats
|
|
except Exception as e:
|
|
print(f"解析 XML 失败: {e}")
|
|
return {
|
|
'total': 0,
|
|
'passed': 0,
|
|
'failed': 0,
|
|
'errors': 0,
|
|
'skipped': 0,
|
|
'time': 0,
|
|
'failed_tests': []
|
|
}
|
|
|
|
|
|
def format_duration(seconds: float) -> str:
|
|
"""格式化持续时间
|
|
|
|
Args:
|
|
seconds: 秒数
|
|
|
|
Returns:
|
|
str: 格式化的时间字符串
|
|
"""
|
|
if seconds < 60:
|
|
return f"{seconds:.1f}s"
|
|
minutes = int(seconds // 60)
|
|
secs = int(seconds % 60)
|
|
return f"{minutes}m {secs}s"
|
|
|
|
|
|
def print_report(stats: Dict[str, Any], title: str = "测试结果") -> None:
|
|
"""打印测试报告
|
|
|
|
Args:
|
|
stats: 测试统计信息
|
|
title: 报告标题
|
|
"""
|
|
print(f"\n{'='*60}")
|
|
print(f" {title}")
|
|
print(f"{'='*60}")
|
|
|
|
total = stats['total']
|
|
passed = stats['passed']
|
|
failed = stats['failed'] + stats['errors']
|
|
skipped = stats['skipped']
|
|
duration = format_duration(stats['time'])
|
|
|
|
# 计算通过率
|
|
pass_rate = (passed / total * 100) if total > 0 else 0
|
|
|
|
print(f"\n 📊 测试统计:")
|
|
print(f" 总计: {total}")
|
|
print(f" ✅ 通过: {passed} ({pass_rate:.1f}%)")
|
|
print(f" ❌ 失败: {failed}")
|
|
print(f" ⏭️ 跳过: {skipped}")
|
|
print(f" ⏱️ 耗时: {duration}")
|
|
|
|
# 打印失败测试
|
|
if stats['failed_tests']:
|
|
print(f"\n ❌ 失败测试:")
|
|
for test in stats['failed_tests'][:10]: # 最多显示 10 个
|
|
print(f" - {test['classname']}::{test['name']}")
|
|
print(f" {test['message']}")
|
|
|
|
if len(stats['failed_tests']) > 10:
|
|
print(f" ... 还有 {len(stats['failed_tests']) - 10} 个失败测试")
|
|
|
|
print(f"\n{'='*60}\n")
|
|
|
|
# 输出到 GitHub Actions
|
|
if os.getenv('GITHUB_ACTIONS') == 'true':
|
|
# 设置输出
|
|
with open(os.getenv('GITHUB_OUTPUT', '/dev/null'), 'a') as f:
|
|
f.write(f"total={total}\n")
|
|
f.write(f"passed={passed}\n")
|
|
f.write(f"failed={failed}\n")
|
|
f.write(f"skipped={skipped}\n")
|
|
f.write(f"pass_rate={pass_rate:.1f}\n")
|
|
|
|
|
|
def main():
|
|
"""主函数"""
|
|
report_dir = Path(os.getenv('REPORT_DIR', 'reports'))
|
|
|
|
# 查找 JUnit XML 文件
|
|
xml_files = list(report_dir.glob('*junit.xml'))
|
|
|
|
if not xml_files:
|
|
print("⚠️ 未找到 JUnit XML 报告文件")
|
|
print(f" 查找目录: {report_dir.absolute()}")
|
|
return
|
|
|
|
# 合并所有报告的统计
|
|
total_stats = {
|
|
'total': 0,
|
|
'passed': 0,
|
|
'failed': 0,
|
|
'errors': 0,
|
|
'skipped': 0,
|
|
'time': 0,
|
|
'failed_tests': []
|
|
}
|
|
|
|
for xml_file in xml_files:
|
|
stats = parse_junit_xml(xml_file)
|
|
total_stats['total'] += stats['total']
|
|
total_stats['passed'] += stats['passed']
|
|
total_stats['failed'] += stats['failed']
|
|
total_stats['errors'] += stats['errors']
|
|
total_stats['skipped'] += stats['skipped']
|
|
total_stats['time'] += stats['time']
|
|
total_stats['failed_tests'].extend(stats['failed_tests'])
|
|
|
|
print_report(total_stats)
|
|
|
|
# 返回退出码
|
|
sys.exit(0 if total_stats['failed'] + total_stats['errors'] == 0 else 1)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|