TBC/scripts/generate_report.py

853 lines
33 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/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 = '<td class="expand-cell"></td>'
result_class = {"通过": "pass", "失败": "fail", "跳过": "skip"}.get(
r["result"], ""
)
badge = f'<span class="badge {result_class}">{r["result"]}</span>'
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'''
<div class="screenshot-container">
<img src="{screenshot_data}" alt="失败截图" class="screenshot-img" onclick="openScreenshot(this)">
</div>'''
err_html = f'''
<tr class="error-row" id="{eid}">
<td colspan="7">
{screenshot_html}
<pre class="error-pre">{escape(r["error"][:3000])}</pre>
</td>
</tr>'''
toggle = f' class="row clickable" onclick="toggleErr(\'{eid}\')"'
expand_col = '<td class="expand-cell"><svg class="chevron" viewBox="0 0 24 24"><path d="M7 10l5 5 5-5z"/></svg></td>'
else:
toggle = f' class="row"'
rows.append(f'''
<tr{toggle} data-result="{r["result"]}" data-fn="{escape(r["function"])}" data-desc="{escape(r.get("description") or "")}">
<td class="fn-cell">{escape(r["function"])}</td>
<td>{escape(r.get("description") or "—")}</td>
<td>{escape(r.get("expected") or "—")}</td>
<td class="center">{badge}</td>
<td class="center">{r.get("duration", 0):.2f}s</td>
<td class="err-snippet">{escape((r.get("reason") or r.get("assertion") or "")[:120])}</td>
{expand_col}
</tr>{err_html}''')
fail_indicator = f'<span class="mod-fail-count">{mf}</span>' if mf else ""
module_parts.append(f'''
<section class="mod-section" data-module="{escape(mod_name)}">
<div class="mod-head" onclick="toggleMod('{mod_id}')">
<svg class="mod-chevron" id="chev_{mod_id}" viewBox="0 0 24 24"><path d="M7 10l5 5 5-5z"/></svg>
<span class="mod-title">{escape(mod_name)}</span>
{fail_indicator}
<span class="mod-meta">{mp}<small>通过</small> {ms}<small>跳过</small> {mt}<small>总计</small></span>
</div>
<div class="mod-body" id="{mod_id}">
<table>
<thead><tr>
<th style="width:180px">测试用例</th>
<th>描述</th>
<th>预期结果</th>
<th style="width:80px" class="center">状态</th>
<th style="width:70px" class="center">耗时</th>
<th style="width:180px">失败原因</th>
<th style="width:36px"></th>
</tr></thead>
<tbody>{"".join(rows)}</tbody>
</table>
</div>
</section>''')
# Failed summary
failed = [r for r in records if r["result"] == "失败"]
fail_section = ""
if failed:
frows = "\n".join(
f"""<tr>
<td>{escape(r.get("module") or "")}</td>
<td class="fn-cell">{escape(r["function"])}</td>
<td>{escape(r.get("description") or "—")}</td>
<td><code class="err-snippet">{escape(r.get("error", "")[:200])}</code></td>
</tr>"""
for r in failed
)
fail_section = f"""
<section class="mod-section fail-summary">
<div class="mod-head" onclick="toggleMod('fail_sum')">
<svg class="mod-chevron" id="chev_fail_sum" viewBox="0 0 24 24"><path d="M7 10l5 5 5-5z"/></svg>
<span class="mod-title fail-title">失败汇总 ({len(failed)})</span>
</div>
<div class="mod-body" id="fail_sum">
<table>
<thead><tr><th>模块</th><th>用例</th><th>描述</th><th>错误</th></tr></thead>
<tbody>{frows}</tbody>
</table>
</div>
</section>"""
# Module select options
mod_options = "\n".join(
f'<option value="{escape(m)}">{escape(m)}</option>'
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'''<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>测试报告 Dashboard</title>
<style>
:root {{
--bg: #f0f2f5; --surface: #fff; --surface2: #f8f9fc;
--text: #1a1a2e; --text2: #555; --text3: #999;
--border: #e4e7ed; --border2: #f0f0f0;
--primary: #4f46e5; --primary-light: #eef2ff;
--green: #10b981; --green-bg: #ecfdf5; --green-text: #065f46;
--red: #ef4444; --red-bg: #fef2f2; --red-text: #991b1b;
--amber: #f59e0b; --amber-bg: #fffbeb; --amber-text: #92400e;
--shadow: 0 1px 3px rgba(0,0,0,.06), 0 1px 2px rgba(0,0,0,.04);
--shadow-md: 0 4px 6px rgba(0,0,0,.05), 0 2px 4px rgba(0,0,0,.03);
--radius: 12px;
--transition: .25s cubic-bezier(.4,0,.2,1);
}}
[data-theme="dark"] {{
--bg: #0f172a; --surface: #1e293b; --surface2: #1a2332;
--text: #e2e8f0; --text2: #94a3b8; --text3: #64748b;
--border: #334155; --border2: #1e293b;
--primary: #818cf8; --primary-light: #1e1b4b;
--green-bg: #064e3b; --green-text: #6ee7b7;
--red-bg: #450a0a; --red-text: #fca5a5;
--amber-bg: #451a03; --amber-text: #fcd34d;
--shadow: 0 1px 3px rgba(0,0,0,.3);
--shadow-md: 0 4px 6px rgba(0,0,0,.3);
}}
* {{ box-sizing: border-box; margin: 0; padding: 0; }}
body {{ font-family: -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"PingFang SC","Noto Sans SC",sans-serif;
background: var(--bg); color: var(--text); font-size: 14px; line-height: 1.6;
transition: background var(--transition), color var(--transition); }}
a {{ color: var(--primary); text-decoration: none; }}
/* ---- Header ---- */
.header {{
background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 50%, #a855f7 100%);
color: #fff; padding: 28px 32px; position: relative; overflow: hidden;
}}
[data-theme="dark"] .header {{
background: linear-gradient(135deg, #312e81 0%, #4c1d95 50%, #581c87 100%);
}}
.header::after {{
content: ""; position: absolute; right: -60px; top: -60px;
width: 200px; height: 200px; border-radius: 50%;
background: rgba(255,255,255,.06); pointer-events: none;
}}
.header h1 {{ font-size: 22px; font-weight: 700; letter-spacing: -.5px; }}
.header .meta {{ opacity: .8; font-size: 12px; margin-top: 4px; }}
.theme-toggle {{
position: absolute; right: 32px; top: 50%; transform: translateY(-50%);
z-index: 1;
background: rgba(255,255,255,.15); border: 1px solid rgba(255,255,255,.2);
color: #fff; border-radius: 8px; padding: 6px 14px; cursor: pointer;
font-size: 13px; backdrop-filter: blur(4px); transition: background .2s;
}}
.theme-toggle:hover {{ background: rgba(255,255,255,.25); }}
/* ---- Dashboard Grid ---- */
.dashboard {{ display: grid; grid-template-columns: 1fr 1fr 1fr;
gap: 16px; padding: 20px 32px; max-width: 1400px; margin: 0 auto; }}
@media (max-width: 900px) {{ .dashboard {{ grid-template-columns: 1fr; }} }}
.card {{
background: var(--surface); border-radius: var(--radius);
padding: 20px; box-shadow: var(--shadow);
border: 1px solid var(--border); transition: all var(--transition);
}}
.card:hover {{ box-shadow: var(--shadow-md); transform: translateY(-1px); }}
.card-title {{ font-size: 13px; color: var(--text3); font-weight: 500;
text-transform: uppercase; letter-spacing: .5px; margin-bottom: 12px; }}
/* Stats Row */
.stats-row {{ display: flex; gap: 12px; padding: 16px 32px 0;
max-width: 1400px; margin: 0 auto; flex-wrap: wrap; }}
.stat-pill {{
background: var(--surface); border-radius: 10px; padding: 14px 20px;
flex: 1; min-width: 120px; text-align: center;
box-shadow: var(--shadow); border: 1px solid var(--border);
transition: all var(--transition);
}}
.stat-pill:hover {{ transform: translateY(-2px); box-shadow: var(--shadow-md); }}
.stat-pill .num {{ font-size: 28px; font-weight: 800; }}
.stat-pill .lbl {{ font-size: 11px; color: var(--text3); margin-top: 2px;
text-transform: uppercase; letter-spacing: .5px; }}
.stat-pill.s-pass .num {{ color: var(--green); }}
.stat-pill.s-fail .num {{ color: var(--red); }}
.stat-pill.s-skip .num {{ color: var(--amber); }}
.stat-pill.s-rate .num {{ color: var(--primary); }}
/* ---- Donut ---- */
.donut-wrap {{ display: flex; align-items: center; justify-content: center; gap: 20px; }}
.donut {{ position: relative; width: 120px; height: 120px; }}
.donut svg {{ transform: rotate(-90deg); }}
.donut-center {{
position: absolute; inset: 0; display: flex; align-items: center;
justify-content: center; flex-direction: column;
}}
.donut-center .pct {{ font-size: 24px; font-weight: 800; color: var(--green); }}
.donut-center .pct-label {{ font-size: 10px; color: var(--text3); }}
.donut-legend {{ font-size: 13px; }}
.donut-legend div {{ display: flex; align-items: center; gap: 8px; margin-bottom: 6px; }}
.dot {{ width: 10px; height: 10px; border-radius: 50%; flex-shrink: 0; }}
.dot-pass {{ background: var(--green); }}
.dot-fail {{ background: var(--red); }}
.dot-skip {{ background: var(--amber); }}
/* ---- Bar Chart ---- */
.bar-chart {{ display: flex; flex-direction: column; gap: 8px; }}
.bar-row {{ display: flex; align-items: center; gap: 10px; }}
.bar-label {{ width: 80px; font-size: 12px; color: var(--text2); text-align: right;
overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }}
.bar-track {{ flex: 1; height: 20px; background: var(--surface2); border-radius: 4px;
overflow: hidden; display: flex; }}
.bar-seg {{ height: 100%; transition: width .6s ease; }}
.bar-seg.bp {{ background: var(--green); }}
.bar-seg.bf {{ background: var(--red); }}
.bar-seg.bs {{ background: var(--amber); }}
.bar-num {{ width: 36px; font-size: 12px; color: var(--text3); text-align: right; }}
/* ---- History Chart ---- */
.history-chart {{ position: relative; height: 140px; }}
.history-empty {{ display: flex; align-items: center; justify-content: center;
height: 100%; color: var(--text3); font-size: 13px; }}
/* ---- Filter Bar ---- */
.filter-bar {{
display: flex; gap: 10px; padding: 16px 32px; max-width: 1400px;
margin: 0 auto; flex-wrap: wrap; align-items: center;
}}
.filter-bar input, .filter-bar select {{
background: var(--surface); border: 1px solid var(--border);
border-radius: 8px; padding: 8px 14px; font-size: 13px;
color: var(--text); outline: none; transition: border .2s;
}}
.filter-bar input:focus, .filter-bar select:focus {{ border-color: var(--primary); }}
.filter-bar input {{ flex: 1; min-width: 200px; }}
.filter-bar select {{ min-width: 120px; }}
.filter-chip {{
display: inline-flex; align-items: center; gap: 4px;
padding: 6px 14px; border-radius: 20px; font-size: 12px; font-weight: 600;
cursor: pointer; border: 1px solid var(--border); background: var(--surface);
color: var(--text2); transition: all .2s; user-select: none;
}}
.filter-chip.active {{ background: var(--primary); color: #fff; border-color: var(--primary); }}
.filter-chip:hover {{ border-color: var(--primary); }}
.result-count {{
margin-left: auto; font-size: 12px; color: var(--text3);
}}
/* ---- Module Sections ---- */
.content {{ padding: 0 32px 32px; max-width: 1400px; margin: 0 auto; }}
.mod-section {{
background: var(--surface); border-radius: var(--radius);
margin-bottom: 12px; box-shadow: var(--shadow); border: 1px solid var(--border);
overflow: hidden; transition: all var(--transition);
}}
.mod-section.fail-summary {{ border-left: 4px solid var(--red); }}
.mod-head {{
padding: 14px 18px; cursor: pointer; display: flex; align-items: center;
gap: 10px; user-select: none; transition: background .2s;
}}
.mod-head:hover {{ background: var(--surface2); }}
.mod-chevron {{ width: 20px; height: 20px; fill: var(--text3);
transition: transform .25s; flex-shrink: 0; }}
.mod-chevron.collapsed {{ transform: rotate(-90deg); }}
.mod-title {{ font-size: 15px; font-weight: 600; color: var(--primary); }}
.fail-title {{ color: var(--red) !important; }}
.mod-fail-count {{
background: var(--red-bg); color: var(--red-text); font-size: 11px;
font-weight: 700; padding: 2px 8px; border-radius: 10px;
}}
.mod-meta {{ margin-left: auto; font-size: 12px; color: var(--text3);
display: flex; gap: 12px; }}
.mod-meta small {{ margin-left: 2px; }}
.mod-body {{ transition: max-height .3s ease; overflow: hidden; }}
.mod-body.collapsed {{ max-height: 0 !important; }}
table {{ width: 100%; border-collapse: collapse; }}
thead {{ background: var(--surface2); }}
th {{ padding: 10px 14px; text-align: left; font-size: 12px;
color: var(--text3); font-weight: 600; text-transform: uppercase;
letter-spacing: .3px; border-bottom: 2px solid var(--border); }}
th.center, td.center {{ text-align: center; }}
td {{ padding: 10px 14px; border-bottom: 1px solid var(--border2);
vertical-align: top; word-break: break-word; font-size: 13px; }}
.fn-cell {{ font-family: "SF Mono","Fira Code",monospace; font-size: 12px; color: var(--primary); }}
tr.row {{ transition: background .15s; }}
tr.clickable {{ cursor: pointer; }}
tr.clickable:hover {{ background: var(--primary-light); }}
tr[data-result="跳过"] {{ opacity: .7; }}
tr[data-result="失败"] {{ background: var(--red-bg); }}
.badge {{
display: inline-block; padding: 3px 10px; border-radius: 6px;
font-size: 11px; font-weight: 700; letter-spacing: .3px;
}}
.badge.pass {{ background: var(--green-bg); color: var(--green-text); }}
.badge.fail {{ background: var(--red-bg); color: var(--red-text); }}
.badge.skip {{ background: var(--amber-bg); color: var(--amber-text); }}
.error-row {{ display: none; }}
.error-row.show {{ display: table-row; }}
.error-pre {{
background: #0d1117; color: #c9d1d9; padding: 16px 20px;
font-size: 12px; line-height: 1.7; overflow-x: auto;
max-height: 320px; overflow-y: auto; white-space: pre-wrap;
font-family: "SF Mono","Fira Code",monospace;
border-radius: 0; margin: 0;
}}
[data-theme="dark"] .error-pre {{ background: #0a0e14; }}
.err-snippet {{ font-size: 11px; color: var(--red-text); word-break: break-all; }}
.screenshot-container {{
margin-bottom: 12px; text-align: center;
}}
.screenshot-img {{
max-width: 100%; max-height: 400px; border-radius: 8px;
border: 1px solid var(--border); cursor: pointer;
transition: transform .2s, box-shadow .2s;
}}
.screenshot-img:hover {{
transform: scale(1.02); box-shadow: 0 4px 20px rgba(0,0,0,.15);
}}
.screenshot-modal {{
position: fixed; top: 0; left: 0; width: 100%; height: 100%;
background: rgba(0,0,0,.9); display: none; justify-content: center;
align-items: center; z-index: 9999; cursor: pointer;
}}
.screenshot-modal.show {{ display: flex; }}
.screenshot-modal img {{ max-width: 95%; max-height: 95%; border-radius: 8px; }}
.expand-cell {{ width: 36px; text-align: center; }}
.chevron {{ width: 18px; height: 18px; fill: var(--text3); transition: transform .2s; }}
tr.clickable .chevron {{ transform: rotate(0deg); }}
tr.clickable.open .chevron {{ transform: rotate(180deg); }}
footer {{
text-align: center; padding: 24px; color: var(--text3); font-size: 11px;
border-top: 1px solid var(--border);
}}
footer strong {{ color: var(--primary); font-weight: 600; }}
/* ---- Animations ---- */
@keyframes fadeIn {{ from {{ opacity: 0; transform: translateY(8px); }}
to {{ opacity: 1; transform: translateY(0); }} }}
.stat-pill, .card, .mod-section {{
animation: fadeIn .4s ease both;
}}
.stat-pill:nth-child(2) {{ animation-delay: .05s; }}
.stat-pill:nth-child(3) {{ animation-delay: .1s; }}
.stat-pill:nth-child(4) {{ animation-delay: .15s; }}
.stat-pill:nth-child(5) {{ animation-delay: .2s; }}
.stat-pill:nth-child(6) {{ animation-delay: .25s; }}
/* SVG chart styles */
.history-svg {{ width: 100%; height: 140px; }}
.history-svg .grid-line {{ stroke: var(--border); stroke-width: 0.5; }}
.history-svg .data-line {{ fill: none; stroke: var(--green); stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }}
.history-svg .data-dot {{ fill: var(--green); stroke: var(--surface); stroke-width: 2; }}
.history-svg .data-area {{ fill: var(--green); opacity: 0.08; }}
.history-svg .axis-label {{ fill: var(--text3); font-size: 10px; }}
</style>
</head>
<body>
<div class="header">
<h1>自动化测试报告</h1>
<div class="meta">生成时间:{generated_at} &nbsp;|&nbsp; data-loop-automation</div>
<button class="theme-toggle" onclick="toggleTheme()">🌓 切换主题</button>
</div>
<!-- Stats Row -->
<div class="stats-row">
<div class="stat-pill"><div class="num">{stats["total"]}</div><div class="lbl">总计</div></div>
<div class="stat-pill s-pass"><div class="num">{stats["passed"]}</div><div class="lbl">通过</div></div>
<div class="stat-pill s-fail"><div class="num">{stats["failed"]}</div><div class="lbl">失败</div></div>
<div class="stat-pill s-skip"><div class="num">{stats["skipped"]}</div><div class="lbl">跳过</div></div>
<div class="stat-pill s-rate"><div class="num">{stats["pass_rate"]}</div><div class="lbl">通过率</div></div>
<div class="stat-pill"><div class="num">{stats["duration"]}</div><div class="lbl">总耗时</div></div>
</div>
<!-- Dashboard Charts -->
<div class="dashboard">
<!-- Donut Chart -->
<div class="card">
<div class="card-title">测试结果分布</div>
<div class="donut-wrap">
<div class="donut">
<svg viewBox="0 0 120 120" width="120" height="120">
<circle cx="60" cy="60" r="54" fill="none" stroke="var(--border)" stroke-width="12"/>
<circle cx="60" cy="60" r="54" fill="none" stroke="var(--green)" stroke-width="12"
stroke-dasharray="{pass_dash:.1f} {circumference:.1f}" stroke-linecap="round"/>
<circle cx="60" cy="60" r="54" fill="none" stroke="var(--red)" stroke-width="12"
stroke-dasharray="{fail_dash:.1f} {circumference:.1f}"
stroke-dashoffset="-{pass_dash:.1f}" stroke-linecap="round"/>
<circle cx="60" cy="60" r="54" fill="none" stroke="var(--amber)" stroke-width="12"
stroke-dasharray="{skip_dash:.1f} {circumference:.1f}"
stroke-dashoffset="-{pass_dash + fail_dash:.1f}" stroke-linecap="round"/>
</svg>
<div class="donut-center">
<div class="pct">{stats["pass_rate"]}</div>
<div class="pct-label">通过率</div>
</div>
</div>
<div class="donut-legend">
<div><span class="dot dot-pass"></span> 通过 {stats["passed"]}</div>
<div><span class="dot dot-fail"></span> 失败 {stats["failed"]}</div>
<div><span class="dot dot-skip"></span> 跳过 {stats["skipped"]}</div>
</div>
</div>
</div>
<!-- Module Bar Chart -->
<div class="card">
<div class="card-title">模块覆盖分布</div>
<div class="bar-chart" id="barChart"></div>
</div>
<!-- History Trend -->
<div class="card">
<div class="card-title">历史趋势</div>
<div class="history-chart" id="historyChart"></div>
</div>
</div>
<!-- Filter Bar -->
<div class="filter-bar">
<input type="text" id="searchInput" placeholder="搜索用例名称或描述..." oninput="applyFilters()">
<select id="moduleFilter" onchange="applyFilters()">
<option value="">所有模块</option>
{mod_options}
</select>
<div style="display:flex;gap:6px;">
<span class="filter-chip active" data-filter="all" onclick="setResultFilter(this,'all')">全部</span>
<span class="filter-chip" data-filter="通过" onclick="setResultFilter(this,'通过')">通过</span>
<span class="filter-chip" data-filter="失败" onclick="setResultFilter(this,'失败')">失败</span>
<span class="filter-chip" data-filter="跳过" onclick="setResultFilter(this,'跳过')">跳过</span>
</div>
<span class="result-count" id="resultCount"></span>
</div>
<!-- Test Results -->
<div class="content">
{fail_section}
{"".join(module_parts)}
</div>
<footer>Powered by <strong>data-loop-automation</strong> &nbsp;·&nbsp; 自动化测试报告 Dashboard</footer>
<script>
// ---- Theme ----
function toggleTheme() {{
const html = document.documentElement;
const isDark = html.getAttribute('data-theme') === 'dark';
const next = isDark ? 'light' : 'dark';
html.setAttribute('data-theme', next);
try {{ localStorage.setItem('report-theme', next); }} catch(e) {{}}
}}
(function() {{
try {{
const saved = localStorage.getItem('report-theme');
if (saved) {{ document.documentElement.setAttribute('data-theme', saved); return; }}
}} catch(e) {{}}
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches)
document.documentElement.setAttribute('data-theme', 'dark');
}})();
// ---- Module Toggle ----
function toggleMod(id) {{
const body = document.getElementById(id);
const chev = document.getElementById('chev_' + id);
body.classList.toggle('collapsed');
chev.classList.toggle('collapsed');
}}
// ---- Error Toggle ----
function toggleErr(id) {{
const row = document.getElementById(id);
row.classList.toggle('show');
const prev = row.previousElementSibling;
if (prev) prev.classList.toggle('open');
}}
// ---- Screenshot Modal ----
function openScreenshot(img) {{
let modal = document.getElementById('screenshotModal');
if (!modal) {{
modal = document.createElement('div');
modal.id = 'screenshotModal';
modal.className = 'screenshot-modal';
modal.onclick = () => modal.classList.remove('show');
modal.innerHTML = '<img src="" alt="截图预览">';
document.body.appendChild(modal);
}}
modal.querySelector('img').src = img.src;
modal.classList.add('show');
}}
// ---- Filters ----
let currentResultFilter = 'all';
function setResultFilter(el, val) {{
currentResultFilter = val;
document.querySelectorAll('.filter-chip').forEach(c => c.classList.remove('active'));
el.classList.add('active');
applyFilters();
}}
function applyFilters() {{
const q = document.getElementById('searchInput').value.toLowerCase();
const mod = document.getElementById('moduleFilter').value;
let visible = 0, total = 0;
document.querySelectorAll('.mod-section').forEach(section => {{
if (section.classList.contains('fail-summary')) return;
const smod = section.getAttribute('data-module');
if (mod && smod !== mod) {{ section.style.display = 'none'; return; }}
section.style.display = '';
let secVisible = 0;
section.querySelectorAll('tbody tr.row').forEach(tr => {{
total++;
const res = tr.getAttribute('data-result');
const fn = (tr.getAttribute('data-fn') || '').toLowerCase();
const desc = (tr.getAttribute('data-desc') || '').toLowerCase();
const matchResult = currentResultFilter === 'all' || res === currentResultFilter;
const matchSearch = !q || fn.includes(q) || desc.includes(q);
const show = matchResult && matchSearch;
tr.style.display = show ? '' : 'none';
// Also hide error row if parent is hidden
const next = tr.nextElementSibling;
if (next && next.classList.contains('error-row') && !show) {{
next.classList.remove('show');
}}
if (show) {{ visible++; secVisible++; }}
}});
// Hide section if no visible rows
if (secVisible === 0 && (mod || q || currentResultFilter !== 'all')) {{
section.style.display = 'none';
}}
}});
document.getElementById('resultCount').textContent =
`显示 ${{visible}} / ${{total}} 条`;
}}
// ---- Module Bar Chart ----
(function() {{
const data = {mod_stats_json};
const maxTotal = Math.max(...data.map(d => d.total), 1);
const chart = document.getElementById('barChart');
let html = '';
data.forEach(d => {{
const pw = (d.passed / maxTotal * 100).toFixed(1);
const fw = (d.failed / maxTotal * 100).toFixed(1);
const sw = (d.skipped / maxTotal * 100).toFixed(1);
html += `<div class="bar-row">
<div class="bar-label" title="${{d.name}}">${{d.name}}</div>
<div class="bar-track">
<div class="bar-seg bp" style="width:${{pw}}%"></div>
<div class="bar-seg bf" style="width:${{fw}}%"></div>
<div class="bar-seg bs" style="width:${{sw}}%"></div>
</div>
<div class="bar-num">${{d.total}}</div>
</div>`;
}});
chart.innerHTML = html;
}})();
// ---- History Trend Chart (SVG) ----
(function() {{
const data = {history_json};
const container = document.getElementById('historyChart');
if (data.length < 2) {{
container.innerHTML = '<div class="history-empty">需要至少 2 次运行记录</div>';
return;
}}
const W = 440, H = 140, PX = 40, PY = 16, PB = 24;
const chartW = W - PX * 2, chartH = H - PY - PB;
const rates = data.map(d => d.pass_rate);
const minR = Math.max(0, Math.min(...rates) - 5);
const maxR = Math.min(100, Math.max(...rates) + 5);
const range = maxR - minR || 1;
function x(i) {{ return PX + (i / (data.length - 1)) * chartW; }}
function y(v) {{ return PY + chartH - ((v - minR) / range) * chartH; }}
const points = data.map((d, i) => `${{x(i).toFixed(1)}},${{y(d.pass_rate).toFixed(1)}}`);
const line = points.join(' ');
const area = `${{PX}},${{H - PB}} ` + line + ` ${{x(data.length - 1).toFixed(1)}},${{H - PB}}`;
// Grid lines
let grids = '';
for (let v = Math.ceil(minR / 10) * 10; v <= maxR; v += 10) {{
const yv = y(v).toFixed(1);
grids += `<line class="grid-line" x1="${{PX}}" y1="${{yv}}" x2="${{W - PX}}" y2="${{yv}}"/>`;
grids += `<text class="axis-label" x="${{PX - 6}}" y="${{yv}}" text-anchor="end" dominant-baseline="middle">${{v}}%</text>`;
}}
// X-axis labels (show a few)
let xlabels = '';
const step = Math.max(1, Math.floor(data.length / 5));
for (let i = 0; i < data.length; i += step) {{
const label = data[i].date.slice(5, 10); // MM-DD
xlabels += `<text class="axis-label" x="${{x(i).toFixed(1)}}" y="${{H - 4}}" text-anchor="middle">${{label}}</text>`;
}}
// Always show last
if ((data.length - 1) % step !== 0) {{
const li = data.length - 1;
xlabels += `<text class="axis-label" x="${{x(li).toFixed(1)}}" y="${{H - 4}}" text-anchor="middle">${{data[li].date.slice(5, 10)}}</text>`;
}}
// Dots
const dots = data.map((d, i) =>
`<circle class="data-dot" cx="${{x(i).toFixed(1)}}" cy="${{y(d.pass_rate).toFixed(1)}}" r="3.5">
<title>${{d.date}}\\n通过率: ${{d.pass_rate}}%\\n${{d.passed}}/${{d.total}}</title>
</circle>`
).join('');
container.innerHTML = `<svg class="history-svg" viewBox="0 0 ${{W}} ${{H}}" preserveAspectRatio="xMidYMid meet">
${{grids}}
<polygon class="data-area" points="${{area}}"/>
<polyline class="data-line" points="${{line}}"/>
${{dots}}
${{xlabels}}
</svg>`;
}})();
// Init filter count
applyFilters();
</script>
</body>
</html>'''
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()