TBC/scripts/api_server.py
d-robotics 633a797226 AutoFlow v2.0: 合并 Test (Robogo) + data-loop-automation (D-Cloud) 为统一平台
- 16 个业务模块,856 个测试用例,40 个 E2E 测试
- 单一 React 19 前端 + PlatformSwitcher 二合一切换
- Flask 后端支持 scenario/dcloud_module/dcloud_e2e/dcloud_all 四种任务类型
- E2E 测试面板:API 全链路(8条) + UI 点击(3条) + 分步测试(3个)
- SSE 实时日志流 + 飞书告警 + 定时调度
- 完整还原原 ToB 平台 TestPanel E2E 模块
2026-06-23 11:48:29 +08:00

228 lines
8.2 KiB
Python

#!/usr/bin/env python3
"""一键测试 API 服务 - SSE 实时日志推送 + 按模块运行 pytest"""
import json
import mimetypes
import subprocess
import sys
import time
import re
from http.server import HTTPServer, BaseHTTPRequestHandler
from pathlib import Path
from urllib.parse import urlparse, parse_qs
from dotenv import load_dotenv
load_dotenv()
PROJECT_ROOT = Path(__file__).resolve().parent.parent
PORT = 8899
class TestHandler(BaseHTTPRequestHandler):
def _send_json(self, status, data):
body = json.dumps(data, ensure_ascii=False).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Methods", "GET, OPTIONS")
self.send_header("Access-Control-Allow-Headers", "Content-Type")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def _send_file(self, filepath):
mime, _ = mimetypes.guess_type(filepath)
content = Path(filepath).read_bytes()
self.send_response(200)
self.send_header("Content-Type", mime or "text/html")
self.send_header("Content-Length", str(len(content)))
self.end_headers()
self.wfile.write(content)
def _sse_headers(self):
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.send_header("Cache-Control", "no-cache")
self.send_header("Connection", "keep-alive")
self.send_header("Access-Control-Allow-Origin", "*")
self.end_headers()
def _sse_send(self, data):
msg = f"data: {json.dumps(data, ensure_ascii=False)}\n\n"
try:
self.wfile.write(msg.encode("utf-8"))
self.wfile.flush()
except (BrokenPipeError, ConnectionResetError):
raise
def do_GET(self):
parsed = urlparse(self.path)
path = parsed.path
params = parse_qs(parsed.query)
if path in ("/", "/html.html"):
self._send_file(PROJECT_ROOT / "html.html")
elif path == "/favicon.ico":
self.send_response(204)
self.end_headers()
elif path == "/api/run-tests":
module = params.get("module", [None])[0]
test = params.get("test", [None])[0]
if not module:
self._send_json(400, {"error": "缺少 module 参数"})
return
self._stream_test(module, test)
elif path == "/api/run-e2e-step":
name = params.get("name", [None])[0]
step = params.get("step", ["1"])[0]
if not name:
self._send_json(400, {"error": "缺少 name 参数"})
return
self._stream_e2e_step(name, step)
else:
self._send_json(404, {"error": "Not found"})
def do_OPTIONS(self):
self.send_response(200)
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Methods", "GET, OPTIONS")
self.send_header("Access-Control-Allow-Headers", "Content-Type")
self.end_headers()
def _resolve_python(self):
"""优先使用项目虚拟环境 Python"""
candidates = [
PROJECT_ROOT / ".venv311" / "bin" / "python3",
PROJECT_ROOT / ".venv" / "bin" / "python3",
]
for p in candidates:
if p.exists():
return str(p)
return sys.executable
def _pytest_cmd(self, module, test=None):
python = self._resolve_python()
# E2E 模块:运行所有标记为 e2e 的测试
if module == "e2e":
if test:
return [python, "-m", "pytest", test, "-v", "--tb=short", "--color=no"]
return [python, "-m", "pytest", "tests/", "-m", "e2e", "-v", "--tb=short", "--color=no"]
test_dir = PROJECT_ROOT / "tests" / module
if not test_dir.exists():
return None
if test:
return [python, "-m", "pytest", test, "-v", "--tb=short", "--color=no"]
return [python, "-m", "pytest", str(test_dir), "-v", "--tb=short", "--color=no"]
def _stream_test(self, module, test=None):
cmd = self._pytest_cmd(module, test)
if cmd is None:
self._send_json(404, {"error": f"未知模块: {module}"})
return
self._run_cmd_stream(cmd)
def _stream_e2e_step(self, name, step):
python = self._resolve_python()
script = PROJECT_ROOT / "scripts" / "run_e2e_split.py"
cmd = [python, str(script), "--name", name, "--step", step]
self._run_cmd_stream(cmd)
def _run_cmd_stream(self, cmd):
self._sse_headers()
start = time.time()
try:
p = subprocess.Popen(
cmd,
cwd=str(PROJECT_ROOT),
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1,
)
except Exception as e:
self._sse_send({"type": "log", "msg": f"启动 pytest 失败: {e}", "cls": "text-red-400"})
self._sse_send({"type": "result", "passed": False, "duration": 0, "summary": str(e)})
return
total = 0
passed = 0
failed = 0
try:
for line in iter(p.stdout.readline, ""):
if not line:
break
line = line.rstrip("\n")
if not line:
continue
cls = ""
if "PASSED" in line:
m = re.search(r"(.+?) PASSED", line)
if m:
self._sse_send({"type": "log", "msg": f" ✓ {m.group(1)}", "cls": "text-green-400"})
passed += 1
total += 1
continue
elif "FAILED" in line:
m = re.search(r"(.+?) FAILED", line)
if m:
self._sse_send({"type": "log", "msg": f" ✗ {m.group(1)}", "cls": "text-red-400"})
failed += 1
total += 1
continue
elif "ERROR" in line:
self._sse_send({"type": "log", "msg": line, "cls": "text-red-400"})
continue
elif line.startswith("="):
self._sse_send({"type": "log", "msg": line, "cls": "text-gray-400"})
continue
elif "collected" in line or "deselected" in line:
self._sse_send({"type": "log", "msg": line, "cls": "text-blue-400"})
match = re.search(r"(\d+) selected", line)
if match:
total = int(match.group(1))
continue
elif re.match(r"tests/.+::", line):
self._sse_send({"type": "log", "msg": " … " + line.split("::")[-1], "cls": "text-gray-500"})
continue
if any(k in line for k in ("PASSED", "FAILED", "ERROR", "WARNING", "SKIPPED")):
self._sse_send({"type": "log", "msg": line, "cls": "text-yellow-400"})
else:
self._sse_send({"type": "log", "msg": line, "cls": ""})
p.wait()
except (BrokenPipeError, ConnectionResetError):
p.kill()
return
duration = round(time.time() - start, 1)
all_passed = p.returncode == 0 and failed == 0
summary = f"共 {passed + failed} 条: 通过 {passed}, 失败 {failed}" if (passed + failed) > 0 else "无测试"
self._sse_send({
"type": "result",
"passed": all_passed,
"duration": duration,
"summary": summary
})
def log_message(self, format, *args):
print(f"[{self.command}] {self.path}")
def main():
server = HTTPServer(("0.0.0.0", PORT), TestHandler)
print(f"页面: http://localhost:{PORT}/")
print(f"测试: GET /api/run-tests?module=workbench")
try:
server.serve_forever()
except KeyboardInterrupt:
print("\n服务已停止")
if __name__ == "__main__":
main()