"""CDP session multiplexing. `websockets` raises if two coroutines call recv() concurrently, and priming genuinely needs to run a long in-page script *while* watching the requests that script triggers. An earlier version ran both against the socket directly; it failed loudly on one machine and silently on another, losing the walk result while looking like it worked. """ from __future__ import annotations import asyncio import json import pytest from wodify import cdp class FakeWS: """Minimal websocket: replies to commands, can inject events.""" def __init__(self): self.sent: list[dict] = [] self._out: asyncio.Queue = asyncio.Queue() self.closed = False self.recv_callers = 0 self.max_concurrent_recv = 0 async def send(self, raw): msg = json.loads(raw) self.sent.append(msg) await self._out.put(json.dumps( {"id": msg["id"], "result": {"echo": msg["method"]}})) async def inject_event(self, method, params=None): await self._out.put(json.dumps({"method": method, "params": params or {}})) async def close(self): self.closed = True def __aiter__(self): return self async def __anext__(self): self.recv_callers += 1 self.max_concurrent_recv = max(self.max_concurrent_recv, self.recv_callers) try: return await self._out.get() finally: self.recv_callers -= 1 @pytest.fixture() async def session(): # Built inside a running loop: start() spawns the reader task. ws = FakeWS() s = cdp.CDPSession(ws) s.start() return s, ws @pytest.mark.asyncio async def test_call_returns_result(session): s, ws = session result = await s.call("Page.enable") assert result == {"echo": "Page.enable"} await s.close() @pytest.mark.asyncio async def test_events_go_to_drain_not_to_call(session): s, ws = session seen = [] drain = asyncio.create_task(s.drain(1.5, seen.append)) await ws.inject_event("Network.requestWillBeSent", {"n": 1}) result = await s.call("Runtime.evaluate") await drain assert result == {"echo": "Runtime.evaluate"} assert [e["params"]["n"] for e in seen] == [1] await s.close() @pytest.mark.asyncio async def test_call_and_drain_run_concurrently_without_conflict(session): """The regression: exactly one coroutine may read the socket.""" s, ws = session seen = [] drain = asyncio.create_task(s.drain(1.5, seen.append)) await asyncio.gather(*(s.call(f"M{i}") for i in range(5))) await ws.inject_event("Network.requestWillBeSent", {"n": 2}) await drain assert ws.max_concurrent_recv <= 1, "socket must have a single reader" assert len(seen) == 1 await s.close() @pytest.mark.asyncio async def test_call_times_out_rather_than_hanging(): class Silent(FakeWS): async def send(self, raw): self.sent.append(json.loads(raw)) # never replies ws = Silent() s = cdp.CDPSession(ws) s.start() with pytest.raises(RuntimeError, match="timed out"): await s.call("Never.Replies", timeout=0.2) await s.close() @pytest.mark.asyncio async def test_error_reply_raises(session): class Failing(FakeWS): async def send(self, raw): msg = json.loads(raw) await self._out.put(json.dumps( {"id": msg["id"], "error": {"message": "nope"}})) ws = Failing() s = cdp.CDPSession(ws) s.start() with pytest.raises(RuntimeError, match="nope"): await s.call("Bad.Method") await s.close() @pytest.mark.asyncio async def test_drain_returns_after_its_window(session): s, _ = session started = asyncio.get_event_loop().time() await s.drain(0.3, lambda _: None) assert asyncio.get_event_loop().time() - started >= 0.3 await s.close() @pytest.mark.asyncio async def test_call_on_target_without_attachment_raises(session): s, _ = session with pytest.raises(RuntimeError, match="no page target"): await s.call("Page.navigate", on_target=True) await s.close() # -------------------------------------------------------------------------- # page lifecycle # -------------------------------------------------------------------------- class PageWS(FakeWS): """Replies with the ids open_page needs.""" async def send(self, raw): msg = json.loads(raw) self.sent.append(msg) result = {"Target.createTarget": {"targetId": "TAB1"}, "Target.attachToTarget": {"sessionId": "SESS1"}}.get(msg["method"], {}) await self._out.put(json.dumps({"id": msg["id"], "result": result})) def _sent(ws, method): return [m for m in ws.sent if m["method"] == method] @pytest.mark.asyncio async def test_open_page_bypasses_the_service_worker_by_default(): """After a Wodify redeploy the app's service worker can keep serving the old runtime to new screen code; that app throws before sending any data action. Priming must bypass the worker -- for this tab only.""" ws = PageWS() s = cdp.CDPSession(ws) s.start() await s.open_page() worker = _sent(ws, "Network.setBypassServiceWorker") assert [m["params"] for m in worker] == [{"bypass": True}] # Scoped to the attached tab, never browser-wide. assert worker[0]["sessionId"] == "SESS1" # Bypass, not destroy: nothing is unregistered or cleared in the profile. assert not [m for m in ws.sent if any(w in m["method"].lower() for w in ("clear", "unregister", "delete"))] await s.close() @pytest.mark.asyncio async def test_open_page_can_opt_out_of_fresh_load(): ws = PageWS() s = cdp.CDPSession(ws) s.start() await s.open_page(fresh=False) assert not _sent(ws, "Network.setBypassServiceWorker") await s.close() @pytest.mark.asyncio async def test_close_closes_the_tab_it_opened(): """Every prime used to leave its tab open in the profile forever.""" ws = PageWS() s = cdp.CDPSession(ws) s.start() await s.open_page() await s.close() assert [m["params"] for m in _sent(ws, "Target.closeTarget")] == [{"targetId": "TAB1"}] assert ws.closed @pytest.mark.asyncio async def test_close_without_a_page_closes_nothing(session): s, ws = session await s.close() assert not _sent(ws, "Target.closeTarget") assert ws.closed @pytest.mark.asyncio async def test_close_survives_a_failing_tab_close(): class Failing(PageWS): async def send(self, raw): msg = json.loads(raw) if msg["method"] == "Target.closeTarget": self.sent.append(msg) await self._out.put(json.dumps( {"id": msg["id"], "error": {"message": "no such target"}})) return await super().send(raw) ws = Failing() s = cdp.CDPSession(ws) s.start() await s.open_page() await s.close() # must not raise assert ws.closed