#!/usr/bin/env python3
"""生成可视化测试报告 HTML"""
import json
import sys
from pathlib import Path
from datetime import datetime
def generate_report(report_data: dict, output_path: str) -> str:
task_name = report_data.get("task_name", "Test Report")
product = report_data.get("product", "test-agent")
result = report_data.get("result", "PASS")
total_runs = report_data.get("total_runs", 0)
passed = report_data.get("pass", 0)
failed = report_data.get("fail", 0)
started_at = report_data.get("started_at", "")
finished_at = report_data.get("finished_at", "")
logs = report_data.get("logs", [])
screenshots = report_data.get("screenshots", [])
results = report_data.get("results", [])
duration = ""
if started_at and finished_at:
try:
s = datetime.fromisoformat(started_at)
f = datetime.fromisoformat(finished_at)
secs = (f - s).total_seconds()
duration = f"{secs:.1f}s" if secs < 60 else f"{secs/60:.1f}min"
except Exception:
duration = "-"
total = passed + failed
skipped = total_runs - total
pass_rate = (passed / total_runs * 100) if total_runs > 0 else 0
circumference = 502.65
pass_dash = passed / total * circumference if total > 0 else 0
fail_dash = failed / total * circumference if total > 0 else 0
skip_dash = skipped / total * circumference if total > 0 else 0
fail_offset = pass_dash
skip_offset = pass_dash + fail_dash
pass_rate_bar = max(pass_rate, 60)
pass_rate_gradient = "--success" if pass_rate >= 95 else "--warning"
defect_rate = min(failed / total * 100 if total > 0 else 0, 100)
defect_gradient = "--success" if defect_rate <= 5 else "--warning"
# Build result rows
result_rows = ""
for r in results:
status = r.get("status", "pass")
msg = r.get("message", "-")
dur = r.get("duration", 0)
result_rows += f'
{r.get("name","")}
{status.upper()}
{dur:.2f}s
{msg}
'
# Build log lines
log_lines = ""
for log in logs:
lvl = log.get("level", "INFO").lower()
ts = log.get("ts", "")
msg = log.get("msg", "")
log_lines += f'
[{ts}]{msg}
'
# Build screenshot cards
screenshot_cards = ""
for s in screenshots:
screenshot_cards += f'
'
badge_class = "pass" if result == "PASS" else "fail"
badge_text = "PASS" if result == "PASS" else "FAIL"
badge_icon = "✓" if result == "PASS" else "✗"
html = """
REPORT_TITLE | TestAgent