#!/usr/bin/env python3 """生成现代化中文测试报告 Dashboard 特性: - 现代 UI 设计(毛玻璃效果、渐变、动画过渡) - 深色/浅色模式切换 - SVG 环形通过率图 + 模块柱状图 + 耗时分布 - 实时筛选(按结果/模块/关键字) - 历史趋势折线图(从 reports/history.json 读取) - 失败截图嵌入报告(点击可放大查看) - 响应式布局,支持移动端 """ import json import sys import argparse import html import base64 from pathlib import Path from datetime import datetime from collections import defaultdict ROOT = Path(__file__).parent.parent def load_data(json_path: Path) -> list: if not json_path.exists(): print(f"[错误] 找不到报告数据文件: {json_path}") print("请先运行测试:python -m pytest tests/ ...") sys.exit(1) with open(json_path, encoding="utf-8") as f: return json.load(f) def load_history(history_path: Path) -> list: """加载历史数据。格式: [{date, total, passed, failed, skipped, duration}, ...]""" if not history_path.exists(): return [] try: with open(history_path, encoding="utf-8") as f: return json.load(f) except Exception: return [] def save_history(history_path: Path, history: list, stats: dict, now: str): """将当前运行结果追加到历史""" history.append( { "date": now, "total": stats["total"], "passed": stats["passed"], "failed": stats["failed"], "skipped": stats["skipped"], "duration": stats["duration_raw"], "pass_rate": stats["pass_rate_raw"], } ) # 最多保留 50 条 history = history[-50:] history_path.parent.mkdir(parents=True, exist_ok=True) with open(history_path, "w", encoding="utf-8") as f: json.dump(history, f, ensure_ascii=False, indent=2) return history def build_stats(records: list) -> dict: total = len(records) passed = sum(1 for r in records if r["result"] == "通过") failed = sum(1 for r in records if r["result"] == "失败") skipped = sum(1 for r in records if r["result"] == "跳过") duration = sum(r.get("duration", 0) for r in records) rate = passed / total * 100 if total else 0 return { "total": total, "passed": passed, "failed": failed, "skipped": skipped, "duration": f"{duration:.1f}s", "duration_raw": round(duration, 1), "pass_rate": f"{rate:.1f}%", "pass_rate_raw": round(rate, 1), } def escape(text: str) -> str: """转义 HTML 特殊字符,防止 XSS""" return html.escape(str(text), quote=True) def screenshot_to_base64(screenshot_path: str) -> str: """将截图文件转换为 base64 编码 Args: screenshot_path: 截图文件路径 Returns: str: base64 编码的 data URI,失败返回空字符串 """ if not screenshot_path: return "" path = Path(screenshot_path) if not path.exists(): return "" try: with open(path, "rb") as f: data = base64.b64encode(f.read()).decode("utf-8") return f"data:image/png;base64,{data}" except Exception: return "" def build_module_stats(records: list) -> list: """按模块聚合统计""" mods = defaultdict( lambda: {"total": 0, "passed": 0, "failed": 0, "skipped": 0, "duration": 0} ) for r in records: m = r.get("module") or "其他" mods[m]["total"] += 1 mods[m]["duration"] += r.get("duration", 0) if r["result"] == "通过": mods[m]["passed"] += 1 elif r["result"] == "失败": mods[m]["failed"] += 1 else: mods[m]["skipped"] += 1 return sorted( [{"name": k, **v} for k, v in mods.items()], key=lambda x: x["total"], reverse=True, ) def build_html(records: list, stats: dict, history: list, generated_at: str) -> str: modules = defaultdict(list) for r in records: modules[r.get("module") or "其他"].append(r) mod_stats = build_module_stats(records) mod_stats_json = json.dumps(mod_stats, ensure_ascii=False) history_json = json.dumps(history[-20:], ensure_ascii=False) # 最近20次 # Build module sections module_parts = [] for mod_name, mod_records in sorted(modules.items()): mp = sum(1 for r in mod_records if r["result"] == "通过") mf = sum(1 for r in mod_records if r["result"] == "失败") ms = sum(1 for r in mod_records if r["result"] == "跳过") mt = len(mod_records) mod_id = f"mod_{mod_name.replace(' ', '_')}" rows = [] for i, r in enumerate(mod_records): err_html = "" toggle = "" expand_col = '' result_class = {"通过": "pass", "失败": "fail", "跳过": "skip"}.get( r["result"], "" ) badge = f'{r["result"]}' if r.get("error"): eid = f"e_{mod_id}_{i}" # 处理截图 screenshot_html = "" screenshot_data = screenshot_to_base64(r.get("screenshot")) if screenshot_data: screenshot_html = f'''
失败截图
''' err_html = f''' {screenshot_html}
{escape(r["error"][:3000])}
''' toggle = f' class="row clickable" onclick="toggleErr(\'{eid}\')"' expand_col = '' else: toggle = f' class="row"' rows.append(f''' {escape(r["function"])} {escape(r.get("description") or "—")} {escape(r.get("expected") or "—")} {badge} {r.get("duration", 0):.2f}s {escape((r.get("reason") or r.get("assertion") or "")[:120])} {expand_col} {err_html}''') fail_indicator = f'{mf}' if mf else "" module_parts.append(f'''
{escape(mod_name)} {fail_indicator} {mp}通过 {ms}跳过 {mt}总计
{"".join(rows)}
测试用例 描述 预期结果 状态 耗时 失败原因
''') # Failed summary failed = [r for r in records if r["result"] == "失败"] fail_section = "" if failed: frows = "\n".join( f""" {escape(r.get("module") or "")} {escape(r["function"])} {escape(r.get("description") or "—")} {escape(r.get("error", "")[:200])} """ for r in failed ) fail_section = f"""
失败汇总 ({len(failed)})
{frows}
模块用例描述错误
""" # Module select options mod_options = "\n".join( f'' for m in sorted(modules.keys()) ) # Compute donut SVG parameters rate = stats["pass_rate_raw"] circumference = 2 * 3.14159 * 54 pass_dash = circumference * rate / 100 fail_pct = stats["failed"] / stats["total"] * 100 if stats["total"] else 0 fail_dash = circumference * fail_pct / 100 skip_pct = stats["skipped"] / stats["total"] * 100 if stats["total"] else 0 skip_dash = circumference * skip_pct / 100 return f''' 测试报告 Dashboard

自动化测试报告

生成时间:{generated_at}  |  data-loop-automation
{stats["total"]}
总计
{stats["passed"]}
通过
{stats["failed"]}
失败
{stats["skipped"]}
跳过
{stats["pass_rate"]}
通过率
{stats["duration"]}
总耗时
测试结果分布
{stats["pass_rate"]}
通过率
通过 {stats["passed"]}
失败 {stats["failed"]}
跳过 {stats["skipped"]}
模块覆盖分布
历史趋势
全部 通过 失败 跳过
{fail_section} {"".join(module_parts)}
''' def main(): parser = argparse.ArgumentParser(description="生成现代化中文测试报告 Dashboard") parser.add_argument( "--data", default=str(ROOT / "reports" / "report_data.json"), help="JSON 数据文件路径(默认 reports/report_data.json)", ) parser.add_argument( "--output", default=str(ROOT / "reports" / "report_zh.html"), help="输出 HTML 文件路径(默认 reports/report_zh.html)", ) parser.add_argument( "--history", default=str(ROOT / "reports" / "history.json"), help="历史数据文件路径(默认 reports/history.json)", ) parser.add_argument( "--no-history", action="store_true", help="不保存历史数据", ) args = parser.parse_args() data_path = Path(args.data) output_path = Path(args.output) history_path = Path(args.history) output_path.parent.mkdir(parents=True, exist_ok=True) records = load_data(data_path) stats = build_stats(records) generated_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S") # 加载并更新历史 history = load_history(history_path) if not args.no_history: history = save_history(history_path, history, stats, generated_at) html = build_html(records, stats, history, generated_at) with open(output_path, "w", encoding="utf-8") as f: f.write(html) print(f"[OK] 报告已生成:{output_path}") print( f" 总计 {stats['total']} | 通过 {stats['passed']} | " f"失败 {stats['failed']} | 跳过 {stats['skipped']} | " f"通过率 {stats['pass_rate']}" ) if not args.no_history: print(f" 历史记录:{history_path} ({len(history)} 条)") if __name__ == "__main__": main()