TBC/plugins/test_runner/__init__.py
jiawei.chen d05f4796a6 release: v1.1.0 - 安全加固与稳定性修复
🔒 Security:
- 修复 API Key 泄露,移除 platform_db.json 明文存储
- 限制 CORS 允许来源,不再全开放
- 添加路径校验防止目录穿越攻击
- Git 命令使用列表传参防止注入
- os.killpg 添加异常处理

🐛 Bug Fixes:
- 生产环境禁用 Flask debug 模式
- 修复 SSE 连接泄漏(useTaskLogs + ReposView)
- 修复 fetch 静默吞错误,添加 console.error 日志
- 补全 _run_ui_fix 函数签名
- 修复 .coveragerc source 配置
- _load_db 添加文件锁和 Queue maxsize
- SSE log_queues 使用 WeakValueDictionary

🔧 Refactor:
- BaseAPI → APIClient 统一命名
- 删除后端死代码和重复 import
- 删除 business_backup 备份代码
- 删除 conftest_metrics 死代码

📝 Docs:
- 新增 CHANGELOG.md 和 CHANGELIST.md
- 更新 QUICKSTART.md 添加安全注意事项
- 更新 CONFIG.md 添加安全加固和性能优化
2026-07-15 16:51:08 +08:00

105 lines
3.7 KiB
Python

"""测试运行插件 - 运行生成的测试并反馈结果"""
import subprocess
import logging
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)