A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
web_check --shots: PASS needs a finished shot; reject blank and non-PNG shots (items 2, 6) (#2895)
Beri22e0c629630e
diff --git a/tools/tests/test_web_check_shots.py b/tools/tests/test_web_check_shots.pyindex 4142ec71e..5f1eb2ece 100644--- a/tools/tests/test_web_check_shots.py+++ b/tools/tests/test_web_check_shots.py@@ -14,7 +14,7 @@ def shot_lines(name: str, png: bytes, chunk: int = 10) -> list[str]:def test_a_shot_is_reassembled_and_written(tmp_path):- png = bytes(range(256)) * 3+ png = png_of_size(32, 18, varied=True)c = wc.ShotCollector(tmp_path)assert all(c.feed(line) for line in shot_lines("gameplay03", png))assert (tmp_path / "gameplay03.png").read_bytes() == png@@ -24,7 +24,7 @@ def test_a_shot_is_reassembled_and_written(tmp_path):def test_parts_may_arrive_out_of_order(tmp_path):- png = b"\x89PNG" + bytes(200)+ png = png_of_size(32, 18, varied=True)lines = shot_lines("diorama02", png)c = wc.ShotCollector(tmp_path)for line in [lines[0]] + list(reversed(lines[1:])):@@ -63,11 +63,15 @@ def test_headless_chrome_runs_uncapped_at_dpr_1():assert "--use-angle=swiftshader" in wc.chrome_flags("/tmp/p", swiftshader=True)-def png_of_size(w: int, h: int) -> bytes:+def png_of_size(w: int, h: int, varied: bool = False) -> bytes:+ """A PNG; varied=True gives it a gradient, since a one-colour (blank) shot is now rejected."""import iofrom PIL import Image+ img = Image.new("RGB", (w, h), (10, 20, 30))+ if varied:+ img.putdata([(x * 255 // max(w - 1, 1), y * 255 // max(h - 1, 1), 99) for y in range(h) for x in range(w)])buf = io.BytesIO()- Image.new("RGB", (w, h), (10, 20, 30)).save(buf, "PNG")+ img.save(buf, "PNG")return buf.getvalue()@@ -78,7 +82,7 @@ def test_a_shot_of_the_wrong_size_fails(tmp_path):for line in shot_lines("gameplay03", png_of_size(1920, 937), chunk=4000):c.feed(line)ok = wc.ShotCollector(tmp_path, size=(64, 36))- assert all(ok.feed(line) for line in shot_lines("diorama02", png_of_size(64, 36), chunk=4000))+ assert all(ok.feed(line) for line in shot_lines("diorama02", png_of_size(64, 36, varied=True), chunk=4000))@pytest.mark.parametrize("bad", ["SHOT gameplay03 0/3 AAAA", "SHOT gameplay03 4/3 AAAA", "SHOT gameplay03 1/2 AAAA"])@@ -156,3 +160,95 @@ def test_rejoin_holds_an_open_line_across_batches_and_leaves_ordinary_lines_alonjoined = rejoin.feed('BBBB", source: x (2)\n')assert [wc.CONSOLE.search(l).group(1) for l in joined] == ["SHOT a 1/2 AAAABBBB"]assert rejoin.flush() == []+++# --- #2697 items 2 and 6: a --shots run that captured nothing usable must fail ---------------------------------------++def run_main(monkeypatch, capsys, tmp_path, console: list[str], *argv: str) -> tuple[int, str]:+ """web_check.main against a fake browser whose stderr is `console` as Chrome prints it; no Chrome, no network."""+ import io+ import sys++ class FakeBrowser:+ stderr = io.StringIO("".join(f'[1105/1.1:INFO:CONSOLE:1] "{t}", source: x (1)\n' for t in console))+ def poll(self): return 0+ def terminate(self): pass+ def wait(self, timeout=None): return 0++ class FakePage:+ def __init__(self, *a): pass+ def open(self): pass+ def close(self): pass+ def command(self, name): pass++ monkeypatch.setattr(wc, "find_chrome", lambda: tmp_path / "chrome")+ monkeypatch.setattr(wc.subprocess, "Popen", lambda *a, **k: FakeBrowser())+ monkeypatch.setattr(wc, "Page", FakePage)+ monkeypatch.setattr(sys, "argv", ["web_check.py", "--url", "http://x.invalid/index.html", "--viewport", "100x100",+ "--shots", str(tmp_path / "shots"), *argv])+ code = wc.main()+ return code, capsys.readouterr().out+++def test_shots_run_with_an_unrelated_expect_and_no_shot_at_all_fails(monkeypatch, capsys, tmp_path):+ code, out = run_main(monkeypatch, capsys, tmp_path, ["GAME OK 1948-05-15"], "--expect", "GAME OK")+ assert code == 1 and "PASS" not in out and not list((tmp_path / "shots").glob("*.png"))+++def test_shots_run_that_never_logs_shot_done_fails_even_with_a_shot(monkeypatch, capsys, tmp_path):+ console = ["GAME OK 1948-05-15"] + shot_lines("gameplay03", png_of_size(100, 100, varied=True), chunk=4000)+ code, out = run_main(monkeypatch, capsys, tmp_path, console, "--expect", "GAME OK")+ assert code == 1 and "PASS" not in out+++def test_shots_run_with_shot_done_but_no_shot_fails(monkeypatch, capsys, tmp_path):+ code, out = run_main(monkeypatch, capsys, tmp_path, ["SHOT done"], "--expect", "SHOT done")+ assert code == 1 and "PASS" not in out+++def test_shots_run_that_finishes_one_good_shot_passes(monkeypatch, capsys, tmp_path):+ console = shot_lines("gameplay03", png_of_size(100, 100, varied=True), chunk=4000) + ["SHOT done"]+ code, out = run_main(monkeypatch, capsys, tmp_path, console, "--expect", "SHOT done")+ assert code == 0 and (tmp_path / "shots" / "gameplay03.png").exists()+++def test_a_blank_shot_is_rejected(tmp_path):+ c = wc.ShotCollector(tmp_path, size=(64, 36))+ with pytest.raises(ValueError, match="blank"):+ for line in shot_lines("gameplay03", png_of_size(64, 36), chunk=4000):+ c.feed(line)+ assert not list(tmp_path.glob("*.png"))+++def test_a_shot_that_is_not_a_png_is_rejected_even_without_a_size(tmp_path):+ c = wc.ShotCollector(tmp_path)+ with pytest.raises(ValueError, match="not a PNG"):+ for line in shot_lines("gameplay03", bytes(range(256)) * 3):+ c.feed(line)+ assert not list(tmp_path.glob("*.png"))+++def test_shots_run_with_a_blank_shot_then_shot_done_fails_and_writes_nothing(monkeypatch, capsys, tmp_path):+ """#2697 item 6 through web_check.main: a one-colour PNG is no capture."""+ console = shot_lines("gameplay03", png_of_size(100, 100), chunk=4000) + ["SHOT done"]+ code, out = run_main(monkeypatch, capsys, tmp_path, console, "--expect", "SHOT done")+ assert code == 1 and "PASS" not in out and "blank" in out and not list((tmp_path / "shots").glob("*"))+++def test_shots_run_with_non_png_bytes_then_shot_done_fails_and_writes_nothing(monkeypatch, capsys, tmp_path):+ console = shot_lines("gameplay03", bytes(range(256)) * 3, chunk=4000) + ["SHOT done"]+ code, out = run_main(monkeypatch, capsys, tmp_path, console, "--expect", "SHOT done")+ assert code == 1 and "PASS" not in out and "not a PNG" in out and not list((tmp_path / "shots").glob("*"))+++def test_a_png_with_a_good_header_and_a_damaged_body_is_rejected(tmp_path):+ """The SHA-256 is of the damaged bytes, so only the decode catches it."""+ png = bytearray(png_of_size(64, 36, varied=True))+ at = png.index(b"IDAT") + 12+ for i in range(at, at + 6):+ png[i] ^= 0xFF+ c = wc.ShotCollector(tmp_path, size=(64, 36))+ with pytest.raises(ValueError, match="not a PNG that decodes"):+ for line in shot_lines("gameplay03", bytes(png), chunk=4000):+ c.feed(line)+ assert not list(tmp_path.glob("*.png"))diff --git a/tools/web_check.py b/tools/web_check.pyindex a86704592..923501779 100644--- a/tools/web_check.py+++ b/tools/web_check.py@@ -1,6 +1,6 @@# /// script# requires-python = ">=3.11"-# dependencies = ["websockets==15.0.1"]+# dependencies = ["websockets==15.0.1", "pillow==12.3.0"]# ///"""Serve a Unity WebGL build on http://localhost and open it in Chrome; pass when the console shows every expected line,fail on a failure line or a timeout. Uses Chrome for Testing from the Playwright cache (macOS only, no npm needed) in@@ -15,7 +15,8 @@ Every run needs a positive check: a nonblank --expect, --startscreen, --persisteOptions: --query Q (page URL query, without '?'), --expect TEXT (repeatable), --fail REGEX (default: GOLDEN FAIL|SMOKE FAIL|BOOT FAIL),--timeout SECONDS (default 300), --stall SECONDS (fail when no console message arrives for that long; 0 = off),--swiftshader (software WebGL when there is no GPU), --dpr N (default 1), --shots DIR (reassemble the player's-"SHOT" console lines, from ?shot, into DIR/<pose>.png; a "SHOT done" with an unfinished shot fails the run),+"SHOT" console lines, from ?shot, into DIR/<pose>.png; a "SHOT done" with an unfinished shot, a blank or non-PNG shot, or a run that ends without "SHOT done" after a+finished shot fails the run),--persistence (play one normal turn, wait for its matching IndexedDB commit, reload and Continue, then play anotherturn and reload as soon as its matching commit arrives; both reloads must report the saved date, turn and hash), --startscreen new|recording (#908: on a freshprofile, the real start screen every player sees first: "new" presses New game, "recording" first presses Play the@@ -40,6 +41,7 @@ import base64import functoolsimport hashlibimport http.server+import ioimport jsonimport osimport re@@ -161,13 +163,15 @@ class Rejoin:class ShotCollector:"""Reassembles the PNGs Statecraft.Game.Map.VisualShots logs: "SHOT <pose> begin <n> <sha256>" then n lines"SHOT <pose> <i>/<n> <base64>" (any order). A finished shot is checked against its SHA-256 and written to- <out_dir>/<pose>.png (out_dir None: checked, not written)."""+ <out_dir>/<pose>.png (out_dir None: checked, not written). A shot that is not a decodable PNG, or has one colour+ throughout (a blank capture), is rejected. `done` turns True at "SHOT done" once at least one shot has finished."""def __init__(self, out_dir: Path | None, size: tuple[int, int] | None = None):self.out_dir, self.size = out_dir, sizeself.expect: dict[str, tuple[int, str]] = {}self.parts: dict[str, dict[int, str]] = {}self.written: list[Path] = []+ self.finished, self.done = 0, Falsedef feed(self, text: str) -> bool:"""True when text was a begin or part line (consumed: too long to print); False for anything else. "SHOT done"@@ -175,6 +179,8 @@ class ShotCollector:if text == "SHOT done" and self.expect:unfinished = ", ".join(f"{n}: {len(self.parts.get(n, {}))} of {k} parts" for n, (k, _) in self.expect.items())raise ValueError(f"SHOT done with unfinished shots ({unfinished})")+ if text == "SHOT done":+ self.done = self.finished > 0m = SHOT_BEGIN.match(text)if m:if int(m.group(2)) < 1:@@ -205,10 +211,21 @@ class ShotCollector:png = b""if hashlib.sha256(png).hexdigest() != digest:raise ValueError(f"SHOT {name}: SHA-256 mismatch (a console line was cut or lost)")+ if png[:8] != b"\x89PNG\r\n\x1a\n":+ raise ValueError(f"SHOT {name}: not a PNG")if self.size is not None:w, h = int.from_bytes(png[16:20], "big"), int.from_bytes(png[20:24], "big")if (w, h) != self.size:raise ValueError(f"SHOT {name}: {w}x{h}, expected {self.size[0]}x{self.size[1]}")+ try:+ from PIL import Image # lazy, like websockets: a run that takes no shots never needs it+ with Image.open(io.BytesIO(png)) as img:+ bands = img.convert("RGBA").getextrema()+ except Exception as e: # a PNG with a good header and a damaged body, or no Pillow+ raise ValueError(f"SHOT {name}: not a PNG that decodes ({e})") from e+ if all(lo == hi for lo, hi in bands):+ raise ValueError(f"SHOT {name}: blank, one colour throughout")+ self.finished += 1if self.out_dir is not None:self.out_dir.mkdir(parents=True, exist_ok=True)path = self.out_dir / f"{name}.png"@@ -963,6 +980,15 @@ def run_plan(a, command, buttons: StartButtons, tail: ConsoleTail, units: UnitsOreturn driver, re.compile(fail), {"complete": lambda: driver.done, "complete_what": what, "grace": DRIVER_GRACE}+def shots_complete(plan: dict, shots: ShotCollector) -> dict:+ """`plan` (run_plan's watch keywords) made to wait for the shot run too: with --shots, PASS needs "SHOT done" after at+ least one finished shot, however the other expectations are met (#2697 item 2)."""+ driver_done, driver_what = plan.get("complete"), plan.get("complete_what")+ what = "a finished shot and SHOT done"+ return {**plan, "complete": (lambda: driver_done() and shots.done) if driver_done else (lambda: shots.done),+ "complete_what": f"{driver_what} and {what}" if driver_what else what}++def parser() -> argparse.ArgumentParser:ap = argparse.ArgumentParser()ap.add_argument("build", type=Path, nargs="?", help="a Unity WebGL build folder, served on localhost (or use --url)")@@ -1068,6 +1094,8 @@ def main() -> int:page.open()print(f"viewport {w}x{h} at DPR {a.dpr:g}{' mobile' if a.mobile else ''} (expect res={res})")driver, fail, plan = run_plan(a, page.command, buttons, tail, units)+ if a.shots is not None:+ plan = shots_complete(plan, shots)def handle_text(text: str) -> bool:consumed = on_text(text)