A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Headed tools: loadshot rejects an undecodable or blank capture; a partial profile fails (Refs #2697 items 4, 5) (#2897)
Beri5f65da781113
diff --git a/tools/headed.py b/tools/headed.pyindex a9812adff..83536e1ae 100644--- a/tools/headed.py+++ b/tools/headed.py@@ -1,6 +1,6 @@# /// script# requires-python = ">=3.12"-# dependencies = ["websockets==15.0.1"]+# dependencies = ["websockets==15.0.1", "pillow==12.3.0"]# ///"""Headed browser checks over the Chrome DevTools Protocol (CDP): real GPU (ANGLE Metal), real mouse events.@@ -379,6 +379,21 @@ async def navpairs(args):return results+def shot_error(path, blank_is_error: bool) -> str | None:+ """Why the PNG at `path` is no capture: it does not decode, or (blank_is_error) it is one colour throughout. #2697: a+ loadshot run used to print whatever Chrome wrote. The loading screenshot is only decoded: a plain loading screen is+ legitimate, the one after GAME OK is not."""+ from PIL import Image+ try:+ with Image.open(path) as im:+ extrema = im.convert("RGBA").getextrema()+ except Exception as e:+ return f"{path} is not a PNG that decodes ({e})"+ if blank_is_error and all(lo == hi for lo, hi in extrema):+ return f"{path} is blank (one colour throughout)"+ return None++async def loadshot(args):async with Browser(args.build) as b:sid = await b.open("bootlog", args.cpu)@@ -389,14 +404,22 @@ async def loadshot(args):if "BOOT FAIL" in line:print(f"FAIL: {line}")return 1- print(await b.shot(sid, args.out + "-loading.png"))+ path = await b.shot(sid, args.out + "-loading.png")+ if error := shot_error(path, blank_is_error=False):+ print(f"FAIL: {error}")+ return 1+ print(path)line = await b.wait_for(sid, r"^GAME OK|BOOT FAIL")if "BOOT FAIL" in line:print(f"FAIL: {line}")return 1await asyncio.sleep(2)print(line)- print(await b.shot(sid, args.out + "-after.png"))+ path = await b.shot(sid, args.out + "-after.png")+ if error := shot_error(path, blank_is_error=True):+ print(f"FAIL: {error}")+ return 1+ print(path)return 0diff --git a/tools/tests/test_headed.py b/tools/tests/test_headed.pyindex f9bc7db11..cffeb422b 100644--- a/tools/tests/test_headed.py+++ b/tools/tests/test_headed.py@@ -137,45 +137,99 @@ def test_wheel_zoom_follows_a_swipe_and_keeps_a_notch_at_one_step():assert r["px150,px200,px49"]["px49"][0] == pytest.approx(0.49, abs=0.02)-def test_loadshot_exits_1_on_a_boot_failure_before_or_after_loading(monkeypatch, tmp_path, capsys):- """#2697: loadshot used to take its screenshots and exit 0 after BOOT FAIL. A BOOT FAIL already in the console when- the first wait returns "player started" (wait_for gives the first match) takes no loading screenshot either."""- shots = []+def png(path, varied=True):+ """A real PNG at `path`: a gradient, or one colour (a blank capture)."""+ from PIL import Image+ im = Image.new("RGB", (8, 8), (40, 60, 80))+ if varied:+ im.putdata([(x * 30, y * 30, 90) for y in range(8) for x in range(8)])+ im.save(path)- class FakeBrowser:- waits: list[str] = []- console: list[str] = []- def __init__(self, *args, **kwargs):- pass+class FakeBrowser:+ """headed.Browser without Chrome: wait_for returns the queued lines; shot writes the PNG the test queued (a gradient by default)."""+ waits: list[str] = []+ console: list[str] = []+ shots: list = []+ contents: list = [] # per shot, in order: "varied", "blank" or "garbage"- async def __aenter__(self):- return self+ def __init__(self, *args, **kwargs):+ pass- async def __aexit__(self, *args):- return None+ async def __aenter__(self):+ return self- async def open(self, *args):- return "sid"+ async def __aexit__(self, *args):+ return None- def lines(self, sid):- return list(FakeBrowser.console)+ async def open(self, *args):+ return "sid"- async def wait_for(self, *args, **kwargs):- line = FakeBrowser.waits.pop(0)- FakeBrowser.console.append(line)- return line+ def lines(self, sid):+ return list(FakeBrowser.console)- async def shot(self, sid, path):- shots.append(path)- return path+ async def wait_for(self, *args, **kwargs):+ line = FakeBrowser.waits.pop(0)+ FakeBrowser.console.append(line)+ return line++ async def shot(self, sid, path):+ FakeBrowser.shots.append(path)+ kind = FakeBrowser.contents.pop(0) if FakeBrowser.contents else "varied"+ if kind == "garbage":+ Path(path).write_bytes(b"not a png")+ else:+ png(path, varied=kind == "varied")+ return path+++def test_loadshot_exits_1_on_a_boot_failure_before_or_after_loading(monkeypatch, tmp_path, capsys):+ """#2697: loadshot used to take its screenshots and exit 0 after BOOT FAIL. A BOOT FAIL already in the console when+ the first wait returns "player started" (wait_for gives the first match) takes no loading screenshot either."""+ shots = FakeBrowser.shotsmonkeypatch.setattr(headed, "Browser", FakeBrowser)for waits, buffered, expected_shots in ((["BOOT FAIL content missing"], [], 0),(["BOOT phase=player started", "BOOT FAIL scene"], [], 1),(["BOOT phase=player started"], ["BOOT FAIL late"], 0)):shots.clear()- FakeBrowser.waits, FakeBrowser.console = list(waits), list(buffered)+ FakeBrowser.waits, FakeBrowser.console, FakeBrowser.contents = list(waits), list(buffered), []assert headed.main(["loadshot", "--build", str(tmp_path), "--out", str(tmp_path / "shot")]) == 1assert len(shots) == expected_shotsassert "FAIL: BOOT FAIL" in capsys.readouterr().out+++def run_loadshot(monkeypatch, tmp_path, contents):+ """loadshot through headed.main on a healthy boot whose two screenshots hold `contents`."""+ monkeypatch.setattr(headed, "Browser", FakeBrowser)+ FakeBrowser.waits = ["BOOT phase=player started", "GAME OK 1948-05-15 turn 0 hash 00"]+ FakeBrowser.console, FakeBrowser.contents, FakeBrowser.shots = [], list(contents), []+ return headed.main(["loadshot", "--build", str(tmp_path), "--out", str(tmp_path / "shot")])+++def test_loadshot_passes_when_both_captures_are_real_and_a_plain_loading_screen_is_fine(monkeypatch, tmp_path):+ assert run_loadshot(monkeypatch, tmp_path, ["varied", "varied"]) == 0+ assert run_loadshot(monkeypatch, tmp_path, ["blank", "varied"]) == 0 # the owner's #2700 caution: a plain loading screen+++def test_loadshot_exits_1_on_a_blank_capture_after_the_game_is_ready(monkeypatch, tmp_path, capsys):+ """#2697 item 4: a blank screenshot after GAME OK is no capture."""+ assert run_loadshot(monkeypatch, tmp_path, ["varied", "blank"]) == 1+ out = capsys.readouterr().out+ assert "FAIL" in out and "blank" in out+++def test_loadshot_exits_1_on_a_capture_that_does_not_decode(monkeypatch, tmp_path, capsys):+ for contents in (["garbage", "varied"], ["varied", "garbage"]):+ assert run_loadshot(monkeypatch, tmp_path, contents) == 1, contents+ assert "FAIL" in capsys.readouterr().out+++def test_profile_exits_1_on_a_partial_profile_and_0_on_a_whole_one(monkeypatch, tmp_path, capsys):+ """#2697 item 5 through headed.main: the done line alone does not make a profile."""+ from test_web_check_shots import profile_lines+ monkeypatch.setattr(headed, "Browser", FakeBrowser)+ for lines, code in ((profile_lines(), 0), ([profile_lines()[0], "PROFILE visual done"], 1)):+ FakeBrowser.waits, FakeBrowser.console = ["PROFILE visual done"], list(lines)+ assert headed.main(["profile", "--build", str(tmp_path)]) == code+ assert ("FAIL" in capsys.readouterr().out) == (code == 1)diff --git a/tools/tests/test_web_check_shots.py b/tools/tests/test_web_check_shots.pyindex 5f1eb2ece..24733643e 100644--- a/tools/tests/test_web_check_shots.py+++ b/tools/tests/test_web_check_shots.py@@ -106,12 +106,36 @@ def test_a_profile_line_at_another_resolution_is_an_error():assert "1920x937" in wc.res_error(good.replace("1920x1080", "1920x937"), "1920x1080")+def profile_lines(poses=("gameplay03", "diorama02"), labels=("all", "-labels", "none"), reps=3, res="1920x1080", done=True):+ """The console lines of a whole ?vprofile run as FrameProfile.Run logs them: per pose and configuration `reps` run+ lines, then a summary line; then the done line."""+ lines = []+ for pose in poses:+ for label in labels:+ lines += [f"PROFILE visual={label} pose={pose} res={res} scale=0.80 rep={r} frames=300 avg_ms=1.73 p95_ms=2.00" for r in range(reps)]+ lines.append(f"PROFILE summary visual={label} pose={pose} runs={reps} median_avg_ms=1.73 spread_ms=0.10 median_p95_ms=2.00")+ return lines + (["PROFILE visual done"] if done else [])++def test_profile_errors_need_run_lines_the_right_size_and_the_done_line():- run = "PROFILE visual=all pose=gameplay03 res=1920x1080 scale=0.80 rep=0 frames=300 avg_ms=1.73 p95_ms=2.00"- assert wc.profile_errors([run, "PROFILE visual done"], "1920x1080") == []+ assert wc.profile_errors(profile_lines(), "1920x1080") == []assert wc.profile_errors(["GAME OK"], "1920x1080") # no PROFILE lines at all- assert wc.profile_errors([run], "1920x1080") # never finished- assert wc.profile_errors([run.replace("1920x1080", "1728x860"), "PROFILE visual done"], "1920x1080")+ assert wc.profile_errors(profile_lines(done=False), "1920x1080") # never finished+ assert wc.profile_errors(profile_lines(res="1728x860"), "1920x1080")+++def test_a_partial_profile_is_an_error_even_with_the_done_line():+ """#2697 item 5: one run line and the done line used to pass."""+ full = profile_lines()+ one_run = [l for l in full if l.startswith("PROFILE visual=all pose=gameplay03 ")][:1] + ["PROFILE visual done"]+ assert wc.profile_errors(one_run, "1920x1080")+ no_summary = [l for l in full if not l.startswith("PROFILE summary visual=-labels pose=diorama02")]+ assert any("diorama02 visual -labels" in e for e in wc.profile_errors(no_summary, "1920x1080"))+ short_pose = [l for l in full if not (l.startswith("PROFILE") and "visual=none pose=diorama02" in l)]+ assert any("diorama02 has no run of none" in e for e in wc.profile_errors(short_pose, "1920x1080"))+ assert any("'none'" in e for e in wc.profile_errors(profile_lines(labels=("all", "-labels")), "1920x1080"))+ dropped = full.copy(); dropped.remove(next(l for l in full if l.startswith("PROFILE visual=all pose=gameplay03 ")))+ assert any("2 run lines, summary says 3" in e for e in wc.profile_errors(dropped, "1920x1080"))def test_measurement_windows_are_kept_awake():diff --git a/tools/web_check.py b/tools/web_check.pyindex 1d3872eff..7f63c5026 100644--- a/tools/web_check.py+++ b/tools/web_check.py@@ -93,14 +93,37 @@ def res_error(text: str, expected: str) -> str | None:return None if m is None or m.group(1) == expected else f"res={m.group(1)}, expected res={expected}: {text}"+PROFILE_RUN = re.compile(r"PROFILE visual=(\S+) pose=(\S+) ")+PROFILE_SUMMARY = re.compile(r"PROFILE summary visual=(\S+) pose=(\S+) runs=(\d+)")++def profile_errors(lines, expected: str) -> list[str]:- """What is wrong with a ?vprofile run's console lines: no PROFILE run lines, a run at another size, no done line."""+ """What is wrong with a ?vprofile run's console lines: no PROFILE run lines, a run at another size, no done line, or a+ partial profile (#2697): a pose that lacks a configuration another pose has, no "all" or "none" configuration, or a+ configuration whose summary line is missing or counts other runs than the run lines logged."""runs = [l for l in lines if l.startswith("PROFILE visual=")]errors = [e for e in (res_error(l, expected) for l in runs) if e]if not runs:errors.append("no PROFILE visual= lines")if "PROFILE visual done" not in lines:errors.append("no 'PROFILE visual done' line")+ counts, summarised = {}, {}+ for l in lines:+ if m := PROFILE_RUN.match(l):+ counts[(m[2], m[1])] = counts.get((m[2], m[1]), 0) + 1+ elif m := PROFILE_SUMMARY.match(l):+ summarised[(m[2], m[1])] = int(m[3])+ labels = {label for _, label in counts}+ for label in ("all", "none"):+ if runs and label not in labels:+ errors.append(f"no PROFILE run of the '{label}' configuration")+ for (pose, label), n in sorted(counts.items()):+ if summarised.get((pose, label)) != n:+ errors.append(f"pose {pose} visual {label}: {n} run lines, summary says {summarised.get((pose, label), 'nothing')}")+ for pose in sorted({pose for pose, _ in counts}):+ missing = sorted(labels - {label for p, label in counts if p == pose})+ if missing:+ errors.append(f"pose {pose} has no run of {', '.join(missing)}")return errors