test(ssap): add Red-phase contract tests and stubs for SsapClient

- Add FakeWebSocketTransport test double in tests/conftest.py
- Add typed SsapClient, PERMISSIONS, build_register_payload, and websockets_connect stubs
- Add 6 xfail contract tests covering permissions, demuxing, 1008 standby, PROMPT, 401/returnValue=false, and reader_loop cleanup
This commit is contained in:
kiskaadee committed 2026-11-15 16:42:34 -05:00
1 parent 72745b85d4
commit 7250944cc3
4 files changed
+349

No files matched your search

+74
View File
@@ -0,0 +1,74 @@
"""SSAP WebSocket client and msg['id'] frame multiplexer."""
from collections.abc import Awaitable, Callable
from typing import Any
from lg_smtv_mcp.errors import ErrorCode
from lg_smtv_mcp.tv_core.protocols import WebSocketConnectFn, WebSocketTransport
PERMISSIONS: tuple[str, ...] = (
"LAUNCH",
"CONTROL_AUDIO",
"CONTROL_DISPLAY",
"CONTROL_POWER",
"CONTROL_INPUT_TEXT",
"CONTROL_INPUT_MEDIA_PLAYBACK",
"CONTROL_INPUT_JOYSTICK",
"CONTROL_INPUT_TV",
"CONTROL_TV_MEDIA",
"CONTROL_MOUSE_AND_KEYBOARD",
"READ_INSTALLED_APPS",
"READ_RUNNING_APPS",
"READ_INPUT_DEVICE_LIST",
"READ_TV_CHANNEL_LIST",
"READ_POWER_STATE",
"WRITE_NOTIFICATION_TOAST",
)
def build_register_payload(
client_key: str | None,
*,
force_pairing: bool = False,
msg_id: str = "register_0",
) -> dict[str, Any]:
"""Build the SSAP register handshake payload."""
raise NotImplementedError
async def websockets_connect(url: str) -> WebSocketTransport:
"""Connect to an LG webOS SSAP or pointer WebSocket endpoint."""
raise NotImplementedError
class SsapClient:
"""Persistent SSAP WebSocket client with msg['id'] request/subscribe demultiplexing."""
def __init__(
self,
url: str,
connect_fn: WebSocketConnectFn = websockets_connect,
*,
on_disconnect: Callable[[ErrorCode], None] | None = None,
) -> None:
raise NotImplementedError
async def connect_and_register(self, client_key: str | None) -> str:
"""Connect, perform SSAP register handshake, and start the reader loop."""
raise NotImplementedError
async def request(self, uri: str, payload: dict[str, Any] | None = None) -> dict[str, Any]:
"""Send a one-shot SSAP request and await its matched response payload."""
raise NotImplementedError
async def subscribe(
self,
uri: str,
callback: Callable[[dict[str, Any]], Awaitable[None] | None],
) -> None:
"""Subscribe to an SSAP endpoint and route push updates to callback."""
raise NotImplementedError
async def close(self) -> None:
"""Close the SSAP transport and cancel the background reader loop."""
raise NotImplementedError
View File
Whitespace-only changes.
+61
View File
@@ -0,0 +1,61 @@
"""Shared offline test fakes and fixtures for lg-smtv-mcp contract tests."""
import asyncio
import json
from collections.abc import Callable
from typing import Any
from lg_smtv_mcp.tv_core.protocols import WebSocketClosedError
class FakeWebSocketTransport:
"""In-memory WebSocketTransport double for offline SSAP and pointer tests."""
def __init__(
self,
*,
on_send: Callable[[str, FakeWebSocketTransport], None] | None = None,
) -> None:
self.sent: list[str] = []
self.closed = False
self._on_send = on_send
self._incoming: asyncio.Queue[str | Exception] = asyncio.Queue()
def push_text(self, data: str) -> None:
"""Enqueue a raw text frame to be returned by recv()."""
self._incoming.put_nowait(data)
def push_json(self, payload: dict[str, Any]) -> None:
"""Enqueue a JSON-serialized frame to be returned by recv()."""
self._incoming.put_nowait(json.dumps(payload))
def push_error(self, exc: Exception) -> None:
"""Enqueue an exception to be raised by the next recv()."""
self._incoming.put_nowait(exc)
def push_close(self, code: int = 1000, reason: str = "") -> None:
"""Enqueue a WebSocketClosedError to simulate remote socket close."""
self._incoming.put_nowait(WebSocketClosedError(code, reason))
async def send(self, data: str) -> None:
"""Record an outgoing frame or raise WebSocketClosedError if closed."""
if self.closed:
raise WebSocketClosedError(1006, "transport closed")
self.sent.append(data)
if self._on_send is not None:
self._on_send(data, self)
async def recv(self) -> str:
"""Return the next queued frame or raise a queued exception."""
if self.closed and self._incoming.empty():
raise WebSocketClosedError(1006, "transport closed")
item = await self._incoming.get()
if isinstance(item, Exception):
raise item
return item
async def close(self) -> None:
"""Mark the transport closed and wake any blocked recv()."""
if not self.closed:
self.closed = True
self._incoming.put_nowait(WebSocketClosedError(1000, "closed"))
+214
View File
@@ -0,0 +1,214 @@
import asyncio
import json
from typing import Any
import pytest
from lg_smtv_mcp.errors import ErrorCode, TvError
from lg_smtv_mcp.tv_core.protocols import WebSocketClosedError
from lg_smtv_mcp.tv_core.ssap import PERMISSIONS, SsapClient
from tests.conftest import FakeWebSocketTransport
@pytest.mark.xfail(strict=True, reason="Red phase: ssap")
async def test_ssap_register_sends_all_permissions_even_with_saved_client_key() -> None:
def on_send(raw: str, ws: FakeWebSocketTransport) -> None:
msg = json.loads(raw)
if msg["type"] == "register":
ws.push_json(
{
"type": "registered",
"id": msg["id"],
"payload": {"client-key": "saved-key-123"},
}
)
transport = FakeWebSocketTransport(on_send=on_send)
async def connect(_url: str) -> FakeWebSocketTransport:
return transport
client = SsapClient("wss://192.0.2.10:3001", connect_fn=connect)
key = await client.connect_and_register("saved-key-123")
await client.close()
assert key == "saved-key-123"
reg_msg = json.loads(transport.sent[0])
assert reg_msg["type"] == "register"
assert reg_msg["payload"]["client-key"] == "saved-key-123"
assert len(PERMISSIONS) == 16
assert reg_msg["payload"]["manifest"]["permissions"] == list(PERMISSIONS)
@pytest.mark.xfail(strict=True, reason="Red phase: ssap")
async def test_ssap_request_demuxes_interleaved_subscribe_push_frame() -> None:
sub_id_holder: list[str] = []
def on_send(raw: str, ws: FakeWebSocketTransport) -> None:
msg = json.loads(raw)
if msg["type"] == "register":
ws.push_json({"type": "registered", "id": msg["id"], "payload": {"client-key": "k"}})
elif msg["type"] == "subscribe":
sub_id_holder.append(msg["id"])
ws.push_json(
{
"type": "response",
"id": msg["id"],
"payload": {"subscribed": True, "returnValue": True, "volume": 10},
}
)
elif msg["type"] == "request":
# Push a subscribe update frame BEFORE the request response frame.
ws.push_json(
{
"type": "response",
"id": sub_id_holder[0],
"payload": {"returnValue": True, "volume": 10, "mute": True},
}
)
ws.push_json(
{
"type": "response",
"id": msg["id"],
"payload": {"returnValue": True, "muteApplied": True},
}
)
transport = FakeWebSocketTransport(on_send=on_send)
async def connect(_url: str) -> FakeWebSocketTransport:
return transport
client = SsapClient("wss://192.0.2.10:3001", connect_fn=connect)
await client.connect_and_register("k")
updates: list[dict[str, Any]] = []
await client.subscribe("ssap://audio/getStatus", updates.append)
resp = await client.request("ssap://audio/setMute", {"mute": True})
await asyncio.sleep(0)
await client.close()
assert resp == {"returnValue": True, "muteApplied": True}
assert updates[-1]["mute"] is True
@pytest.mark.xfail(strict=True, reason="Red phase: ssap")
async def test_ssap_connect_maps_1008_and_timeout_to_tv_offline_standby() -> None:
transport_1008 = FakeWebSocketTransport()
transport_1008.push_close(1008, "Try Again Later (EWS)")
async def connect_1008(_url: str) -> FakeWebSocketTransport:
return transport_1008
client_1008 = SsapClient("wss://192.0.2.10:3001", connect_fn=connect_1008)
with pytest.raises(TvError) as exc_1008:
await client_1008.connect_and_register("k")
assert exc_1008.value.code is ErrorCode.TV_OFFLINE_STANDBY
async def connect_timeout(_url: str) -> FakeWebSocketTransport:
raise TimeoutError("handshake timed out")
client_timeout = SsapClient("wss://192.0.2.10:3001", connect_fn=connect_timeout)
with pytest.raises(TvError) as exc_timeout:
await client_timeout.connect_and_register("k")
assert exc_timeout.value.code is ErrorCode.TV_OFFLINE_STANDBY
@pytest.mark.xfail(strict=True, reason="Red phase: ssap")
async def test_ssap_register_maps_prompt_to_pairing_required() -> None:
def on_send(raw: str, ws: FakeWebSocketTransport) -> None:
msg = json.loads(raw)
if msg["type"] == "register":
ws.push_json(
{
"type": "response",
"id": msg["id"],
"payload": {"pairingType": "PROMPT", "returnValue": True},
}
)
transport = FakeWebSocketTransport(on_send=on_send)
async def connect(_url: str) -> FakeWebSocketTransport:
return transport
client = SsapClient("wss://192.0.2.10:3001", connect_fn=connect)
with pytest.raises(TvError) as exc_info:
await client.connect_and_register(None)
assert exc_info.value.code is ErrorCode.PAIRING_REQUIRED
assert transport.closed is True
@pytest.mark.xfail(strict=True, reason="Red phase: ssap")
async def test_ssap_request_maps_return_value_false_and_401_to_domain_errors() -> None:
def on_send(raw: str, ws: FakeWebSocketTransport) -> None:
msg = json.loads(raw)
if msg["type"] == "register":
ws.push_json({"type": "registered", "id": msg["id"], "payload": {"client-key": "k"}})
elif msg["type"] == "request":
if msg["uri"] == "ssap://fail/cmd":
ws.push_json(
{
"type": "response",
"id": msg["id"],
"payload": {"returnValue": False, "errorText": "bad target"},
}
)
elif msg["uri"] == "ssap://settings/getSystemSettings":
ws.push_json(
{
"type": "error",
"id": msg["id"],
"error": "401 insufficient permissions",
"payload": {"returnValue": False},
}
)
transport = FakeWebSocketTransport(on_send=on_send)
async def connect(_url: str) -> FakeWebSocketTransport:
return transport
client = SsapClient("wss://192.0.2.10:3001", connect_fn=connect)
await client.connect_and_register("k")
with pytest.raises(TvError) as exc_cmd:
await client.request("ssap://fail/cmd")
assert exc_cmd.value.code is ErrorCode.COMMAND_FAILED
with pytest.raises(TvError) as exc_perm:
await client.request("ssap://settings/getSystemSettings")
assert exc_perm.value.code is ErrorCode.PAIRING_REQUIRED
await client.close()
@pytest.mark.xfail(strict=True, reason="Red phase: ssap")
async def test_ssap_reader_loop_finally_fails_pending_futures_with_standby_error() -> None:
def on_send(raw: str, ws: FakeWebSocketTransport) -> None:
msg = json.loads(raw)
if msg["type"] == "register":
ws.push_json({"type": "registered", "id": msg["id"], "payload": {"client-key": "k"}})
elif msg["type"] == "request":
# Drop the socket instead of answering the request.
ws.push_error(WebSocketClosedError(1008, "Try Again Later (EWS)"))
transport = FakeWebSocketTransport(on_send=on_send)
async def connect(_url: str) -> FakeWebSocketTransport:
return transport
disconnected: list[ErrorCode] = []
client = SsapClient(
"wss://192.0.2.10:3001",
connect_fn=connect,
on_disconnect=disconnected.append,
)
await client.connect_and_register("k")
with pytest.raises(TvError) as exc_info:
await client.request("ssap://audio/getStatus")
assert exc_info.value.code is ErrorCode.TV_OFFLINE_STANDBY
await asyncio.sleep(0)
assert disconnected == [ErrorCode.TV_OFFLINE_STANDBY]
await client.close()