"""The server side of the remote session channel: what it sends on attach, and how it lets go of a socket.""" from __future__ import annotations import asyncio import logging from typing import Any import pytest from aiohttp import WSMessage from aiohttp.http_websocket import WS_CLOSED_MESSAGE from unshackle.core.api.input_bridge import InputBridge from unshackle.core.api.session_log import SessionLogBuffer from unshackle.core.api.session_store import SessionEntry pytestmark = pytest.mark.unit class FakeSocket: """A server WebSocket that records what it sends, and ends its read loop when it closes.""" def __init__(self) -> None: self.sent: list[dict[str, Any]] = [] self.closed = asyncio.Event() async def send_json(self, message: dict[str, Any]) -> None: self.sent.append(message) async def close(self, code: int = 1000, message: bytes = b"") -> bool: self.closed.set() return True async def receive(self) -> WSMessage: await self.closed.wait() return WS_CLOSED_MESSAGE def entry_with_logs(count: int) -> SessionEntry: entry = SessionEntry("s", "EXAMPLE", None, log_buffer=SessionLogBuffer(), input_bridge=InputBridge()) for n in range(count): entry.log_buffer.append(logging.INFO, f"EXAMPLE line {n + 1}") return entry async def test_a_socket_that_cannot_send_is_closed_and_detached() -> None: entry = entry_with_logs(1) broken = FakeSocket() async def fail(message: dict[str, Any]) -> None: raise RuntimeError("EXAMPLE socket gone") broken.send_json = fail # type: ignore[method-assign] await asyncio.wait_for(entry.channel.serve(broken, entry, 0, False), 5) # type: ignore[arg-type] assert broken.closed.is_set() assert not entry.channel.attached