"""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()