"""测试运行插件 - 运行生成的测试并反馈结果""" import subprocess import logging import json from pathlib import Path logger = logging.getLogger(__name__) class TestRunner: def __init__(self, test_dir: Path): self.test_dir = Path(test_dir) def run_tests(self, markers: list[str] = None, verbose: bool = True) -> dict: cmd = ["pytest"] if markers: marker_expr = " or ".join(markers) cmd.extend(["-m", marker_expr]) if verbose: cmd.append("-v") cmd.extend(["--tb=short", str(self.test_dir)]) logger.info(f"运行测试: {' '.join(cmd)}") try: result = subprocess.run( cmd, capture_output=True, text=True, timeout=300, ) return self._parse_result(result) except subprocess.TimeoutExpired: logger.error("测试运行超时") return {"passed": 0, "failed": 0, "error": "timeout"} except FileNotFoundError: logger.error("pytest 未安装,请运行: pip install pytest") return {"passed": 0, "failed": 0, "error": "pytest not found"} def _parse_result(self, result: subprocess.CompletedProcess) -> dict: output = result.stdout + result.stderr passed = 0 failed = 0 errors = 0 skipped = 0 for line in output.splitlines(): if "passed" in line and "=" in line: parts = line.split(",") for part in parts: part = part.strip() if "passed" in part: try: passed = int(part.split()[0]) except ValueError: pass elif "failed" in part: try: failed = int(part.split()[0]) except ValueError: pass elif "error" in part: try: errors = int(part.split()[0]) except ValueError: pass elif "skipped" in part: try: skipped = int(part.split()[0]) except ValueError: pass return { "passed": passed, "failed": failed, "errors": errors, "skipped": skipped, "total": passed + failed + errors + skipped, "pass_rate": (passed / (passed + failed + errors) * 100) if (passed + failed + errors) > 0 else 0, "output": output, } def check_metrics_gate(self, results: dict) -> bool: pass_rate = results.get("pass_rate", 0) if pass_rate < 95: logger.warning(f"通过率 {pass_rate:.1f}% 低于门禁 95%") return False logger.info(f"通过率 {pass_rate:.1f}% 达标") return True def generate_run_report(self, results: dict) -> str: lines = ["# 测试运行报告", ""] lines.append(f"- 通过: {results.get('passed', 0)}") lines.append(f"- 失败: {results.get('failed', 0)}") lines.append(f"- 错误: {results.get('errors', 0)}") lines.append(f"- 跳过: {results.get('skipped', 0)}") lines.append(f"- 总计: {results.get('total', 0)}") lines.append(f"- 通过率: {results.get('pass_rate', 0):.1f}%") gate = self.check_metrics_gate(results) lines.append(f"- 指标门禁: {'✅ 通过' if gate else '❌ 未通过'}") return "\n".join(lines)