mirror of
https://github.com/ProjectLeonida/mandy.git
synced 2026-12-06 08:58:36 +00:00
xcl_compare: open transcript before Popen, format float timeouts, validate paths upfront, write JSON atomically
This commit is contained in:
@ -263,5 +263,106 @@ class RestartTraces(unittest.TestCase):
|
||||
self.assertEqual(trace1.read_text(encoding="utf-8"), '{"attempt": 1}\n')
|
||||
|
||||
|
||||
class GuardsAndAtomicIO(unittest.TestCase):
|
||||
def test_unwritable_transcript_does_not_spawn_title(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
with mock.patch.object(xc.subprocess, "Popen", side_effect=AssertionError("should not spawn")):
|
||||
with self.assertRaises(OSError):
|
||||
xc.run_title([sys.executable, "-c", "pass"], os.environ, tmp, xc.Run("synthetic"),
|
||||
[], 1, None, Sink(), [], transcript=tmp)
|
||||
|
||||
def test_fractional_timeout_preserves_subsecond_reason(self):
|
||||
script = "import time\nprint('[RUN] probe', flush=True)\ntime.sleep(5)\n"
|
||||
run = xc.Run("synthetic")
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
hung = xc.run_title([sys.executable, "-I", "-c", script], os.environ, tmp, run,
|
||||
["probe"], 0.5, None, Sink(), [])
|
||||
self.assertEqual(hung, "probe")
|
||||
self.assertEqual(run.checks["probe"]["reason"], "no output for 0.5 s")
|
||||
|
||||
def test_kill_tree_ignores_already_exited_process(self):
|
||||
proc = mock.Mock(pid=12345)
|
||||
proc.kill.side_effect = ProcessLookupError("already exited")
|
||||
xc.kill_tree(proc)
|
||||
|
||||
def _make_fake_env(self, root):
|
||||
xcl_dir = root / "xcl"
|
||||
rel = xcl_dir / "target" / "release"
|
||||
rel.mkdir(parents=True)
|
||||
for name in ("xcl.exe", "xcl_testtitle.exe", "testgame_mw.dll"):
|
||||
(rel / name).write_bytes(b"stub")
|
||||
testgame = xcl_dir / "tests" / "data" / "testgame"
|
||||
testgame.mkdir(parents=True)
|
||||
(testgame / "marker.txt").write_text("clean", encoding="utf-8", newline="\n")
|
||||
gta6rt = root / "gta6rt.exe"
|
||||
gta6rt.write_bytes(b"stub")
|
||||
return xcl_dir, gta6rt
|
||||
|
||||
def test_run_all_rejects_bad_out_and_paths_before_running(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
xcl_dir, gta6rt = self._make_fake_env(root)
|
||||
work = root / "work"
|
||||
out_dir = root / "out_dir"
|
||||
out_dir.mkdir()
|
||||
cases = [
|
||||
{"out": ""},
|
||||
{"out": " "},
|
||||
{"out": str(out_dir)},
|
||||
{"out": str(root / "folder") + os.sep},
|
||||
{"work": " "},
|
||||
]
|
||||
with mock.patch.object(xc, "run_title", side_effect=AssertionError("should not run")):
|
||||
for overrides in cases:
|
||||
with self.subTest(**overrides):
|
||||
ns = argparse.Namespace(
|
||||
xcl=str(xcl_dir), gta6rt=str(gta6rt), work=str(work),
|
||||
timeout=15.0, max_restarts=1, skip=[], cdb=None, out=None,
|
||||
)
|
||||
for k, v in overrides.items():
|
||||
setattr(ns, k, v)
|
||||
with self.assertRaises(SystemExit):
|
||||
xc.run_all(ns, Sink())
|
||||
|
||||
def test_run_all_report_write_is_atomic_on_failure(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
xcl_dir, gta6rt = self._make_fake_env(root)
|
||||
work = root / "work"
|
||||
work.mkdir()
|
||||
out = work / "report.json"
|
||||
prior = '{"prior": true}\n'
|
||||
out.write_text(prior, encoding="utf-8", newline="\n")
|
||||
real_open = open
|
||||
|
||||
class FailingWriter:
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
return False
|
||||
|
||||
def write(self, _data):
|
||||
raise OSError("disk full")
|
||||
|
||||
def fail_write(path, mode="r", *args, **kwargs):
|
||||
if "w" in mode and os.path.abspath(str(path)) == os.path.abspath(str(out)):
|
||||
real_open(path, "w", encoding="utf-8", newline="\n").close()
|
||||
return FailingWriter()
|
||||
return real_open(path, mode, *args, **kwargs)
|
||||
|
||||
args = argparse.Namespace(
|
||||
xcl=str(xcl_dir), gta6rt=str(gta6rt), work=str(work),
|
||||
timeout=15.0, max_restarts=0, skip=[], cdb=None, out=str(out),
|
||||
)
|
||||
with mock.patch.object(xc, "run_title", return_value=None), \
|
||||
mock.patch("builtins.open", side_effect=fail_write), \
|
||||
mock.patch.object(xc, "replace_retry", side_effect=OSError("disk full"), create=True):
|
||||
with self.assertRaises(OSError):
|
||||
xc.run_all(args, Sink())
|
||||
self.assertEqual(out.read_text(encoding="utf-8"), prior)
|
||||
self.assertEqual([p.name for p in work.glob("*.tmp")], [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@ -30,6 +30,7 @@ import math
|
||||
import os
|
||||
import queue
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
@ -37,6 +38,10 @@ import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
|
||||
from file_mode import published_mode # noqa: E402
|
||||
from replace_retry import replace as replace_retry # noqa: E402
|
||||
|
||||
REPO = Path(__file__).resolve().parent.parent
|
||||
CDB_DEFAULT = Path(r"C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\cdb.exe")
|
||||
STATUS_ORDER = ("PASS", "FAIL", "SKIP", "HANG", "NOT RUN")
|
||||
@ -131,9 +136,14 @@ def thread_stacks(cdb, pid):
|
||||
def kill_tree(proc):
|
||||
"""Stop the title and every process it started (taskkill /T on Windows, the process alone elsewhere)."""
|
||||
if os.name == "nt":
|
||||
subprocess.run(["taskkill", "/F", "/T", "/PID", str(proc.pid)], capture_output=True)
|
||||
else:
|
||||
try:
|
||||
subprocess.run(["taskkill", "/F", "/T", "/PID", str(proc.pid)], capture_output=True)
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
proc.kill()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def run_title(cmd, env, cwd, run, known, timeout, cdb, events, skip, transcript=None):
|
||||
@ -144,22 +154,31 @@ def run_title(cmd, env, cwd, run, known, timeout, cdb, events, skip, transcript=
|
||||
env = dict(env)
|
||||
if skip:
|
||||
env["XCL_TESTTITLE_SKIP"] = ";".join(skip)
|
||||
proc = subprocess.Popen(cmd, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
||||
stdin=subprocess.DEVNULL, text=True, encoding="utf-8", errors="replace")
|
||||
lines = queue.Queue()
|
||||
|
||||
def pump():
|
||||
with proc.stdout:
|
||||
for line in proc.stdout:
|
||||
lines.put(line.rstrip("\r\n"))
|
||||
lines.put(None)
|
||||
|
||||
threading.Thread(target=pump, daemon=True).start()
|
||||
out = open(transcript, "a", encoding="utf-8", newline="\n") if transcript else None
|
||||
if out:
|
||||
out.write("--- %s\n" % " ".join(str(c) for c in cmd))
|
||||
proc = None
|
||||
try:
|
||||
if out:
|
||||
out.write("--- %s\n" % " ".join(str(c) for c in cmd))
|
||||
proc = subprocess.Popen(cmd, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
||||
stdin=subprocess.DEVNULL, text=True, encoding="utf-8", errors="replace")
|
||||
lines = queue.Queue()
|
||||
|
||||
def pump():
|
||||
with proc.stdout:
|
||||
for line in proc.stdout:
|
||||
lines.put(line.rstrip("\r\n"))
|
||||
lines.put(None)
|
||||
|
||||
threading.Thread(target=pump, daemon=True).start()
|
||||
return _follow(proc, lines, run, known, timeout, cdb, events, out, cmd)
|
||||
except BaseException:
|
||||
if proc is not None and proc.poll() is None:
|
||||
kill_tree(proc)
|
||||
try:
|
||||
proc.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
pass
|
||||
raise
|
||||
finally:
|
||||
if out:
|
||||
out.close()
|
||||
@ -184,7 +203,7 @@ def _follow(proc, lines, run, known, timeout, cdb, events, out, cmd):
|
||||
stacks = thread_stacks(cdb, proc.pid)
|
||||
kill_tree(proc)
|
||||
proc.wait()
|
||||
run.set(hung, status="HANG", reason="no output for %d s" % timeout, stack=stacks,
|
||||
run.set(hung, status="HANG", reason="no output for %g s" % timeout, stack=stacks,
|
||||
seconds=round(time.monotonic() - started, 2))
|
||||
events.put(("check", run.label, hung))
|
||||
return hung
|
||||
@ -225,7 +244,56 @@ def _follow(proc, lines, run, known, timeout, cdb, events, out, cmd):
|
||||
return None
|
||||
|
||||
|
||||
def _write_json_atomic(path, report):
|
||||
"""Publish complete JSON atomically, leaving any existing report intact on failure."""
|
||||
destination = os.path.realpath(str(path))
|
||||
out_dir = os.path.dirname(destination) or "."
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
try:
|
||||
mode = os.stat(destination).st_mode
|
||||
except FileNotFoundError:
|
||||
mode = None
|
||||
if mode is not None and not stat.S_ISREG(mode):
|
||||
with open(destination, "w", encoding="utf-8", newline="\n") as f:
|
||||
json.dump(report, f, indent=2, ensure_ascii=False, allow_nan=False)
|
||||
f.write("\n")
|
||||
return
|
||||
if mode is not None:
|
||||
os.close(os.open(destination, os.O_WRONLY))
|
||||
staged = tempfile.NamedTemporaryFile(
|
||||
mode="w", encoding="utf-8", newline="\n", delete=False,
|
||||
dir=out_dir, prefix=".xcl_compare-", suffix=".tmp",
|
||||
)
|
||||
try:
|
||||
with staged:
|
||||
json.dump(report, staged, indent=2, ensure_ascii=False, allow_nan=False)
|
||||
staged.write("\n")
|
||||
if os.name != "nt":
|
||||
os.chmod(staged.name, published_mode(destination))
|
||||
replace_retry(staged.name, destination)
|
||||
finally:
|
||||
try:
|
||||
os.unlink(staged.name)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
||||
|
||||
def _validate_out_path(raw_out):
|
||||
if raw_out is None:
|
||||
return None
|
||||
if not str(raw_out).strip():
|
||||
raise SystemExit("--out must not be empty")
|
||||
text = str(raw_out)
|
||||
if text.endswith(os.sep) or (os.altsep and text.endswith(os.altsep)) or os.path.isdir(text):
|
||||
raise SystemExit(f"--out is a folder, not a file: {raw_out}")
|
||||
return Path(raw_out)
|
||||
|
||||
|
||||
def run_all(args, events):
|
||||
for flag, val in (("--xcl", args.xcl), ("--gta6rt", args.gta6rt), ("--work", args.work), ("--cdb", args.cdb)):
|
||||
if val is not None and not str(val).strip():
|
||||
raise SystemExit(f"{flag} must not be empty")
|
||||
out = _validate_out_path(args.out)
|
||||
xcl_dir = Path(args.xcl).resolve()
|
||||
bins = find_xcl_binaries(xcl_dir)
|
||||
if not bins:
|
||||
@ -237,6 +305,10 @@ def run_all(args, events):
|
||||
if work.drive.upper() == "D:":
|
||||
# XCL maps the console drive D: to the game folder, so a real D:\ path is not reachable inside it.
|
||||
raise SystemExit("--work is on D:, which XCL maps to the game folder; use a folder on another drive")
|
||||
if out is None:
|
||||
out = work / "report.json"
|
||||
if out.is_dir():
|
||||
raise SystemExit(f"--out is a folder, not a file: {out}")
|
||||
work.mkdir(parents=True, exist_ok=True)
|
||||
cdb = Path(args.cdb) if args.cdb else (CDB_DEFAULT if CDB_DEFAULT.is_file() else None)
|
||||
|
||||
@ -244,7 +316,8 @@ def run_all(args, events):
|
||||
events.put(("runs", xcl, leo))
|
||||
transcripts = {"xcl": work / "xcl_output.txt", "leonida": work / "leonida_output.txt"}
|
||||
for path in transcripts.values():
|
||||
open(path, "w", encoding="utf-8", newline="\n").close()
|
||||
with open(path, "w", encoding="utf-8", newline="\n"):
|
||||
pass
|
||||
|
||||
# 1. XCL: the reference run, which also gives the check order.
|
||||
if (work / "xcl").exists():
|
||||
@ -280,11 +353,7 @@ def run_all(args, events):
|
||||
leo.set(name)
|
||||
report = make_report(xcl, leo, known, gta6rt, xcl_dir)
|
||||
report["transcripts"] = {k: str(v) for k, v in transcripts.items()}
|
||||
out = Path(args.out) if args.out else work / "report.json"
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(out, "w", encoding="utf-8", newline="\n") as f:
|
||||
json.dump(report, f, indent=2, ensure_ascii=False)
|
||||
f.write("\n")
|
||||
_write_json_atomic(out, report)
|
||||
events.put(("done", report, str(out)))
|
||||
return report, out
|
||||
|
||||
@ -466,7 +535,7 @@ def gui(args):
|
||||
root.mainloop()
|
||||
|
||||
|
||||
def main():
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
||||
ap.add_argument("--xcl", required=True, help="an XCL checkout with 'cargo build --release --workspace' done")
|
||||
ap.add_argument("--gta6rt", help="gta6rt.exe (default: the one under runtime/build)")
|
||||
@ -477,7 +546,11 @@ def main():
|
||||
ap.add_argument("--cdb", help="cdb.exe for stacks of a hung title")
|
||||
ap.add_argument("--out", help="report path (default: <work>/report.json)")
|
||||
ap.add_argument("--gui", action="store_true", help="show the checks live in a window")
|
||||
args = ap.parse_args()
|
||||
args = ap.parse_args(argv)
|
||||
for flag, val in (("--xcl", args.xcl), ("--gta6rt", args.gta6rt), ("--work", args.work),
|
||||
("--cdb", args.cdb), ("--out", args.out)):
|
||||
if val is not None and not val.strip():
|
||||
ap.error(f"{flag} must not be empty")
|
||||
if not math.isfinite(args.timeout) or args.timeout <= 0:
|
||||
ap.error("--timeout must be finite and greater than zero")
|
||||
if args.max_restarts < 0:
|
||||
@ -507,5 +580,8 @@ def main():
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.stdout.reconfigure(errors="replace")
|
||||
try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
|
||||
sys.stdout.reconfigure(errors="replace")
|
||||
except (AttributeError, ValueError, OSError):
|
||||
pass
|
||||
sys.exit(main())
|
||||
|
||||
Reference in New Issue
Block a user