Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

Tools: loadshot fails a capture that is not the page's size, and the profile checks its toggle list (Refs #3043) (#3063)

Eyal Golan3f495e949b62
diff --git a/tools/README.md b/tools/README.md
index d8572ba6a..a7800a7ee 100644
--- a/tools/README.md
+++ b/tools/README.md
@@ -102,8 +102,9 @@ Offline data tools (uv inline-script Python). Run from the repo root.
"Post-merge Unity run" below).
- `headed.py` drives a WebGL build in a headed Chrome for Testing over CDP (real GPU, real mouse events, a temporary
profile deleted on exit): `boot` (?bootlog phase timings, optional CPU throttling), `navpairs` (same-frame click pairs
- under ?navlog), `loadshot` (screenshots during the load) and `profile` (visual v1's `?vprofile` in a headed window at a
- chosen DPR); `boot --runs N --baseline MS` checks the boot budget. Its browser test runs only with `pytest --headed`.
+ under ?navlog), `loadshot` (screenshots during the load; each must be the page's CSS size times its pixel ratio, within
+ 1 px) and `profile` (visual v1's `?vprofile` in a headed window at a chosen DPR; every toggle and pose in `web_check.py`'s
+ lists, which `test_visual_toggles.py` checks against the C#); `boot --runs N --baseline MS` checks the boot budget. Its browser test runs only with `pytest --headed`.
- `yaml12.py` is how the tools, scripts and their tests read YAML. `yaml12.load` resolves plain scalars by the YAML 1.2
core schema and refuses duplicate keys, where `yaml.safe_load` follows YAML 1.1 (`yes` becomes True, `1:30` becomes
90, `2026-10-15` becomes a date). That matches YamlDotNet's reads into string fields, not its bool and int fields,
diff --git a/tools/headed.py b/tools/headed.py
index 601855c75..2fcbe4bc1 100644
--- a/tools/headed.py
+++ b/tools/headed.py
@@ -9,7 +9,8 @@ serves a WebGL build with web_check's handler, and drives it over one browser-le
boot boot-phase timings from ?bootlog (optionally under CPU throttling): where the start-up time goes
navpairs pairs of clicks on a screen button and a second target, d ms apart or in one frame, under ?navlog
- loadshot screenshots during the load and once ready; a boot-failure line ends the run with exit 1
+ loadshot screenshots during the load and once ready; a boot-failure line, or a capture that is blank after GAME OK,
+ does not decode or is not the page's CSS size times its pixel ratio, ends the run with exit 1
profile visual v1's ?vprofile in a headed 1920x1080 window at --dpr (frame rate uncapped)
wheel wheel zoom under ?camlog (#43): a touchpad-like swipe, mouse notches in pixels and lines, over the map and a panel
@@ -220,6 +221,11 @@ FIRST_FRAME_SCRIPT = """(() => {
})();"""
+# loadshot's expected capture size (#3043): Page.captureScreenshot with no clip captures the page's viewport in device
+# pixels, the CSS size times the ratio.
+PAGE_SIZE = "[window.innerWidth, window.innerHeight, window.devicePixelRatio]"
+
+
class Browser:
def __init__(self, build: Path, port=8766, width=WINDOW[0], height=WINDOW[1], dpr=None, uncapped=False,
viewport=None, keep_awake=False):
@@ -322,6 +328,16 @@ class Browser:
Path(path).write_bytes(base64.b64decode(data))
return path
+ async def page_size(self, sid) -> tuple[float, float, float]:
+ """The page's (innerWidth, innerHeight, devicePixelRatio) now; ValueError when the page answers with an exception
+ or no such value (a page mid-reload), RuntimeError (from send) when CDP refuses the call."""
+ r = await self.send("Runtime.evaluate", {"expression": PAGE_SIZE, "returnByValue": True}, session=sid)
+ value = r.get("result", {}).get("value")
+ if "exceptionDetails" in r or not (isinstance(value, list) and len(value) == 3
+ and all(isinstance(v, (int, float)) and v > 0 for v in value)):
+ raise ValueError(f"no page size from Runtime.evaluate: {r}")
+ return tuple(value)
+
async def click(self, sid, x, y):
for e in burst_events([(x, y)]):
await self.send("Input.dispatchMouseEvent", e, session=sid)
@@ -428,6 +444,42 @@ def shot_error(path, blank_is_error: bool) -> str | None:
return None
+def png_size(path) -> tuple[int, int]:
+ """The width and height in a PNG's IHDR header (as web_check's ShotCollector reads them)."""
+ head = Path(path).read_bytes()[:24]
+ return int.from_bytes(head[16:20], "big"), int.from_bytes(head[20:24], "big")
+
+
+def size_error(path, page) -> str | None:
+ """Why the PNG at `path` (one shot_error passed) is not the capture of a page of `page` = (innerWidth, innerHeight,
+ devicePixelRatio): its header size is more than 1 px from round(CSS size x ratio) in either dimension (1 px for a
+ fractional ratio's rounding). #3043: the window keeps its size (the #2700 caution), so the page reports what it is."""
+ w, h = png_size(path)
+ cw, ch, dpr = page
+ ew, eh = round(cw * dpr), round(ch * dpr)
+ if abs(w - ew) > 1 or abs(h - eh) > 1:
+ return f"{path} is {w}x{h}, the page is {cw:g}x{ch:g} CSS px at DPR {dpr:g} ({ew}x{eh})"
+ return None
+
+
+class CaptureFailed(Exception):
+ """A loadshot capture that is no capture; the message is the FAIL reason."""
+
+
+async def capture(b, sid, path, blank_is_error: bool) -> str:
+ """loadshot's capture: the page size read just before the screenshot, then shot_error and size_error. Returns the
+ line to print, which records the PNG and page sizes; raises CaptureFailed with the FAIL reason."""
+ try:
+ page = await b.page_size(sid)
+ except (RuntimeError, ValueError, asyncio.TimeoutError) as e:
+ raise CaptureFailed(f"could not read the page size before {path} ({e})") from e
+ await b.shot(sid, path)
+ if error := (shot_error(path, blank_is_error) or size_error(path, page)):
+ raise CaptureFailed(error)
+ w, h = png_size(path)
+ return f"{path} {w}x{h}, page {page[0]:g}x{page[1]:g} CSS px at DPR {page[2]:g}"
+
+
async def loadshot(args):
async with Browser(args.build) as b:
sid = await b.open("bootlog", args.cpu)
@@ -438,22 +490,18 @@ async def loadshot(args):
if "BOOT FAIL" in line:
print(f"FAIL: {line}")
return 1
- 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 1
- await asyncio.sleep(2)
- print(line)
- path = await b.shot(sid, args.out + "-after.png")
- if error := shot_error(path, blank_is_error=True):
- print(f"FAIL: {error}")
+ try:
+ print(await capture(b, sid, args.out + "-loading.png", blank_is_error=False))
+ line = await b.wait_for(sid, r"^GAME OK|BOOT FAIL")
+ if "BOOT FAIL" in line:
+ print(f"FAIL: {line}")
+ return 1
+ await asyncio.sleep(2)
+ print(line)
+ print(await capture(b, sid, args.out + "-after.png", blank_is_error=True))
+ except CaptureFailed as e:
+ print(f"FAIL: {e}")
return 1
- print(path)
return 0
diff --git a/tools/tests/test_headed.py b/tools/tests/test_headed.py
index 343789fa1..c8d8e0866 100644
--- a/tools/tests/test_headed.py
+++ b/tools/tests/test_headed.py
@@ -137,21 +137,27 @@ 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 png(path, varied=True):
- """A real PNG at `path`: a gradient, or one colour (a blank capture)."""
+def png(path, varied=True, size=(8, 8)):
+ """A real PNG at `path` of `size` pixels: a gradient, or one colour (a blank capture)."""
from PIL import Image
- im = Image.new("RGB", (8, 8), (40, 60, 80))
+ w, h = size
+ im = Image.new("RGB", (w, h), (40, 60, 80))
if varied:
- im.putdata([(x * 30, y * 30, 90) for y in range(8) for x in range(8)])
+ im.putdata([(x * 30 % 256, y * 30 % 256, 90) for y in range(h) for x in range(w)])
im.save(path)
class FakeBrowser:
- """headed.Browser without Chrome: wait_for returns the queued lines; shot writes the PNG the test queued (a gradient by default)."""
+ """headed.Browser without Chrome: wait_for returns the queued lines; shot writes the PNG the test queued (a gradient by
+ default, 8x8); page_size answers as Runtime.evaluate would, with the queued (innerWidth, innerHeight, devicePixelRatio)
+ (8, 8, 1 by default) or raises a queued exception."""
waits: list[str] = []
console: list[str] = []
shots: list = []
contents: list = [] # per shot, in order: "varied", "blank" or "garbage"
+ png_sizes: list = [] # per shot, in order: the PNG's (width, height)
+ pages: list = [] # per page_size call, in order: (width, height, dpr) or an exception
+ calls: list = [] # "page_size" and "shot", in the order loadshot made them
def __init__(self, *args, **kwargs):
pass
@@ -175,13 +181,22 @@ class FakeBrowser:
async def shot(self, sid, path):
FakeBrowser.shots.append(path)
+ FakeBrowser.calls.append("shot")
kind = FakeBrowser.contents.pop(0) if FakeBrowser.contents else "varied"
+ size = FakeBrowser.png_sizes.pop(0) if FakeBrowser.png_sizes else (8, 8)
if kind == "garbage":
Path(path).write_bytes(b"not a png")
else:
- png(path, varied=kind == "varied")
+ png(path, varied=kind == "varied", size=size)
return path
+ async def page_size(self, sid):
+ FakeBrowser.calls.append("page_size")
+ page = FakeBrowser.pages.pop(0) if FakeBrowser.pages else (8, 8, 1)
+ if isinstance(page, Exception):
+ raise page
+ return page
+
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
@@ -199,11 +214,13 @@ def test_loadshot_exits_1_on_a_boot_failure_before_or_after_loading(monkeypatch,
assert "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`."""
+def run_loadshot(monkeypatch, tmp_path, contents, png_sizes=(), pages=()):
+ """loadshot through headed.main on a healthy boot whose two screenshots hold `contents` at `png_sizes`, on a page
+ that reports `pages` (8x8 PNGs of an 8x8 page at DPR 1 by default)."""
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), []
+ FakeBrowser.png_sizes, FakeBrowser.pages, FakeBrowser.calls = list(png_sizes), list(pages), []
return headed.main(["loadshot", "--build", str(tmp_path), "--out", str(tmp_path / "shot")])
@@ -225,6 +242,74 @@ def test_loadshot_exits_1_on_a_capture_that_does_not_decode(monkeypatch, tmp_pat
assert "FAIL" in capsys.readouterr().out
+def test_loadshot_exits_1_when_a_capture_is_not_the_page_size_times_its_pixel_ratio(monkeypatch, tmp_path, capsys):
+ """#3043 item 1: a capture of the wrong size used to pass. The expected size is the page's own innerWidth x
+ innerHeight times its devicePixelRatio, read just before each capture, so the window and viewport stay as they are
+ (the #2700 caution); more than 1 px off in either dimension is a failure."""
+ for pngs, pages, wrong in (([(8, 8), (16, 8)], [(8, 8, 1), (8, 8, 1)], "16x8"), # the capture after GAME OK
+ ([(8, 4), (16, 8)], [(8, 4, 2), (8, 4, 2)], "8x4"), # CSS size on a DPR 2 page
+ ([(14, 8), (16, 7)], [(9, 5, 1.5), (9, 5, 1.5)], "16x7"), # 2 px wide of 14x8
+ ([(8, 8), (8, 6)], [(8, 8, 1), (8, 8, 1)], "8x6")): # 2 px short
+ assert run_loadshot(monkeypatch, tmp_path, ["varied", "varied"], pngs, pages) == 1, (pngs, pages)
+ out = capsys.readouterr().out
+ assert "FAIL:" in out and wrong in out, out
+
+
+def test_loadshot_passes_a_capture_the_page_size_times_its_pixel_ratio_and_records_both(monkeypatch, tmp_path, capsys):
+ """#3043 item 1: DPR 2 (a Retina screen: device pixels, twice the CSS size), DPR 1, and 1 px of rounding for a
+ fractional ratio (9 x 1.5 = 13.5) all pass; each capture line records the PNG and page sizes."""
+ for pngs, pages, recorded in (([(16, 8), (16, 8)], [(8, 4, 2), (8, 4, 2)], "16x8, page 8x4 CSS px at DPR 2"),
+ ([(8, 8), (8, 8)], [(8, 8, 1), (8, 8, 1)], "8x8, page 8x8 CSS px at DPR 1"),
+ ([(13, 7), (14, 8)], [(9, 5, 1.5), (9, 5, 1.5)], "13x7, page 9x5 CSS px at DPR 1.5")):
+ assert run_loadshot(monkeypatch, tmp_path, ["varied", "varied"], pngs, pages) == 0, (pngs, pages)
+ out = capsys.readouterr().out
+ assert "FAIL" not in out and recorded in out, out
+ assert FakeBrowser.calls == ["page_size", "shot", "page_size", "shot"] # read just before each capture
+
+
+def test_loadshot_exits_1_when_the_page_size_cannot_be_read(monkeypatch, tmp_path, capsys):
+ """#3043 item 1: a page mid-reload (Runtime.evaluate fails, or answers with no value) is a failure, not a pass."""
+ for pages, shots in (([RuntimeError("Runtime.evaluate: Execution context was destroyed")], 0),
+ ([(8, 8, 1), ValueError("no page size (exceptionDetails)")], 1)):
+ assert run_loadshot(monkeypatch, tmp_path, ["varied", "varied"], pages=pages) == 1
+ out = capsys.readouterr().out
+ assert "FAIL:" in out and "page size" in out, out
+ assert len(FakeBrowser.shots) == shots
+
+
+def test_page_size_reads_the_window_and_ratio_over_runtime_evaluate(tmp_path):
+ """The real Browser.page_size: one Runtime.evaluate on the page's session, by value; an exception in the page or a
+ missing value raises, so loadshot fails instead of guessing."""
+ import shutil
+ b = headed.Browser(tmp_path)
+ answers, sent = [{"result": {"type": "object", "value": [1520, 640, 2]}},
+ {"result": {"type": "object"}, "exceptionDetails": {"text": "Uncaught"}}], []
+
+ async def send(method, params=None, session=None, timeout=60):
+ sent.append((method, params, session))
+ return answers.pop(0)
+ b.send = send
+ assert asyncio.run(b.page_size("s1")) == (1520, 640, 2)
+ method, params, session = sent[0]
+ assert method == "Runtime.evaluate" and session == "s1" and params["returnByValue"] is True
+ for name in ("innerWidth", "innerHeight", "devicePixelRatio"):
+ assert name in params["expression"]
+ with pytest.raises(ValueError, match="page size"):
+ asyncio.run(b.page_size("s1"))
+ shutil.rmtree(b.profile, ignore_errors=True)
+
+
+def test_profile_exits_1_on_a_run_missing_a_configuration_from_every_pose(monkeypatch, tmp_path, capsys):
+ """#3043 item 2 through headed.main: every pose has the same configurations, so the per-pose check passed this run;
+ the toggles the game registers (web_check.VISUAL_TOGGLES) are missing from all of them."""
+ from test_web_check_shots import profile_lines
+ monkeypatch.setattr(headed, "Browser", FakeBrowser)
+ FakeBrowser.waits, FakeBrowser.console = ["PROFILE visual done"], profile_lines(labels=("all", "none"))
+ assert headed.main(["profile", "--build", str(tmp_path)]) == 1
+ out = capsys.readouterr().out
+ assert "FAIL" in out and "-labels" in out, 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
diff --git a/tools/tests/test_visual_toggles.py b/tools/tests/test_visual_toggles.py
new file mode 100644
index 000000000..0f04eb90a
--- /dev/null
+++ b/tools/tests/test_visual_toggles.py
@@ -0,0 +1,104 @@
+"""#3043 item 2: web_check's expected toggle and pose lists (what `profile` checks a ?vprofile run against) match the C#.
+
+FrameProfile.Run prices "all", "-<name>" for each VisualToggles name registered at run time, then "none", at each
+PromoPose.All pose (plus "opening" and PromoPose.CloseUps under vclose). The toggles are registered by the features
+themselves, across the map code, some through name constants; this reads every VisualToggles.Register call in
+unity/Assets/Scripts and resolves its name, so a toggle added, renamed or removed in C# fails here until the list follows.
+"""
+import re
+from pathlib import Path
+
+import web_check as wc
+
+REPO = Path(__file__).resolve().parents[2]
+SCRIPTS = REPO / "unity/Assets/Scripts"
+REGISTER = re.compile(r"\bVisualToggles\.Register\(\s*([A-Za-z_][\w.]*|\"[^\"]*\")\s*,")
+
+
+def code(path: Path) -> str:
+ """The file without its // and /// comments (the doc comments quote Register calls as examples)."""
+ return "\n".join(line.split("//", 1)[0] for line in path.read_text(encoding="utf-8").splitlines())
+
+
+def class_file(name: str) -> Path:
+ hits = [p for p in SCRIPTS.rglob("*.cs") if re.search(rf"\bclass {re.escape(name)}\b", code(p))]
+ assert len(hits) == 1, f"class {name}: {hits}"
+ return hits[0]
+
+
+def constant(path: Path, name: str) -> str:
+ """The string value of the const `name` declared in `path` (one declaration may list several: `A = "a", B = "b"`)."""
+ m = re.search(rf"\bconst string\b[^;]*?\b{re.escape(name)}\s*=\s*\"([^\"]*)\"", code(path), re.S)
+ assert m, f"{path.relative_to(REPO)}: no const string {name}"
+ return m.group(1)
+
+
+def registered() -> dict[str, set[str]]:
+ """Every toggle name a VisualToggles.Register call in the game code passes, with the files that register it."""
+ names: dict[str, set[str]] = {}
+ for path in sorted(SCRIPTS.rglob("*.cs")):
+ for arg in REGISTER.findall(code(path)):
+ if arg.startswith('"'):
+ name = arg.strip('"')
+ elif "." in arg:
+ cls, const = arg.rsplit(".", 1)
+ name = constant(class_file(cls.rsplit(".", 1)[-1]), const)
+ else:
+ name = constant(path, arg)
+ names.setdefault(name, set()).add(path.relative_to(SCRIPTS).as_posix())
+ return names
+
+
+def test_the_expected_toggles_are_the_ones_the_game_registers():
+ found = registered()
+ assert len(found) >= 15, found # the parse still sees the map's registrations
+ expected = set(wc.VISUAL_TOGGLES) | set(wc.OPTIONAL_VISUAL_TOGGLES)
+ assert not set(wc.VISUAL_TOGGLES) & set(wc.OPTIONAL_VISUAL_TOGGLES)
+ assert sorted(found) == sorted(expected), (
+ f"registered in C# only: {sorted(set(found) - expected)}; listed in web_check only: {sorted(expected - set(found))}")
+ assert len(wc.VISUAL_TOGGLES) == len(set(wc.VISUAL_TOGGLES))
+
+
+def test_name_constants_resolve_and_unrelated_constants_are_not_toggles():
+ found = registered()
+ assert "Map/MapBorders.cs" in found["borders"] # MapBorders.ToggleName
+ assert found["grounddetail"] == {"Map/GroundDetail.cs"} and found["groundscrub"] == {"Map/GroundDetail.cs"}
+ assert found["train"] == {"Map/Routes/RouteLayer.cs"} # TrainToggle, registered in two branches
+ assert "city-projects-toggle" not in found # GddHexPanel.ToggleName is a UI element name
+
+
+def test_the_furrows_toggle_is_expected_in_every_profile():
+ """#3070 (#2917) registers "furrows" (GroundDetail.FurrowToggle) with the ground detail pass, beside "grounddetail" and
+ "groundscrub", on every map build, so every ?vprofile run prices "-furrows": a required toggle, not an optional one."""
+ found = registered()
+ assert found.get("furrows") == {"Map/GroundDetail.cs"}, found.get("furrows")
+ assert "furrows" in wc.VISUAL_TOGGLES and "furrows" not in wc.OPTIONAL_VISUAL_TOGGLES
+
+
+def test_the_optional_toggles_are_the_flag_only_ones():
+ """The train is built only for a train mode or from its service date (RouteLayer.Build) and the unit showcase only
+ under ?units (UnitShowcase.Requested, GameRoot): a plain ?vprofile run may lack them. Every other toggle is expected."""
+ assert set(wc.OPTIONAL_VISUAL_TOGGLES) == {"train", "unitshowcase"}
+ route = code(SCRIPTS / "Map/Routes/RouteLayer.cs")
+ assert re.search(r"if \(trainRoute != null && train == TrainMode\.Service\)", route)
+ root = code(SCRIPTS / "UI/GameRoot.cs")
+ assert re.search(r"UnitShowcase\.Requested\(\)\)\s*\n\s*Statecraft\.Game\.Map\.Units\.UnitShowcase\.Spawn\(", root)
+
+
+def test_the_expected_poses_are_frame_profiles():
+ profile, pose = code(SCRIPTS / "Map/FrameProfile.cs"), code(SCRIPTS / "Map/PromoPose.cs")
+ assert 'foreach (var name in VisualToggles.Names) configs.Add(("-" + name, name));' in profile
+ assert "new List<PromoPose>(PromoPose.All)" in profile and "poses.AddRange(PromoPose.CloseUps);" in profile
+
+ def names(member):
+ m = re.search(rf"\b{member} {{ get; }} = new\[\]\s*\{{(.*?)\}};", pose, re.S)
+ assert m, member
+ body = m.group(1)
+ literal = re.findall(r'new PromoPose\("([^"]+)"', body)
+ if literal:
+ return literal
+ return [re.search(rf"\b{field} = new PromoPose\(\"([^\"]+)\"", pose).group(1)
+ for field in re.findall(r"[A-Za-z_]\w*", body)]
+
+ assert list(wc.PROFILE_POSES) == names("All")
+ assert set(wc.OPTIONAL_PROFILE_POSES) == {*re.findall(r'new PromoPose\("([^"]+)"', profile), *names("CloseUps")}
diff --git a/tools/tests/test_web_check_shots.py b/tools/tests/test_web_check_shots.py
index 24733643e..06246872c 100644
--- a/tools/tests/test_web_check_shots.py
+++ b/tools/tests/test_web_check_shots.py
@@ -106,7 +106,8 @@ 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):
+def profile_lines(poses=wc.PROFILE_POSES, labels=("all", *(f"-{t}" for t in wc.VISUAL_TOGGLES), "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 = []
@@ -138,6 +139,23 @@ def test_a_partial_profile_is_an_error_even_with_the_done_line():
assert any("2 run lines, summary says 3" in e for e in wc.profile_errors(dropped, "1920x1080"))
+def test_a_configuration_missing_from_every_pose_is_an_error():
+ """#3043 item 2: the per-pose check compares poses with each other, so a run that drops one toggle's configuration
+ (or a pose) everywhere passed. The expected toggles and poses are web_check's lists, checked against the C# Register
+ calls by test_visual_toggles.py; the flag-only toggles and the vclose poses may be there or not."""
+ full = ("all", *(f"-{t}" for t in wc.VISUAL_TOGGLES), "none")
+ assert wc.profile_errors(profile_lines(labels=full, poses=wc.PROFILE_POSES), "1920x1080") == []
+ for gone in ("-borders", "-labels", f"-{wc.VISUAL_TOGGLES[0]}"):
+ errors = wc.profile_errors(profile_lines(labels=[l for l in full if l != gone], poses=wc.PROFILE_POSES), "1920x1080")
+ assert any(f"'{gone}'" in e for e in errors), (gone, errors)
+ errors = wc.profile_errors(profile_lines(labels=full, poses=wc.PROFILE_POSES[1:]), "1920x1080")
+ assert any(f"pose {wc.PROFILE_POSES[0]}" in e for e in errors), errors
+ extra = (*full[:-1], *(f"-{t}" for t in wc.OPTIONAL_VISUAL_TOGGLES), "none")
+ assert wc.profile_errors(profile_lines(labels=extra, poses=(*wc.PROFILE_POSES, *wc.OPTIONAL_PROFILE_POSES)), "1920x1080") == []
+ moving = tuple(f"{p}-moving" for p in wc.PROFILE_POSES) # a ?vmoving run's poses (FrameProfile.cs)
+ assert wc.profile_errors(profile_lines(labels=full, poses=moving), "1920x1080") == []
+
+
def test_measurement_windows_are_kept_awake():
flags = wc.chrome_flags("/tmp/p", swiftshader=False)
for flag in ("--disable-backgrounding-occluded-windows", "--disable-renderer-backgrounding",
diff --git a/tools/web_check.py b/tools/web_check.py
index 2cb1e76d8..4038df42f 100644
--- a/tools/web_check.py
+++ b/tools/web_check.py
@@ -93,6 +93,16 @@ 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}"
+# What a ?vprofile run prices (#3043): FrameProfile.Run's "-<name>" configuration for each VisualToggles name and its
+# PromoPose.All poses. test_visual_toggles.py checks these against the C# Register calls and PromoPose. The optional ones
+# may be there or not: the train (a train mode or its service date) and the unit showcase (?units) register only then,
+# and "opening" and PromoPose.CloseUps are priced only under vclose.
+VISUAL_TOGGLES = ("armisticelines", "borders", "foam", "furrows", "grade", "grid", "grounddetail", "groundscrub", "haze",
+ "kits", "labels", "land", "routes", "seacalm", "seatexture", "shadows", "siteground", "tiltshift",
+ "trees", "units", "water")
+OPTIONAL_VISUAL_TOGGLES = ("train", "unitshowcase")
+PROFILE_POSES = ("gameplay03", "diorama02")
+OPTIONAL_PROFILE_POSES = ("opening", "tel_aviv30", "jaffa12")
PROFILE_RUN = re.compile(r"PROFILE visual=(\S+) pose=(\S+) ")
PROFILE_SUMMARY = re.compile(r"PROFILE summary visual=(\S+) pose=(\S+) runs=(\d+)")
@@ -100,7 +110,8 @@ 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, 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."""
+ configuration whose summary line is missing or counts other runs than the run lines logged; or (#3043) a run missing
+ a VISUAL_TOGGLES configuration or a PROFILE_POSES pose from every pose (a ?vmoving run's poses end in "-moving")."""
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:
@@ -114,9 +125,12 @@ def profile_errors(lines, expected: str) -> list[str]:
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"):
+ for label in ("all", *(f"-{t}" for t in VISUAL_TOGGLES), "none"):
if runs and label not in labels:
errors.append(f"no PROFILE run of the '{label}' configuration")
+ for pose in PROFILE_POSES:
+ if runs and not any(p in (pose, f"{pose}-moving") for p, _ in counts):
+ errors.append(f"pose {pose} has no PROFILE run")
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')}")