"""Priming must fail loudly, and must load the app fresh. Background (2026-11): after a Wodify redeploy the app's service worker kept serving the old runtime to new screen code. Every data action threw client-side before a request was sent, so prime observed nothing, wrote a cache with an empty action table, and every later query reported NOT PRIMED. The session was valid the whole time. Nothing here needs a browser. """ from __future__ import annotations import json import pytest from wodify import actions, cdp, client, prime def _console_error(*texts: str) -> dict: return {"method": "Runtime.consoleAPICalled", "params": {"type": "error", "args": [{"type": "string", "value": t} for t in texts]}} # The shape the broken app actually emitted. STAMPED = "[2026-11-11T05:02:11.964Z]: s is not a function " STACK = ("TypeError: s is not a function\n" " at Controller.callServerDataSource (https://h/scripts/OutSystems.js:17:20936)\n" " at Controller.innerCallDataAction (https://h/scripts/OutSystems.js:17:20451)") def test_page_error_is_summarised_with_its_first_frame(): errors: list[str] = [] prime._observe_errors(_console_error(STAMPED, STACK), errors) assert errors == ["s is not a function at Controller.callServerDataSource"] def test_identical_errors_with_different_stamps_collapse(): errors: list[str] = [] for stamp in ("05:02:11.964", "05:02:15.717", "05:02:16.154"): prime._observe_errors( _console_error(f"[2026-11-11T{stamp}Z]: s is not a function ", STACK), errors) assert len(errors) == 1 def test_uncaught_exception_is_collected(): errors: list[str] = [] prime._observe_errors({"method": "Runtime.exceptionThrown", "params": { "exceptionDetails": {"text": "Uncaught (in promise)", "exception": {"description": STACK}}}}, errors) assert errors == ["TypeError: s is not a function at Controller.callServerDataSource"] def test_page_errors_are_capped(): errors: list[str] = [] for i in range(prime.MAX_PAGE_ERRORS + 10): prime._observe_errors(_console_error(f"boom {i}"), errors) assert len(errors) == prime.MAX_PAGE_ERRORS def test_console_logs_and_requests_are_not_errors(): errors: list[str] = [] prime._observe_errors({"method": "Runtime.consoleAPICalled", "params": { "type": "log", "args": [{"value": "Firestore Initialized"}]}}, errors) prime._observe_errors({"method": "Network.requestWillBeSent", "params": {}}, errors) assert errors == [] # -------------------------------------------------------------------------- # _run / prime, against a scripted session # -------------------------------------------------------------------------- def _request(path: str, *, csrf: str = "T" * 28) -> dict: body = {"versionInfo": {"moduleVersion": "MV", "apiVersion": "AV"}, "viewName": "MainScreens.Home", "screenData": {"variables": {}}} return {"method": "Network.requestWillBeSent", "params": {"request": { "url": f"https://example.invalid/WodifyClient/screenservices/{path}", "headers": {"X-CSRFToken": csrf}, "postData": json.dumps(body)}}} class ScriptedSession: """Stands in for CDPSession: replays ``events`` on the first drain.""" def __init__(self, events): self.events = list(events) self.closed = False async def session_cookies(self): return "nr1W_Theme_UI=x" async def open_page(self, *a, **kw): return None async def navigate(self, url): return None async def drain(self, seconds, handler): events, self.events = self.events, [] for ev in events: handler(ev) async def evaluate(self, expression, *, await_promise=False): return "MV" if "moduleversioninfo" in expression else '{"ok": true}' async def close(self): self.closed = True @pytest.fixture() def scripted(monkeypatch): def install(events): session = ScriptedSession(events) async def connect(*a, **kw): return session monkeypatch.setattr(cdp.CDPSession, "connect", connect) return session return install def _never_save(monkeypatch): def boom(*a, **kw): raise AssertionError("an empty capture must never be written to the cache") monkeypatch.setattr(client, "save_cache", boom) def test_empty_capture_from_a_crashing_page_is_refused_not_saved(scripted, monkeypatch): """The regression. CSRF is observed (the app's bootstrap calls still fire), no allowlisted action is, and the page is throwing.""" session = scripted([ _request("WodifyClient/ActionShowFeaturesAvailable"), _console_error(STAMPED, STACK), ]) _never_save(monkeypatch) with pytest.raises(RuntimeError) as err: prime.prime() message = str(err.value) assert "left untouched" in message assert "callServerDataSource" in message # names the real cause assert "moved its endpoints" not in message # and does not guess another assert session.closed def test_empty_capture_without_page_errors_points_at_moved_endpoints(scripted, monkeypatch): scripted([_request("WodifyClient/ActionShowFeaturesAvailable")]) _never_save(monkeypatch) with pytest.raises(RuntimeError, match="moved its endpoints"): prime.prime() def test_successful_capture_is_saved_and_reports_page_errors(scripted, monkeypatch, tmp_path): scripted([_request(actions.ACTIONS["schedule"].path), _console_error("minor")]) saved = {} def save(payload, path=None): saved.update(payload) return tmp_path / "session.json" monkeypatch.setattr(client, "save_cache", save) summary = prime.prime() assert summary["actions_captured"] == ["schedule"] assert summary["page_errors"] == ["minor"] # Diagnostics are for the operator, not for the credential cache. assert "page_errors" not in saved and "walk_log" not in saved assert actions.ACTIONS["schedule"].path in saved["actions"]