team-ljyzipelo

공개
106줄4.7 KB
1import argparse
2import fcntl
3import hashlib
4import json
5import os
6from pathlib import Path
7import re
8import signal
9import subprocess
10import sys
11
12if sys.flags.optimize or os.environ.get("PYTHONOPTIMIZE"):
13 raise SystemExit("정상 Python mode 필요")
14HERE = Path(__file__).resolve().parent
15ROOT = HERE.parents[1]
16parser = argparse.ArgumentParser()
17parser.add_argument("--execute-reviewed", action="store_true")
18parser.add_argument("--record", type=Path, required=True)
19parser.add_argument("--workspace-lock", type=Path, required=True)
20args = parser.parse_args()
21if not args.execute_reviewed:
22 raise SystemExit("고정 head 실행 배정 후 --execute-reviewed 필요")
23record = args.record.resolve()
24if not record.is_relative_to(HERE) or record.exists():
25 raise SystemExit("새 tests 내부 기록 경로 필요")
26lock = args.workspace_lock.resolve().open("r")
27fcntl.flock(lock, fcntl.LOCK_EX)
28subprocess.run(["git", "status", "--porcelain"], cwd=ROOT, stdout=subprocess.DEVNULL, check=True)
29record.mkdir()
30commands = []
31report = {"commands": commands, "status": "started", "passed": [], "unexecuted": []}
32
33
34def digest(data):
35 return hashlib.sha256(data).hexdigest()
36
37
38def write_report():
39 (record / "report.json").write_text(json.dumps(report, ensure_ascii=False, indent=4) + "\n")
40
41
42def run(stage, command, timeout):
43 proc = subprocess.Popen(command, cwd=ROOT, stdout=subprocess.PIPE, stderr=subprocess.PIPE, start_new_session=True)
44 timed_out = False
45 try:
46 out, err = proc.communicate(timeout=timeout)
47 except subprocess.TimeoutExpired:
48 timed_out = True
49 os.killpg(proc.pid, signal.SIGKILL)
50 out, err = proc.communicate()
51 (record / (stage + ".stdout")).write_bytes(out)
52 (record / (stage + ".stderr")).write_bytes(err)
53 commands.append({"stage": stage, "command": command, "exit": proc.returncode, "timeout_seconds": timeout, "timed_out": timed_out, "stdout_sha256": digest(out), "stderr_sha256": digest(err)})
54 write_report()
55 if timed_out or proc.returncode:
56 raise RuntimeError("첫 실패: " + stage)
57 return out
58
59
60fixed = json.loads((HERE / "sources.json").read_text())
61inputs = {str(ROOT / p): v["sha256"] for p, v in fixed.items()}
62for line in (HERE / "SHA256SUMS").read_text().splitlines():
63 value, path = line.split(" ", 1)
64 inputs[str(ROOT / path)] = value
65inputs[str(HERE / "SHA256SUMS")] = digest((HERE / "SHA256SUMS").read_bytes())
66contract = json.loads((HERE / "contract.json").read_text())
67report["unexecuted"] = contract["names"].copy()
68try:
69 run("static", [sys.executable, str(HERE / "static_check.py")], 15)
70 manifest = str(HERE / "Cargo.toml")
71 output = run("compile", ["cargo", "+1.99.1", "test", "--locked", "--offline", "--manifest-path", manifest, "--test", "races", "--no-run", "--message-format=json", "--target-dir", str(record / "target")], 180)
72 artifacts = [json.loads(line) for line in output.splitlines() if line.startswith(b"{")]
73 bins = [a["executable"] for a in artifacts if a.get("reason") == "compiler-artifact" and a.get("target", {}).get("name") == "races" and a.get("executable")]
74 if len(bins) != 1:
75 raise RuntimeError("시험 binary 수 불일치")
76 binary = bins[0]
77 report["binary_sha256"] = digest(Path(binary).read_bytes())
78 listing = run("discovery", [binary, "--list", "--format", "terse"], 10).decode().splitlines()
79 if any(not line.endswith(": test") for line in listing if line.strip()):
80 raise RuntimeError("발견 행 형식 불일치")
81 names = [line[:-6] for line in listing if line.strip()]
82 report["discovered"] = names
83 if len(names) != len(set(names)) or set(names) != set(contract["names"]):
84 raise RuntimeError("발견 이름 집합 불일치")
85 for index, name in enumerate(contract["names"]):
86 report["active"] = name
87 write_report()
88 out = run(f"test-{index:02}", [binary, name, "--exact", "--test-threads=1", "--nocapture"], 30).decode()
89 expected = f"1 passed; 0 failed; 0 ignored; 0 measured; {len(names) - 1} filtered out"
90 if expected not in out or not re.search(r"test " + re.escape(name) + r" \.\.\. ok", out):
91 raise RuntimeError("실행 결과 불일치: " + name)
92 report["passed"].append(name)
93 report["unexecuted"].remove(name)
94 report["status"] = "passed"
95except Exception as error:
96 report["status"] = "failed"
97 report["failure"] = str(error)
98 raise
99finally:
100 report["inputs_unchanged"] = all(digest(Path(p).read_bytes()) == value for p, value in inputs.items())
101 if not report["inputs_unchanged"]:
102 report["status"] = "failed"
103 report["failure"] = "고정 입력 변경 감지"
104 write_report()
105 if not report["inputs_unchanged"]:
106 raise RuntimeError("고정 입력 변경 감지")