|
| 1 | +"""tests/_harness.py:run_all 回归集共享夹具(ok/skip 收集、宿主协议钩子触发、临时 git 仓)。""" |
| 2 | +from __future__ import annotations |
| 3 | + |
| 4 | +import json |
| 5 | +import os |
| 6 | +import subprocess |
| 7 | +import sys |
| 8 | +import tempfile |
| 9 | +from pathlib import Path |
| 10 | + |
| 11 | +PLUGIN = Path(__file__).resolve().parents[1] |
| 12 | +HOOKS = PLUGIN / "hooks" |
| 13 | +sys.path.insert(0, str(PLUGIN / "scripts")) |
| 14 | +sys.path.insert(0, str(HOOKS)) |
| 15 | + |
| 16 | +PASS, FAIL, SKIP = [], [], [] |
| 17 | + |
| 18 | + |
| 19 | +def ok(name, cond, note=""): |
| 20 | + (PASS if cond else FAIL).append(name) |
| 21 | + print(f" {'✅' if cond else '❌'} {name}" + (f" — {note}" if note and not cond else "")) |
| 22 | + |
| 23 | + |
| 24 | +def skip(name, why): |
| 25 | + SKIP.append(name) |
| 26 | + print(f" ⏭️ {name} — {why}") |
| 27 | + |
| 28 | + |
| 29 | +def run_hook(script: str, payload: dict | None, cwd: Path, env_extra: dict | None = None): |
| 30 | + """按宿主协议触发钩子:stdin JSON → (exit, stdout, stderr)""" |
| 31 | + env = {**os.environ, "PYTHONIOENCODING": "utf-8", **(env_extra or {})} |
| 32 | + return subprocess.run( |
| 33 | + [sys.executable, str(HOOKS / script)], |
| 34 | + input=json.dumps(payload) if payload is not None else "", |
| 35 | + capture_output=True, check=False, text=True, cwd=cwd, timeout=120, env=env, |
| 36 | + ) |
| 37 | + |
| 38 | + |
| 39 | +def git(repo: Path, *args: str): |
| 40 | + return subprocess.run(["git", *args], cwd=repo, capture_output=True, check=False, text=True) |
| 41 | + |
| 42 | + |
| 43 | +def make_repo() -> Path: |
| 44 | + """临时 git 仓(含一个必被 shellcheck 抓到的坏脚本)""" |
| 45 | + repo = Path(tempfile.mkdtemp(prefix="cg-test-")) |
| 46 | + git(repo, "init", "-q") |
| 47 | + git(repo, "config", "user.email", "t@t") |
| 48 | + git(repo, "config", "user.name", "t") |
| 49 | + (repo / "scripts").mkdir() |
| 50 | + (repo / "scripts" / "deploy.sh").write_text( |
| 51 | + '#!/bin/bash\nif [ $foo = bar ]; then echo hi; fi\n' |
| 52 | + ) |
| 53 | + git(repo, "add", "-A") |
| 54 | + git(repo, "commit", "-q", "-m", "init") |
| 55 | + return repo |
0 commit comments