""" 报告生成器模块 """ import json from pathlib import Path from datetime import datetime from typing import Dict, Any, List from dataclasses import dataclass, asdict @dataclass class TestResult: """测试结果数据类""" test_name: str test_type: str url: str method: str status_code: int response_time: float success: bool error_message: str request_data: Dict[str, Any] response_data: Dict[str, Any] timestamp: str def to_dict(self) -> Dict[str, Any]: """转换为字典""" return asdict(self) @dataclass class TestSummary: """测试摘要数据类""" total: int passed: int failed: int skipped: int pass_rate: float total_time: float start_time: str end_time: str def to_dict(self) -> Dict[str, Any]: """转换为字典""" return asdict(self) class ReportGenerator: """测试报告生成器""" def __init__(self, output_dir: str = "reports"): """ 初始化报告生成器 Args: output_dir: 报告输出目录 """ self.output_dir = Path(output_dir) self.output_dir.mkdir(parents=True, exist_ok=True) def generate_json_report(self, results: List[TestResult], summary: TestSummary, filename: str = None) -> str: """ 生成JSON格式报告 Args: results: 测试结果列表 summary: 测试摘要 filename: 报告文件名 Returns: 报告文件路径 """ if filename is None: timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") filename = f"test_report_{timestamp}.json" report_path = self.output_dir / filename report_data = { "summary": summary.to_dict(), "results": [result.to_dict() for result in results], "generated_at": datetime.now().isoformat() } with open(report_path, 'w', encoding='utf-8') as f: json.dump(report_data, f, ensure_ascii=False, indent=2) return str(report_path) def generate_html_report(self, results: List[TestResult], summary: TestSummary, filename: str = None) -> str: """ 生成HTML格式报告 Args: results: 测试结果列表 summary: 测试摘要 filename: 报告文件名 Returns: 报告文件路径 """ if filename is None: timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") filename = f"test_report_{timestamp}.html" report_path = self.output_dir / filename html_content = self._generate_html_content(results, summary) with open(report_path, 'w', encoding='utf-8') as f: f.write(html_content) return str(report_path) def _generate_html_content(self, results: List[TestResult], summary: TestSummary) -> str: """ 生成HTML内容 Args: results: 测试结果列表 summary: 测试摘要 Returns: HTML内容 """ passed_results = [r for r in results if r.success] failed_results = [r for r in results if not r.success] html = f"""
生成时间: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}