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.

web_check: End turn skips each unit it selects (--startscreen, --persistence) (#1664)

Eyal Golan1263289453fa
diff --git a/tools/tests/test_web_check.py b/tools/tests/test_web_check.py
index a28d2c4f6..c087c8d9f 100644
--- a/tools/tests/test_web_check.py
+++ b/tools/tests/test_web_check.py
@@ -282,6 +282,154 @@ def test_page_query_adds_navlog_only_to_the_start_screen_runs():
assert wc.page_query(_args("--query", "golden")) == "golden"
+class FakeGame:
+ """Answers a driver's clicks as ?navlog's game does, through a real ConsoleTail: End turn (either layout's) selects a
+ unit while `units` still need orders, else ends the turn: a TURN line in the console EndTurn reads (a driver's own
+ TURN lines are fed by the test). The unit card is EN_CARD, its rows mirrored in Hebrew: a probe names the element under
+ it (a "map" one is taken by the map), and a click on Skip skips a unit."""
+
+ def __init__(self, units=0, card=None, hebrew=False, answers=True):
+ self.tail, self.units, self.answers = wc.ConsoleTail(), units, answers
+ self.card, self.hebrew, self.actions, self.turn = card or EN_CARD, hebrew, [], 1
+
+ def nav(self, what):
+ self.tail.feed(f"NAV f=1 t=1 {what}")
+
+ def at(self, x, y):
+ if self.hebrew:
+ x = wc.INFO_PANEL_LEFT + wc.INFO_PANEL_RIGHT - x
+ inside = wc.INFO_PANEL_LEFT <= x <= wc.INFO_PANEL_RIGHT and y >= 1080 - wc.INFO_PANEL_BOTTOM - wc.INFO_PANEL_MAX_HEIGHT
+ return next((name for (x0, x1, y0, y1), name in self.card if x0 <= x <= x1 and y0 <= y <= y1),
+ "info-region" if inside else "top-bar")
+
+ def __call__(self, action):
+ self.actions.append(action)
+ kind, _, at = action.partition(":")
+ if not self.answers or not at:
+ return
+ x, y = (int(v) for v in at.split(","))
+ if kind == "click" and (x, y) in (wc.END_TURN, wc.END_TURN_HE):
+ self.nav("ui click count=1 target=end-turn")
+ if self.units == 0:
+ self.tail.feed(f"TURN {self.turn} 1948-06-15 hash bb")
+ self.turn += self.units == 0
+ elif kind == "probe":
+ target = self.at(x, y)
+ if target == "map": # a press the UI does not take: the map's hex click
+ self.nav(f"map click at ({x}, {1080 - y}) overUi=False")
+ else:
+ self.nav(f"ui pointerdown id=0 at ({x}, {y}) target={target}")
+ elif kind == "click":
+ target = self.at(x, y)
+ self.nav(f"ui click count=1 target={target}")
+ self.units -= target == "info-skip"
+
+
+# The unit card of the RC build at 1920x1080 (English): ((x0, x1, y0, y1), the element there); elsewhere the description.
+EN_CARD = [((84, 536, 1010, 1064), "info-reason"), ((96, 200, 976, 1002), "info-skip"), ((206, 290, 976, 1002), "info-attack"),
+ ((96, 300, 930, 956), "info-defence"), ((306, 380, 930, 956), "info-move"), ((84, 536, 920, 1009), "VisualElement")]
+# Skip second in its line: found along the line, not at its start.
+SECOND_CARD = [((84, 536, 1010, 1064), "info-reason"), ((96, 180, 976, 1002), "info-move"), ((186, 300, 976, 1002), "info-skip"),
+ ((84, 536, 960, 1009), "VisualElement")]
+NO_SKIP_CARD = [((84, 536, 1010, 1064), "info-reason"), ((96, 180, 976, 1002), "info-move"), ((84, 536, 960, 1009), "VisualElement")]
+
+
+def _quiet():
+ """A PersistenceCheck's game, buttons and console."""
+ game = FakeGame()
+ return game, _buttons(), game.tail
+
+
+def _quiet_start():
+ """An English New game StartScreenCheck's game, recording, hebrew, buttons and console."""
+ game = FakeGame()
+ return game, False, False, _buttons(), game.tail
+
+
+def _end_turn(game, **kw):
+ return wc.EndTurn(game, game.tail, game.hebrew, settle=lambda s: None, answer=0.05, turn_wait=0.05, **kw)
+
+
+def test_end_turn_skips_each_unit_it_selects_then_ends_the_turn(capsys):
+ game = FakeGame(units=3)
+ assert _end_turn(game)() == 3 and game.units == 0
+ clicks = [a for a in game.actions if a.startswith("click:")]
+ assert clicks == _clicks(wc.END_TURN, (110, 998)) * 3 + _clicks(wc.END_TURN), "only End turn and Skip are left-clicked"
+ probes = [a for a in game.actions if a.startswith("probe:")]
+ assert probes.count("probe:110,998") == 3 and len(probes) == 7, "Skip is looked for once, then probed where it was"
+ assert "END TURN the turn ended after 3 Skip(s)" in capsys.readouterr().out
+
+
+def test_end_turn_with_no_unit_needing_orders_is_one_click():
+ game = FakeGame()
+ assert _end_turn(game)() == 0 and game.actions == _clicks(wc.END_TURN)
+
+
[email protected]("hebrew", [False, True])
+def test_end_turn_finds_skip_along_its_line_in_either_layout(hebrew):
+ game = FakeGame(units=1, card=SECOND_CARD, hebrew=hebrew)
+ assert _end_turn(game)() == 1
+ x = int([a for a in game.actions if a.startswith("click:")][1].split(":")[1].split(",")[0])
+ assert (wc.INFO_PANEL_LEFT + wc.INFO_PANEL_RIGHT - x if hebrew else x) in range(186, 301)
+ assert game.actions[-1] == "click:" + ",".join(map(str, wc.END_TURN_HE if hebrew else wc.END_TURN))
+
+
+def test_end_turn_fails_when_the_turn_never_ends():
+ game = FakeGame(units=100)
+ with pytest.raises(ValueError, match="END TURN FAIL End turn still selected a unit needing orders after 2 Skips"):
+ _end_turn(game, max_skips=2)()
+ assert game.units == 98
+
+
+def test_end_turn_fails_on_a_card_without_skip():
+ with pytest.raises(ValueError, match="card shows no info-skip .*order rows at y \\[998\\]"):
+ _end_turn(FakeGame(units=1, card=NO_SKIP_CARD))()
+
+
+def test_end_turn_fails_when_its_click_misses_end_turn():
+ with pytest.raises(ValueError, match="END TURN FAIL the click at \\(1840, 45\\) did not press end-turn"):
+ _end_turn(FakeGame(answers=False))()
+
+
+def test_a_click_that_does_not_press_skip_fails():
+ game = FakeGame(units=1)
+ probe_at = game.at
+ game.at = lambda x, y: probe_at(x, y) if game.actions[-1].startswith("probe:") else "info-hold" # the card moved
+ with pytest.raises(ValueError, match="END TURN FAIL the click at \\(110, 998\\) did not press info-skip"):
+ _end_turn(game)()
+
+
+def test_a_probe_that_reaches_the_map_fails_at_once():
+ game = FakeGame(units=1, card=[((0, 2000, 0, 2000), "map")])
+ with pytest.raises(ValueError, match="END TURN FAIL a press at \\(110, 1038\\) reached the map"):
+ _end_turn(game)()
+ assert sum(a.startswith("probe:") for a in game.actions) == 1
+
+
+def test_console_tail_waits_for_a_match_after_the_mark_from_another_thread():
+ tail = wc.ConsoleTail()
+ tail.feed("NAV f=1 t=1 ui click count=1 target=end-turn")
+ since = tail.mark()
+ assert tail.wait(wc.NAV_CLICK, since, 0, "end-turn") is None, "lines before the mark do not count"
+ threading.Timer(0.05, tail.feed, ["NAV f=2 t=2 ui click count=1 target=info-skip"]).start()
+ assert tail.wait(wc.NAV_CLICK, since, 5, "info-skip").group(1) == "info-skip"
+ assert tail.wait(wc.NAV_DOWN, since, 0) is None
+
+
+def test_watch_does_not_stall_while_a_driver_waits_on_lines_that_keep_coming(capsys):
+ inbox, t = queue.Queue(), [0.0]
+ inbox.put(line("GAME OK 1948-05-15 turn 0 hash aa"))
+
+ def on_text(text):
+ if text.startswith("GAME OK"):
+ t[0] += 30 # EndTurn's Skips took 30 s, the page logging all along
+ inbox.put(line("TURN 1 1948-06-15 hash bb"))
+ return False
+ rc = wc.watch(inbox, lambda: None, lambda: None, ["TURN 1"], re.compile("BOOT FAIL"), 300, now=lambda: t[0],
+ sleep=lambda s: t.__setitem__(0, t[0] + s), on_text=on_text, stall=20)
+ assert rc == 0, capsys.readouterr().out
+
+
def _committed_turn(check, generation, date, turn, digest):
receipt = f"{generation} {date} turn {turn} hash {digest}"
check.feed("AUTOSAVE PENDING " + receipt)
@@ -290,8 +438,9 @@ def _committed_turn(check, generation, date, turn, digest):
def test_persistence_check_reloads_after_a_settled_and_an_immediate_autosave(capsys):
- actions, sleeps = [], []
- check = wc.PersistenceCheck(actions.append, _buttons(), sleeps.append)
+ sleeps, game = [], FakeGame()
+ actions = game.actions
+ check = wc.PersistenceCheck(game, _buttons(), game.tail, sleeps.append)
check.feed("GAME OK 1948-05-15 turn 0 hash aa00")
check.feed("TURN 1 1948-06-01 turn 1 hash one") # malformed diagnostic is ignored
_committed_turn(check, 1, "1948-06-01", 1, "aaa1")
@@ -314,7 +463,7 @@ def _played_to_the_settled_reload(check):
def test_persistence_check_fails_when_the_immediate_reload_did_not_load_the_saved_turn():
- check = wc.PersistenceCheck(lambda action: None, _buttons(), lambda seconds: None)
+ check = wc.PersistenceCheck(*_quiet(), lambda seconds: None)
_played_to_the_settled_reload(check)
check.buttons.feed(LAID_OUT) # the reloaded page reports its own layout
check.feed("GAME OK 1948-06-15 turn 1 hash bb")
@@ -324,14 +473,14 @@ def test_persistence_check_fails_when_the_immediate_reload_did_not_load_the_save
def test_persistence_check_fails_when_the_settled_reload_did_not_load_the_saved_turn():
- check = wc.PersistenceCheck(lambda action: None, _buttons(), lambda seconds: None)
+ check = wc.PersistenceCheck(*_quiet(), lambda seconds: None)
_played_to_the_settled_reload(check)
with pytest.raises(ValueError, match="PERSISTENCE FAIL settled reload got 1948-05-15 turn 0"):
check.feed("GAME OK 1948-05-15 turn 0 hash aa")
def test_persistence_check_fails_when_continue_started_a_new_game():
- check = wc.PersistenceCheck(lambda action: None, _buttons(), lambda seconds: None)
+ check = wc.PersistenceCheck(*_quiet(), lambda seconds: None)
_played_to_the_settled_reload(check)
check.buttons.feed(LAID_OUT) # the reloaded page reports its own layout
check.feed("GAME OK 1948-06-15 turn 1 hash bb")
@@ -340,7 +489,7 @@ def test_persistence_check_fails_when_continue_started_a_new_game():
def test_persistence_check_fails_when_the_first_boot_is_not_a_fresh_game():
- check = wc.PersistenceCheck(lambda action: None, _buttons(), lambda seconds: None)
+ check = wc.PersistenceCheck(*_quiet(), lambda seconds: None)
with pytest.raises(ValueError, match="expected turn 0"):
check.feed("GAME OK 1948-06-15 turn 1 hash bb")
@@ -360,8 +509,9 @@ def _clicks(*points):
def test_start_screen_check_presses_new_game_then_end_turn_and_needs_turn_1(capsys):
- actions = []
- check = wc.StartScreenCheck(actions.append, recording=False, hebrew=False, buttons=_buttons(), settle=lambda s: None)
+ game = FakeGame()
+ actions = game.actions
+ check = wc.StartScreenCheck(game, recording=False, hebrew=False, buttons=_buttons(), tail=game.tail, settle=lambda s: None)
check.feed("GAME OK 1948-05-15 turn 0 hash aa")
assert actions == _clicks(AT["start-new-game"], wc.END_TURN)
assert not check.done
@@ -372,15 +522,15 @@ def test_start_screen_check_presses_new_game_then_end_turn_and_needs_turn_1(caps
def test_start_screen_check_fails_at_once_when_the_game_never_says_where_new_game_is():
- check = wc.StartScreenCheck(lambda a: None, False, False, buttons=_buttons(""), settle=lambda s: None)
+ check = wc.StartScreenCheck(lambda a: None, False, False, buttons=_buttons(""), tail=wc.ConsoleTail(), settle=lambda s: None)
with pytest.raises(ValueError, match="START SCREEN FAIL no centre for start-new-game"):
check.feed("GAME OK 1948-05-15 turn 0 hash aa")
def test_start_screen_check_plays_the_recording_first_and_waits_for_it_hebrew_layout():
- actions = []
- buttons = _buttons()
- check = wc.StartScreenCheck(actions.append, recording=True, hebrew=True, buttons=buttons, settle=lambda s: None)
+ game = FakeGame()
+ actions, buttons = game.actions, _buttons()
+ check = wc.StartScreenCheck(game, recording=True, hebrew=True, buttons=buttons, tail=game.tail, settle=lambda s: None)
check.feed("GAME OK 1948-05-15 turn 0 hash aa")
assert actions == _clicks(AT["start-listen"])
check.feed("TURN 1 1948-06-15 hash bb") # no New game before the recording plays
@@ -394,8 +544,8 @@ def test_start_screen_check_plays_the_recording_first_and_waits_for_it_hebrew_la
def test_start_screen_check_fails_on_a_saved_game_or_a_wrong_turn():
with pytest.raises(ValueError, match="START SCREEN FAIL the first boot is turn 3"):
- wc.StartScreenCheck(lambda a: None, False, False, _buttons(), lambda s: None).feed("GAME OK 1948-08-15 turn 3 hash aa")
- check = wc.StartScreenCheck(lambda a: None, False, False, _buttons(), lambda s: None)
+ wc.StartScreenCheck(*_quiet_start(), lambda s: None).feed("GAME OK 1948-08-15 turn 3 hash aa")
+ check = wc.StartScreenCheck(*_quiet_start(), lambda s: None)
check.feed("GAME OK 1948-05-15 turn 0 hash aa")
with pytest.raises(ValueError, match="START SCREEN FAIL End turn after New game logged turn 2"):
check.feed("TURN 2 1948-07-15 hash cc")
@@ -409,8 +559,9 @@ def test_query_value():
def test_start_screen_check_english_recording_uses_the_english_layout():
- actions = []
- check = wc.StartScreenCheck(actions.append, recording=True, hebrew=False, buttons=_buttons(), settle=lambda s: None)
+ game = FakeGame()
+ actions = game.actions
+ check = wc.StartScreenCheck(game, recording=True, hebrew=False, buttons=_buttons(), tail=game.tail, settle=lambda s: None)
check.feed("GAME OK 1948-05-15 turn 0 hash aa")
check.feed("RECORDING playing audio/declaration.wav (9.29 s, at 0.20 s)")
assert actions == _clicks(AT["start-listen"], AT["start-new-game"], wc.END_TURN)
@@ -421,9 +572,10 @@ def _args(*argv):
def _plan(*argv):
- driver, fail, plan = wc.run_plan(_args(*argv), lambda action: None, _buttons())
+ game = FakeGame()
+ driver, fail, plan = wc.run_plan(_args(*argv), game, _buttons(), game.tail)
if driver is not None:
- driver.settle = lambda seconds: None
+ driver.settle = driver.end_turn.settle = lambda seconds: None
return driver, fail, plan
@@ -445,7 +597,7 @@ def test_a_start_screen_run_fails_on_boot_fail_exceptions_and_the_recording_what
def test_the_start_screen_run_takes_the_hebrew_layout_from_the_query():
he, _, _ = _plan("--startscreen", "recording", "--query", "lang=he&smoke=0")
en, _, _ = _plan("--startscreen", "recording")
- assert (he.end_turn, en.end_turn) == (wc.END_TURN_HE, wc.END_TURN)
+ assert (he.end_turn.point, en.end_turn.point) == (wc.END_TURN_HE, wc.END_TURN)
def test_persistence_and_start_screen_are_separate_runs():
@@ -511,8 +663,9 @@ def test_mobile_only_flips_the_emulation_flag():
def test_persistence_check_does_not_reload_turn_two_before_its_commit_ack():
- actions = []
- check = wc.PersistenceCheck(actions.append, _buttons(), lambda seconds: None)
+ game = FakeGame()
+ actions = game.actions
+ check = wc.PersistenceCheck(game, _buttons(), game.tail, lambda seconds: None)
check.feed("GAME OK 1948-05-15 turn 0 hash aa")
check.feed("AUTOSAVE PENDING 1 1948-06-15 turn 1 hash bb")
check.feed("TURN 1 1948-06-15 hash bb")
@@ -536,8 +689,9 @@ def test_persistence_check_does_not_reload_turn_two_before_its_commit_ack():
"AUTOSAVE OK 2 1948-06-15 turn 1 hash bb", # old turn/date
])
def test_a_stale_or_mismatched_save_ack_cannot_authorize_reload(ack):
- actions = []
- check = wc.PersistenceCheck(actions.append, _buttons(), lambda seconds: None)
+ game = FakeGame()
+ actions = game.actions
+ check = wc.PersistenceCheck(game, _buttons(), game.tail, lambda seconds: None)
_played_to_the_settled_reload(check)
check.buttons.feed(LAID_OUT) # the reloaded page reports its own layout
check.feed("GAME OK 1948-06-15 turn 1 hash bb")
@@ -552,7 +706,7 @@ def test_a_stale_or_mismatched_save_ack_cannot_authorize_reload(ack):
def test_a_commit_timeout_fails_even_without_any_further_console_line():
clock = [0.0]
- check = wc.PersistenceCheck(lambda action: None, _buttons(), lambda seconds: None, now=lambda: clock[0], save_timeout=5)
+ check = wc.PersistenceCheck(*_quiet(), lambda seconds: None, now=lambda: clock[0], save_timeout=5)
check.feed("GAME OK 1948-05-15 turn 0 hash aa")
check.feed("TURN 1 1948-06-15 hash bb")
clock[0] = 5
@@ -561,14 +715,15 @@ def test_a_commit_timeout_fails_even_without_any_further_console_line():
def test_an_indexeddb_failure_fails_the_driver_loudly():
- check = wc.PersistenceCheck(lambda action: None, _buttons(), lambda seconds: None)
+ check = wc.PersistenceCheck(*_quiet(), lambda seconds: None)
with pytest.raises(ValueError, match="IndexedDB autosave failed"):
check.feed("AUTOSAVE FAIL 1 1948-06-15 turn 1 hash bb")
def test_commit_ack_before_turn_diagnostic_is_not_lost():
- actions = []
- check = wc.PersistenceCheck(actions.append, _buttons(), lambda seconds: None)
+ game = FakeGame()
+ actions = game.actions
+ check = wc.PersistenceCheck(game, _buttons(), game.tail, lambda seconds: None)
check.feed("GAME OK 1948-05-15 turn 0 hash aa")
check.feed("AUTOSAVE PENDING 1 1948-06-15 turn 1 hash bb")
check.feed("AUTOSAVE OK 1 1948-06-15 turn 1 hash bb")
@@ -579,7 +734,7 @@ def test_commit_ack_before_turn_diagnostic_is_not_lost():
def test_commit_timeout_is_polled_while_an_unrelated_expectation_is_still_missing():
clock = [0.0]
- check = wc.PersistenceCheck(lambda action: None, _buttons(), lambda seconds: None, now=lambda: clock[0], save_timeout=5)
+ check = wc.PersistenceCheck(*_quiet(), lambda seconds: None, now=lambda: clock[0], save_timeout=5)
check.feed("GAME OK 1948-05-15 turn 0 hash aa")
check.feed("TURN 1 1948-06-15 hash bb")
with pytest.raises(ValueError, match="no matching IndexedDB commit within 5s"):
diff --git a/tools/web_check.py b/tools/web_check.py
index 7574bef25..0039ea0f2 100644
--- a/tools/web_check.py
+++ b/tools/web_check.py
@@ -18,7 +18,8 @@ Options: --query Q (page URL query, without '?'), --expect TEXT (repeatable), --
--persistence (play one normal turn, wait for its matching IndexedDB commit, reload and Continue, then play another
turn 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 fresh
profile, the real start screen every player sees first: "new" presses New game, "recording" first presses Play the
-recording and waits for RECORDING playing; then End turn must log TURN 1; any console Exception, RECORDING failed or
+recording and waits for RECORDING playing; then End turn must log TURN 1, pressing "Skip this turn" on each unit End
+turn selects while units still need orders (EndTurn; --persistence ends its turns so too); any console Exception, RECORDING failed or
BOOT FAIL fails the run; add --query lang=he for the Hebrew layout). Both runs add ?navlog and click the start screen's
buttons where its "start buttons" line says they are (StartButtons).
The page is opened over the DevTools protocol with its viewport fixed to 1920x1080 at the DPR before it loads
@@ -270,8 +271,9 @@ class Page:
self.thread.join(5)
def command(self, name: str) -> None:
- """Runs one action on the page's CDP thread and waits for it: "reload", or "click:X,Y" (a left click at CSS
- pixels X, Y of the viewport)."""
+ """Runs one action on the page's CDP thread and waits for it: "reload", "click:X,Y" (a left click at CSS
+ pixels X, Y of the viewport), or "probe:X,Y" (a middle-button click there: EndTurn's probe, which no button, map
+ or camera acts on, while ?navlog names the element under it)."""
done, result = threading.Event(), []
self.commands.put((name, done, result))
if not done.wait(10):
@@ -319,6 +321,12 @@ class Page:
for kind in ("mousePressed", "mouseReleased"):
await call("Input.dispatchMouseEvent", {"type": kind, "x": x, "y": y, "button": "left",
"clickCount": 1}, sid)
+ elif name.startswith("probe:"):
+ x, y = (float(v) for v in name[len("probe:"):].split(","))
+ await call("Input.dispatchMouseEvent", {"type": "mouseMoved", "x": x, "y": y}, sid)
+ for kind in ("mousePressed", "mouseReleased"):
+ await call("Input.dispatchMouseEvent", {"type": kind, "x": x, "y": y, "button": "middle",
+ "clickCount": 1}, sid)
elif name == "reload":
await call("Page.reload", {"ignoreCache": True}, sid)
else:
@@ -438,6 +446,151 @@ class StartButtons:
return round(fx * self.viewport[0]), round(fy * self.viewport[1])
+class ConsoleTail:
+ """The console messages so far, numbered, fed from the stderr reader thread (like StartButtons), so a driver that is
+ waiting for the game's answer to its click sees it come in. `wait` returns the first match after mark `since`."""
+
+ KEEP = 5000
+
+ def __init__(self):
+ self.cond, self.lines, self.count = threading.Condition(), [], 0
+
+ def feed(self, text: str) -> None:
+ with self.cond:
+ self.count += 1
+ self.lines.append((self.count, text))
+ del self.lines[:-self.KEEP]
+ self.cond.notify_all()
+
+ def mark(self) -> int:
+ with self.cond:
+ return self.count
+
+ def wait(self, pattern: re.Pattern, since: int, timeout: float, group: str | None = None) -> re.Match | None:
+ """The first message numbered after `since` that `pattern` matches (with group(1) == `group` when given), waiting
+ up to `timeout` seconds for it; None when none comes."""
+ deadline = time.monotonic() + timeout
+ with self.cond:
+ while True:
+ for n, text in self.lines:
+ m = pattern.match(text) if n > since else None
+ if m and (group is None or m.group(1) == group):
+ return m
+ left = deadline - time.monotonic()
+ if left <= 0:
+ return None
+ self.cond.wait(left)
+
+
+# What ?navlog's NavEventLog says of a press and a click: the deepest UI element under the pointer, by name.
+NAV_DOWN = re.compile(r"^NAV f=\d+ t=\d+ ui pointerdown id=\d+ at \([^)]*\) target=(\S+)$")
+NAV_CLICK = re.compile(r"^NAV f=\d+ t=\d+ ui click count=\d+ target=(\S+)$")
+# A left press the map takes: not over the UI, or (#1617) on the unit card's text over a lit hex of its armed Move pick,
+# which moves the unit. So EndTurn finds Skip with the middle button, which only the UI's pointer events see.
+NAV_MAP = re.compile(r"^NAV f=\d+ t=\d+ map click at \([^)]*\) overUi=False$")
+# The unit card is the info panel (Statecraft.uss .info-panel: left 84 px, bottom 16 px, width 452 px, in both languages;
+# in Hebrew only its rows mirror). Its order buttons wrap in one row container (Game.uxml), whose lines each start at
+# the body's start edge (left, or right in Hebrew), under the unit's description lines and over the reason and notes.
+# Probes keep PROBE_INSET px inside the panel's frame.
+INFO_PANEL_LEFT, INFO_PANEL_RIGHT, INFO_PANEL_BOTTOM, INFO_PANEL_MAX_HEIGHT, PROBE_INSET = 84, 536, 16, 640, 26
+ORDER_ROW = {"build-camp", "build-housing", "info-defence", "info-primary-orders", "info-move", "info-fortify", "info-hold",
+ "info-skip", "info-attack", "info-send-home", "info-reinforce"}
+ABOVE_ORDERS = {"info-title", "info-subtitle", "info-region", "info-settlements", "info-localities", "info-placement"}
+SKIP = "info-skip"
+# Well over the units a turn has needing orders (8 on a new game, 9 on turn 2, 0.3.0 RC): a turn that never ends fails.
+MAX_SKIPS = 40
+
+
+class EndTurn:
+ """Ends the turn as a player does since #1527 U4: End turn selects a unit that still needs orders (HudPresenter) instead
+ of ending the turn, so press that unit's "Skip this turn" and End turn again, until the game logs the next TURN line, at
+ most `max_skips` times (GameRoot.Smoke's loop, through the browser). The unit card's buttons move with its text, so
+ Skip is found where the game draws it: a middle-button probe reports the element under it (?navlog NAV_DOWN) and acts
+ on nothing (a left press on the card's text can move the unit, NAV_MAP), then a left click presses Skip. A missed End
+ turn, a probe the map takes, a card with no Skip, or a turn that never ends fails at once. Returns the number of Skips."""
+
+ def __init__(self, action, tail: ConsoleTail, hebrew: bool, settle=time.sleep, max_skips=MAX_SKIPS, answer=5.0,
+ turn_wait=3.0, viewport=VIEWPORT):
+ self.action, self.tail, self.hebrew, self.settle = action, tail, hebrew, settle
+ self.max_skips, self.answer, self.turn_wait = max_skips, answer, turn_wait
+ self.point = END_TURN_HE if hebrew else END_TURN
+ self.bottom = viewport[1] - INFO_PANEL_BOTTOM
+ self.skip_at: tuple[int, int] | None = None # where Skip was last: cards of one kind keep it there
+
+ def __call__(self) -> int:
+ for skips in range(self.max_skips + 1):
+ since = self.tail.mark()
+ x, y = self.point
+ print(f"click end-turn at ({x}, {y})")
+ self.action(f"click:{x},{y}")
+ if self.tail.wait(NAV_CLICK, since, self.answer, "end-turn") is None:
+ raise ValueError(f"END TURN FAIL the click at ({x}, {y}) did not press end-turn within {self.answer:g} s")
+ if self.tail.wait(TURN_STATE, since, self.turn_wait) is not None:
+ print(f"END TURN the turn ended after {skips} Skip(s)")
+ return skips
+ if skips == self.max_skips:
+ break
+ self.settle(1) # the camera goes to the unit and its card lays out
+ if not self.skip(since):
+ print(f"END TURN the turn ended after {skips} Skip(s)")
+ return skips
+ raise ValueError(f"END TURN FAIL End turn still selected a unit needing orders after {self.max_skips} Skips")
+
+ def skip(self, since: int) -> bool:
+ """Clicks the shown unit card's Skip; False when the turn ended after all (a late TURN line), so nothing was pressed."""
+ if self.skip_at is not None and self.probe(*self.skip_at):
+ return True
+ x0 = INFO_PANEL_RIGHT - PROBE_INSET if self.hebrew else INFO_PANEL_LEFT + PROBE_INSET
+ rows, seen = [], []
+ for y in range(self.bottom - PROBE_INSET, self.bottom - INFO_PANEL_MAX_HEIGHT, -10):
+ if self.tail.wait(TURN_STATE, since, 0) is not None:
+ return False
+ target = self.press(x0, y)
+ seen.append(target)
+ if target == SKIP:
+ self.click_skip(x0, y)
+ return True
+ if target in ORDER_ROW and (not rows or rows[-1] - y > 20):
+ rows.append(y)
+ elif target in ABOVE_ORDERS and rows:
+ break
+ step = -20 if self.hebrew else 20
+ for y in rows:
+ for x in range(x0 + step, INFO_PANEL_LEFT + PROBE_INSET if self.hebrew else INFO_PANEL_RIGHT - PROBE_INSET, step):
+ if self.probe(x, y):
+ return True
+ raise ValueError(f"END TURN FAIL End turn selected a unit, but its card shows no {SKIP} (order rows at y "
+ f"{rows or 'none'}; pressed {', '.join(dict.fromkeys(seen))})")
+
+ def probe(self, x: int, y: int) -> bool:
+ """Clicks Skip when it is at x, y (True)."""
+ if self.press(x, y) != SKIP:
+ return False
+ self.click_skip(x, y)
+ return True
+
+ def press(self, x: int, y: int) -> str:
+ """The UI element a middle-button probe at x, y reaches."""
+ since = self.tail.mark()
+ self.action(f"probe:{x},{y}")
+ down = self.tail.wait(NAV_DOWN, since, self.answer)
+ if self.tail.wait(NAV_MAP, since, 0) is not None:
+ raise ValueError(f"END TURN FAIL a press at ({x}, {y}) reached the map, not the unit card")
+ if down is None:
+ raise ValueError(f"END TURN FAIL a press at ({x}, {y}) reached no UI element within {self.answer:g} s "
+ f"(the page needs ?{NAVLOG})")
+ print(f"probe ({x}, {y}): {down.group(1)}")
+ return down.group(1)
+
+ def click_skip(self, x: int, y: int) -> None:
+ since = self.tail.mark()
+ print(f"click {SKIP} at ({x}, {y})")
+ self.action(f"click:{x},{y}")
+ if self.tail.wait(NAV_CLICK, since, self.answer, SKIP) is None:
+ raise ValueError(f"END TURN FAIL the click at ({x}, {y}) did not press {SKIP} within {self.answer:g} s")
+ self.skip_at = (x, y)
+
+
def click_button(action, buttons: StartButtons, name: str) -> None:
"""A left click on a start-screen button where the game says it is; printed, so a stalled run shows where it clicked."""
x, y = buttons.point(name)
@@ -447,10 +600,12 @@ def click_button(action, buttons: StartButtons, name: str) -> None:
class PersistenceCheck:
"""Drives and checks the two reloads of issue #910. `action` is Page.command (injected, so the unit tests need no
- browser); a reload keeps the page's profile and origin, so its IndexedDB autosave."""
+ browser); a reload keeps the page's profile and origin, so its IndexedDB autosave. Each turn ends through EndTurn."""
- def __init__(self, action, buttons: StartButtons, settle=time.sleep, now=time.monotonic, save_timeout=15.0):
+ def __init__(self, action, buttons: StartButtons, tail: ConsoleTail, settle=time.sleep, now=time.monotonic,
+ save_timeout=15.0):
self.action, self.buttons, self.settle, self.now, self.save_timeout = action, buttons, settle, now, save_timeout
+ self.end_turn = EndTurn(action, tail, hebrew=False, settle=settle)
self.stage, self.saved, self._done = "first_boot", None, False
self.pending, self.acknowledged, self.deadline = None, None, None
@@ -501,7 +656,7 @@ class PersistenceCheck:
self.click(NEW_GAME)
self.settle(2)
self.stage = "first_turn"
- self.click(END_TURN)
+ self.end_turn()
elif self.stage == "first_turn" and kind == "TURN":
self._turn(state, 1, "first End turn after New game")
self.saved, self.stage = state, "first_commit"
@@ -516,7 +671,7 @@ class PersistenceCheck:
self.click(CONTINUE)
self.settle(2)
self.stage = "second_turn"
- self.click(END_TURN)
+ self.end_turn()
elif self.stage == "second_turn" and kind == "TURN":
self._turn(state, self.saved[1] + 1, "End turn after Continue")
self.saved, self.stage = state, "second_commit"
@@ -553,12 +708,12 @@ def query_value(query: str, key: str) -> str | None:
class StartScreenCheck:
"""Issue #908: the start screen of a fresh profile, as a player meets it (no automation flag skips it). New game
- (after Play the recording when `recording`) and End turn must reach the map's first turn. `action` is Page.command;
- `buttons` says where the start screen's buttons are."""
+ (after Play the recording when `recording`) and End turn (EndTurn: Skip each unit it selects) must reach the map's
+ first turn. `action` is Page.command; `buttons` says where the start screen's buttons are; `tail` is the console."""
- def __init__(self, action, recording: bool, hebrew: bool, buttons: StartButtons, settle=time.sleep):
+ def __init__(self, action, recording: bool, hebrew: bool, buttons: StartButtons, tail: ConsoleTail, settle=time.sleep):
self.action, self.recording, self.buttons, self.settle = action, recording, buttons, settle
- self.end_turn = END_TURN_HE if hebrew else END_TURN
+ self.end_turn = EndTurn(action, tail, hebrew, settle=settle)
self.stage, self.done = "boot", False
def feed(self, text: str) -> None:
@@ -585,8 +740,8 @@ class StartScreenCheck:
def new_game(self) -> None:
self.click(NEW_GAME)
self.settle(2)
- self.click(self.end_turn)
self.stage = "turn"
+ self.end_turn()
def click(self, target: str | tuple[int, int]) -> None:
if isinstance(target, str):
@@ -620,6 +775,8 @@ def watch(inbox, poll, join_reader, expect, fail, timeout, now=time.time, sleep=
if on_text is not None and on_text(t):
continue
print("console:", t)
+ if texts:
+ last = now() # again: a driver (EndTurn) may have waited in on_text while the page kept logging
if status == "fail":
print(f"FAIL: {texts[-1]}")
return 1
@@ -666,16 +823,16 @@ def page_query(a) -> str:
return f"{a.query}&{NAVLOG}" if a.query else NAVLOG
-def run_plan(a, command, buttons: StartButtons):
+def run_plan(a, command, buttons: StartButtons, tail: ConsoleTail):
"""What a run drives and fails on: (driver or None, the failure regex, watch's keyword arguments). `command` is
- Page.command; `buttons` is fed the console by the caller."""
+ Page.command; `buttons` and `tail` are fed the console by the caller."""
if a.persistence and a.startscreen:
raise ValueError("--persistence and --startscreen are separate runs")
if a.startscreen:
- driver = StartScreenCheck(command, a.startscreen == "recording", query_value(a.query, "lang") == "he", buttons)
+ driver = StartScreenCheck(command, a.startscreen == "recording", query_value(a.query, "lang") == "he", buttons, tail)
fail, what = f"(?:{a.fail})|{START_SCREEN_FAILS}", f"the end of the --startscreen {a.startscreen} run"
elif a.persistence:
- driver, fail, what = PersistenceCheck(command, buttons), a.fail, "the end of the --persistence run"
+ driver, fail, what = PersistenceCheck(command, buttons, tail), a.fail, "the end of the --persistence run"
else:
return None, re.compile(a.fail), {}
return driver, re.compile(fail), {"complete": lambda: driver.done, "complete_what": what, "grace": DRIVER_GRACE}
@@ -711,7 +868,7 @@ def main() -> int:
sys.exit(str(e))
res = expected_res(w, h, a.dpr)
shots = ShotCollector(a.shots, size=(round(w * a.dpr), round(h * a.dpr)))
- buttons = StartButtons((w, h))
+ buttons, tail = StartButtons((w, h)), ConsoleTail()
def on_text(text: str) -> bool:
err = res_error(text, res)
@@ -734,6 +891,7 @@ def main() -> int:
console = CONSOLE.search(line)
if console:
buttons.feed(console.group(1)) # here, not in watch: a driver waiting in settle() sees it
+ tail.feed(console.group(1)) # and one waiting for the game's answer to its click
inbox.put(line)
for line in rejoin.flush():
inbox.put(line)
@@ -743,7 +901,7 @@ def main() -> int:
page = Page(profile, url, w, h, a.dpr, a.mobile)
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)
+ driver, fail, plan = run_plan(a, page.command, buttons, tail)
def handle_text(text: str) -> bool:
consumed = on_text(text)