From 699c46fafbda6c2ca3fce3f876a5978154b79945 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Mon, 16 Nov 2026 17:56:41 -0500 Subject: [PATCH 1/4] feat(tv_core): add AsyncSshCaptureTransport and CaptureClient - capture: implement AsyncSshCaptureTransport with asyncssh connect args, lazy SFTP connect/reconnect, temp sweep on new session, read_and_remove with shielded cleanup grace, and handle clearing on transport errors - capture: implement CaptureClient executeOneShot flow with shared 6s timeout, sequence-numbered remote paths, SHA256/change tracking, close reset, and error mapping to SCREENSHOT_UNAVAILABLE while preserving TV_OFFLINE_STANDBY/PAIRING_REQUIRED - tests: add offline contract tests for transport connect/sweep/cleanup and capture request/read/error/timeout/change-detection behavior --- src/lg_smtv_mcp/tv_core/capture.py | 198 ++++++++++++++ tests/test_capture.py | 404 +++++++++++++++++++++++++++++ 2 files changed, 602 insertions(+) create mode 100644 src/lg_smtv_mcp/tv_core/capture.py create mode 100644 tests/test_capture.py diff --git a/src/lg_smtv_mcp/tv_core/capture.py b/src/lg_smtv_mcp/tv_core/capture.py new file mode 100644 index 0000000..2b92d01 --- /dev/null +++ b/src/lg_smtv_mcp/tv_core/capture.py @@ -0,0 +1,198 @@ +"""AsyncSSH-backed capture transport and CaptureClient for LG webOS screenshots.""" + +import asyncio +import hashlib +import os +from collections.abc import Awaitable, Callable +from contextlib import suppress +from typing import Any + +import asyncssh + +from lg_smtv_mcp.config import TvConfig +from lg_smtv_mcp.errors import ErrorCode, TvError +from lg_smtv_mcp.tv_core.protocols import CaptureResult, CaptureTransport + + +class AsyncSshCaptureTransport: + """SFTP transport for reading and removing Developer Mode screenshot captures.""" + + def __init__( + self, + config: TvConfig, + connect_fn: Callable[..., Awaitable[Any]] | None = None, + ) -> None: + self._config = config + self._connect_fn = connect_fn or asyncssh.connect + self._conn: Any = None + self._sftp: Any = None + + async def _close_handles(self) -> None: + sftp = self._sftp + conn = self._conn + self._sftp = None + self._conn = None + if sftp is not None: + with suppress(Exception): + exit_fn = getattr(sftp, "exit", None) + if callable(exit_fn): + res = exit_fn() + if asyncio.iscoroutine(res): + await res + else: + close_fn = getattr(sftp, "close", None) + if callable(close_fn): + res = close_fn() + if asyncio.iscoroutine(res): + await res + if conn is not None: + with suppress(Exception): + conn.close() + wait_closed = getattr(conn, "wait_closed", None) + if callable(wait_closed): + res = wait_closed() + if asyncio.iscoroutine(res): + await res + + async def _ensure_sftp(self) -> Any: + if self._sftp is not None: + return self._sftp + + config = self._config + self._conn = await self._connect_fn( + host=config.tv_ip, + port=9922, + username="prisoner", + config=[], + known_hosts=( + str(config.ssh_known_hosts_path) + if config.ssh_known_hosts_path is not None + else None + ), + server_host_key_algs=["ssh-rsa"], + signature_algs=["ssh-rsa"], + client_keys=[str(config.ssh_key_path)] if config.ssh_key_path is not None else None, + passphrase=config.webos_ssh_passphrase, + ) + self._sftp = await self._conn.start_sftp_client() + with suppress(Exception): + await self.sweep_temp_files("/tmp/lg_smtv_cap_") + return self._sftp + + async def read_and_remove( + self, + remote_path: str, + timeout: float = 6.0, + cleanup_grace: float = 1.5, + ) -> bytes: + _ = timeout # timeout budget is enforced by CaptureClient around the full operation + try: + sftp = await self._ensure_sftp() + try: + data = await sftp.read(remote_path) + if not isinstance(data, (bytes, bytearray)): + data = bytes(data) + else: + data = bytes(data) + finally: + with suppress(Exception): + await asyncio.wait_for( + asyncio.shield(sftp.remove(remote_path)), + timeout=cleanup_grace, + ) + return data + except asyncssh.Error, OSError: + await self._close_handles() + raise + + async def sweep_temp_files(self, prefix: str = "/tmp/lg_smtv_cap_") -> None: + sftp = self._sftp + if sftp is None: + return + directory = os.path.dirname(prefix) or "/tmp" + name_prefix = os.path.basename(prefix) + try: + entries = await sftp.listdir(directory) + except Exception: + return + for entry in entries: + if not isinstance(entry, str) or not entry.startswith(name_prefix): + continue + remote_path = f"{directory.rstrip('/')}/{entry}" + with suppress(Exception): + await sftp.remove(remote_path) + + async def close(self) -> None: + await self._close_handles() + + +class CaptureClient: + """FrameCapturer that triggers executeOneShot and fetches JPEG via SFTP.""" + + def __init__(self, transport: CaptureTransport) -> None: + self._transport = transport + self._seq = 0 + self._last_sha256: str | None = None + + async def capture_frame( + self, + ssap_request_fn: Callable[[str, dict[str, Any]], Awaitable[dict[str, Any]]], + ) -> CaptureResult: + self._seq += 1 + remote_path = f"/tmp/lg_smtv_cap_{self._seq}.jpg" + try: + async with asyncio.timeout(6.0): + try: + response = await ssap_request_fn( + "ssap://com.webos.service.capture/executeOneShot", + {"path": remote_path, "method": "DISPLAY", "format": "JPG"}, + ) + except TvError as exc: + if exc.code in (ErrorCode.TV_OFFLINE_STANDBY, ErrorCode.PAIRING_REQUIRED): + raise + if exc.code is ErrorCode.COMMAND_FAILED: + raise TvError( + ErrorCode.SCREENSHOT_UNAVAILABLE, + f"executeOneShot failed: {exc.message}", + ) from exc + raise TvError( + ErrorCode.SCREENSHOT_UNAVAILABLE, + f"executeOneShot failed: {exc.message}", + ) from exc + + if response.get("returnValue") is False: + raise TvError( + ErrorCode.SCREENSHOT_UNAVAILABLE, + "executeOneShot returned returnValue false", + ) + + try: + image_bytes = await self._transport.read_and_remove( + remote_path, timeout=6.0, cleanup_grace=1.5 + ) + except TvError: + raise + except (asyncssh.Error, OSError) as exc: + raise TvError( + ErrorCode.SCREENSHOT_UNAVAILABLE, + f"Failed to retrieve screenshot over SSH/SFTP: {exc}", + ) from exc + except TimeoutError as exc: + raise TvError( + ErrorCode.SCREENSHOT_UNAVAILABLE, + "Screenshot capture timed out after 6.0s", + ) from exc + + frame_sha256 = hashlib.sha256(image_bytes).hexdigest() + changed_since_last = self._last_sha256 != frame_sha256 + self._last_sha256 = frame_sha256 + return CaptureResult( + image_bytes=image_bytes, + frame_sha256=frame_sha256, + changed_since_last=changed_since_last, + size_bytes=len(image_bytes), + ) + + async def close(self) -> None: + self._last_sha256 = None + await self._transport.close() diff --git a/tests/test_capture.py b/tests/test_capture.py new file mode 100644 index 0000000..da69b41 --- /dev/null +++ b/tests/test_capture.py @@ -0,0 +1,404 @@ +"""Offline contract tests for AsyncSshCaptureTransport and CaptureClient.""" + +import asyncio +import hashlib +from pathlib import Path +from typing import Any + +import pytest + +from lg_smtv_mcp.config import TvConfig +from lg_smtv_mcp.errors import ErrorCode, TvError +from lg_smtv_mcp.tv_core.capture import AsyncSshCaptureTransport, CaptureClient + + +class FakeSftpClient: + def __init__( + self, + *, + files: dict[str, bytes] | None = None, + list_names: list[str] | None = None, + read_error: Exception | None = None, + remove_delay: float = 0.0, + remove_error: Exception | None = None, + ) -> None: + self.files = dict(files or {}) + self.list_names = list(list_names or []) + self.read_error = read_error + self.remove_delay = remove_delay + self.remove_error = remove_error + self.read_calls: list[str] = [] + self.remove_calls: list[str] = [] + self.closed = False + + async def read(self, path: str) -> bytes: + self.read_calls.append(path) + if self.read_error is not None: + raise self.read_error + if path not in self.files: + raise FileNotFoundError(path) + return self.files[path] + + async def remove(self, path: str) -> None: + if self.remove_delay > 0: + await asyncio.sleep(self.remove_delay) + self.remove_calls.append(path) + if self.remove_error is not None: + raise self.remove_error + self.files.pop(path, None) + if path in self.list_names: + self.list_names.remove(path) + + async def listdir(self, path: str) -> list[str]: + _ = path + return list(self.list_names) + + async def exit(self) -> None: + self.closed = True + + +class FakeSshConnection: + def __init__(self, sftp: FakeSftpClient) -> None: + self.sftp = sftp + self.sftp_calls = 0 + self.closed = False + + async def start_sftp_client(self) -> FakeSftpClient: + self.sftp_calls += 1 + return self.sftp + + def close(self) -> None: + self.closed = True + + async def wait_closed(self) -> None: + return None + + +def _make_config(tmp_path: Path, *, with_ssh: bool = False) -> TvConfig: + ssh_key = tmp_path / "id_rsa" + known_hosts = tmp_path / "known_hosts" + if with_ssh: + ssh_key.write_text("dummy", encoding="utf-8") + known_hosts.write_text("dummy", encoding="utf-8") + kwargs: dict[str, Any] = {"tv_ip": "192.0.2.10"} + if with_ssh: + kwargs["ssh_key_path"] = ssh_key + kwargs["ssh_known_hosts_path"] = known_hosts + kwargs["webos_ssh_passphrase"] = "secret" + return TvConfig(**kwargs) + + +async def test_async_ssh_capture_transport_connect_uses_required_args(tmp_path: Path) -> None: + sftp = FakeSftpClient(files={"/tmp/lg_smtv_cap_1.jpg": b"jpeg"}, list_names=[]) + conn = FakeSshConnection(sftp) + calls: list[dict[str, Any]] = [] + + async def fake_connect(**kwargs: Any) -> FakeSshConnection: + calls.append(kwargs) + return conn + + cfg = _make_config(tmp_path, with_ssh=True) + transport = AsyncSshCaptureTransport(cfg, connect_fn=fake_connect) + data = await transport.read_and_remove("/tmp/lg_smtv_cap_1.jpg") + + assert data == b"jpeg" + assert len(calls) == 1 + assert calls[0]["host"] == "192.0.2.10" + assert calls[0]["port"] == 9922 + assert calls[0]["username"] == "prisoner" + assert calls[0]["config"] == [] + assert calls[0]["server_host_key_algs"] == ["ssh-rsa"] + assert calls[0]["signature_algs"] == ["ssh-rsa"] + assert calls[0]["client_keys"] == [str(cfg.ssh_key_path)] + assert calls[0]["known_hosts"] == str(cfg.ssh_known_hosts_path) + assert calls[0]["passphrase"] == "secret" + + +async def test_async_ssh_capture_transport_sweeps_on_initial_connect_and_reconnect( + tmp_path: Path, +) -> None: + sftp1 = FakeSftpClient( + files={"/tmp/lg_smtv_cap_1.jpg": b"one"}, + list_names=["lg_smtv_cap_old.jpg", "other.txt"], + ) + conn1 = FakeSshConnection(sftp1) + sftp2 = FakeSftpClient( + files={"/tmp/lg_smtv_cap_2.jpg": b"two"}, + list_names=["lg_smtv_cap_stale.jpg", "keep.txt"], + ) + conn2 = FakeSshConnection(sftp2) + conns = [conn1, conn2] + + async def fake_connect(**kwargs: Any) -> FakeSshConnection: + _ = kwargs + return conns.pop(0) + + transport = AsyncSshCaptureTransport(_make_config(tmp_path), connect_fn=fake_connect) + await transport.read_and_remove("/tmp/lg_smtv_cap_1.jpg") + assert "/tmp/lg_smtv_cap_old.jpg" in sftp1.remove_calls + assert "/tmp/other.txt" not in sftp1.remove_calls + + # Force transport error on next read to trigger reconnect and sweep on new SFTP. + sftp1.read_error = OSError("boom") + with pytest.raises(OSError): + await transport.read_and_remove("/tmp/lg_smtv_cap_1.jpg") + + data = await transport.read_and_remove("/tmp/lg_smtv_cap_2.jpg") + assert data == b"two" + assert "/tmp/lg_smtv_cap_stale.jpg" in sftp2.remove_calls + assert "/tmp/keep.txt" not in sftp2.remove_calls + + +async def test_async_ssh_capture_transport_shields_remove_on_read_error(tmp_path: Path) -> None: + sftp = FakeSftpClient( + files={"/tmp/lg_smtv_cap_1.jpg": b"jpeg"}, + read_error=OSError("read failed"), + remove_delay=0.05, + ) + conn = FakeSshConnection(sftp) + + async def fake_connect(**kwargs: Any) -> FakeSshConnection: + _ = kwargs + return conn + + transport = AsyncSshCaptureTransport(_make_config(tmp_path), connect_fn=fake_connect) + with pytest.raises(OSError, match="read failed"): + await transport.read_and_remove("/tmp/lg_smtv_cap_1.jpg", timeout=6.0, cleanup_grace=1.5) + + assert "/tmp/lg_smtv_cap_1.jpg" in sftp.remove_calls + + +async def test_capture_client_sends_execute_one_shot_and_returns_metadata(tmp_path: Path) -> None: + _ = tmp_path + image = b"frame-bytes" + expected_sha = hashlib.sha256(image).hexdigest() + + class FakeTransport: + def __init__(self) -> None: + self.read_calls: list[tuple[str, float, float]] = [] + self.closed = False + + async def read_and_remove( + self, remote_path: str, timeout: float = 6.0, cleanup_grace: float = 1.5 + ) -> bytes: + self.read_calls.append((remote_path, timeout, cleanup_grace)) + return image + + async def sweep_temp_files(self, prefix: str = "/tmp/lg_smtv_cap_") -> None: + _ = prefix + + async def close(self) -> None: + self.closed = True + + transport = FakeTransport() + client = CaptureClient(transport) + calls: list[tuple[str, dict[str, Any]]] = [] + + async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]: + calls.append((uri, payload)) + return {"returnValue": True} + + result = await client.capture_frame(ssap_request) + + assert calls == [ + ( + "ssap://com.webos.service.capture/executeOneShot", + {"path": "/tmp/lg_smtv_cap_1.jpg", "method": "DISPLAY", "format": "JPG"}, + ) + ] + assert transport.read_calls == [("/tmp/lg_smtv_cap_1.jpg", 6.0, 1.5)] + assert result.image_bytes == image + assert result.frame_sha256 == expected_sha + assert result.changed_since_last is True + assert result.size_bytes == len(image) + + +async def test_capture_client_changed_since_last_and_close_resets(tmp_path: Path) -> None: + _ = tmp_path + image = b"same" + + class FakeTransport: + async def read_and_remove( + self, remote_path: str, timeout: float = 6.0, cleanup_grace: float = 1.5 + ) -> bytes: + _ = (remote_path, timeout, cleanup_grace) + return image + + async def sweep_temp_files(self, prefix: str = "/tmp/lg_smtv_cap_") -> None: + _ = prefix + + async def close(self) -> None: + return None + + client = CaptureClient(FakeTransport()) + + async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]: + _ = (uri, payload) + return {"returnValue": True} + + first = await client.capture_frame(ssap_request) + second = await client.capture_frame(ssap_request) + await client.close() + third = await client.capture_frame(ssap_request) + + assert first.changed_since_last is True + assert second.changed_since_last is False + assert third.changed_since_last is True + + +async def test_capture_client_maps_execute_one_shot_failure_without_sftp_read( + tmp_path: Path, +) -> None: + _ = tmp_path + + class FakeTransport: + def __init__(self) -> None: + self.read_calls = 0 + + async def read_and_remove( + self, remote_path: str, timeout: float = 6.0, cleanup_grace: float = 1.5 + ) -> bytes: + _ = (remote_path, timeout, cleanup_grace) + self.read_calls += 1 + return b"nope" + + async def sweep_temp_files(self, prefix: str = "/tmp/lg_smtv_cap_") -> None: + _ = prefix + + async def close(self) -> None: + return None + + transport = FakeTransport() + client = CaptureClient(transport) + + async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]: + _ = (uri, payload) + return {"returnValue": False} + + with pytest.raises(TvError) as exc_info: + await client.capture_frame(ssap_request) + assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE + assert transport.read_calls == 0 + + +async def test_capture_client_preserves_standby_and_pairing_errors(tmp_path: Path) -> None: + _ = tmp_path + + class FakeTransport: + async def read_and_remove( + self, remote_path: str, timeout: float = 6.0, cleanup_grace: float = 1.5 + ) -> bytes: + _ = (remote_path, timeout, cleanup_grace) + return b"img" + + async def sweep_temp_files(self, prefix: str = "/tmp/lg_smtv_cap_") -> None: + _ = prefix + + async def close(self) -> None: + return None + + client = CaptureClient(FakeTransport()) + + async def standby_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]: + _ = (uri, payload) + raise TvError(ErrorCode.TV_OFFLINE_STANDBY, "standby") + + with pytest.raises(TvError) as standby_exc: + await client.capture_frame(standby_request) + assert standby_exc.value.code is ErrorCode.TV_OFFLINE_STANDBY + + async def pairing_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]: + _ = (uri, payload) + raise TvError(ErrorCode.PAIRING_REQUIRED, "pairing") + + with pytest.raises(TvError) as pairing_exc: + await client.capture_frame(pairing_request) + assert pairing_exc.value.code is ErrorCode.PAIRING_REQUIRED + + +async def test_capture_client_maps_command_failed_without_sftp_read(tmp_path: Path) -> None: + _ = tmp_path + + class FakeTransport: + def __init__(self) -> None: + self.read_calls = 0 + + async def read_and_remove( + self, remote_path: str, timeout: float = 6.0, cleanup_grace: float = 1.5 + ) -> bytes: + _ = (remote_path, timeout, cleanup_grace) + self.read_calls += 1 + return b"nope" + + async def sweep_temp_files(self, prefix: str = "/tmp/lg_smtv_cap_") -> None: + _ = prefix + + async def close(self) -> None: + return None + + transport = FakeTransport() + client = CaptureClient(transport) + + async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]: + _ = (uri, payload) + raise TvError(ErrorCode.COMMAND_FAILED, "executeOneShot failed") + + with pytest.raises(TvError) as exc_info: + await client.capture_frame(ssap_request) + assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE + assert transport.read_calls == 0 + + +async def test_capture_client_maps_sftp_os_error_to_screenshot_unavailable(tmp_path: Path) -> None: + _ = tmp_path + + class FakeTransport: + async def read_and_remove( + self, remote_path: str, timeout: float = 6.0, cleanup_grace: float = 1.5 + ) -> bytes: + _ = (remote_path, timeout, cleanup_grace) + raise OSError("sftp read failed") + + async def sweep_temp_files(self, prefix: str = "/tmp/lg_smtv_cap_") -> None: + _ = prefix + + async def close(self) -> None: + return None + + client = CaptureClient(FakeTransport()) + + async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]: + _ = (uri, payload) + return {"returnValue": True} + + with pytest.raises(TvError) as exc_info: + await client.capture_frame(ssap_request) + assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE + + +async def test_capture_client_maps_timeout_to_screenshot_unavailable(tmp_path: Path) -> None: + _ = tmp_path + + class FakeTransport: + async def read_and_remove( + self, remote_path: str, timeout: float = 6.0, cleanup_grace: float = 1.5 + ) -> bytes: + _ = (remote_path, timeout, cleanup_grace) + return b"img" + + async def sweep_temp_files(self, prefix: str = "/tmp/lg_smtv_cap_") -> None: + _ = prefix + + async def close(self) -> None: + return None + + client = CaptureClient(FakeTransport()) + + async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]: + _ = (uri, payload) + await asyncio.sleep(10) + return {"returnValue": True} + + with pytest.raises(TvError) as exc_info: + await client.capture_frame(ssap_request) + assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE From 227bf6aa2113f75135d0294f0844800660dd88d5 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Mon, 16 Nov 2026 17:57:04 -0500 Subject: [PATCH 2/4] feat(server): wire default capture client and exports - tv_core: export AsyncSshCaptureTransport and CaptureClient from package __init__ for default manager wiring - server: pass CaptureClient(AsyncSshCaptureTransport(config)) when create_mcp_server builds the default TvManager while keeping explicit manager injection unchanged - tests: add offline server wiring coverage asserting default TvManager receives a CaptureClient backed by AsyncSshCaptureTransport --- src/lg_smtv_mcp/server.py | 8 +++++-- src/lg_smtv_mcp/tv_core/__init__.py | 3 +++ tests/test_server.py | 34 +++++++++++++++++++++++++++++ 3 files changed, 43 insertions(+), 2 deletions(-) diff --git a/src/lg_smtv_mcp/server.py b/src/lg_smtv_mcp/server.py index b80de19..a5d3d43 100644 --- a/src/lg_smtv_mcp/server.py +++ b/src/lg_smtv_mcp/server.py @@ -16,7 +16,7 @@ from mcp.types import ImageContent, TextContent from lg_smtv_mcp.auth import ASGIApp, build_transport_security_settings, wrap_bearer_auth from lg_smtv_mcp.config import TvConfig, require_bearer_token from lg_smtv_mcp.errors import ConfigError, TvError -from lg_smtv_mcp.tv_core import TvManager +from lg_smtv_mcp.tv_core import AsyncSshCaptureTransport, CaptureClient, TvManager async def _run_tv_call[T](fn: Callable[[], Awaitable[T]]) -> T: @@ -157,7 +157,11 @@ def _register_tools(server: MCPServer, tv_manager: TvManager, config: TvConfig) def create_mcp_server(config: TvConfig, manager: TvManager | None = None) -> MCPServer: """Create and configure the MCPServer instance with TV tools and lifespan.""" - tv_manager = manager if manager is not None else TvManager(config) + tv_manager = ( + manager + if manager is not None + else TvManager(config, capture_client=CaptureClient(AsyncSshCaptureTransport(config))) + ) @asynccontextmanager async def _lifespan(_server: MCPServer[None]) -> AsyncGenerator[None]: diff --git a/src/lg_smtv_mcp/tv_core/__init__.py b/src/lg_smtv_mcp/tv_core/__init__.py index 9ff3c77..fdcd1c6 100644 --- a/src/lg_smtv_mcp/tv_core/__init__.py +++ b/src/lg_smtv_mcp/tv_core/__init__.py @@ -1,5 +1,6 @@ """Core LG webOS TV transport, protocol, and state machine package.""" +from lg_smtv_mcp.tv_core.capture import AsyncSshCaptureTransport, CaptureClient from lg_smtv_mcp.tv_core.manager import ConnectionState, TvManager, TvState, send_wol from lg_smtv_mcp.tv_core.pointer import BUTTON_ALLOWLIST, PointerClient, normalize_button_keys from lg_smtv_mcp.tv_core.protocols import ( @@ -22,7 +23,9 @@ from lg_smtv_mcp.tv_core.ssap import ( ) __all__ = [ + "AsyncSshCaptureTransport", "BUTTON_ALLOWLIST", + "CaptureClient", "CaptureResult", "CaptureTransport", "ConnectionState", diff --git a/tests/test_server.py b/tests/test_server.py index 6da11a0..805f054 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -457,3 +457,37 @@ async def test_server_http_app_allows_authenticated_mcp_initialize_request( finally: allow_shutdown.set() await asyncio.wait_for(lifespan_task, timeout=2.0) + + +async def test_server_create_mcp_server_wires_default_capture_client(tmp_path: Path) -> None: + import lg_smtv_mcp.server as server_mod + from lg_smtv_mcp.tv_core.capture import AsyncSshCaptureTransport, CaptureClient + + config = _make_config(tmp_path) + captured: dict[str, Any] = {} + original_tv_manager = server_mod.TvManager + + class DummyManager: + async def start(self) -> None: + return None + + async def close(self) -> None: + return None + + def fake_tv_manager(cfg: Any, **kwargs: Any) -> DummyManager: + captured["config"] = cfg + captured["kwargs"] = kwargs + return DummyManager() + + server_mod.TvManager = fake_tv_manager # type: ignore[assignment] + try: + server_mod.create_mcp_server(config) + finally: + server_mod.TvManager = original_tv_manager # type: ignore[assignment] + + assert captured["config"] is config + assert "capture_client" in captured["kwargs"] + capture_client = captured["kwargs"]["capture_client"] + assert isinstance(capture_client, CaptureClient) + transport = capture_client._transport # pyright: ignore[reportPrivateUsage] + assert isinstance(transport, AsyncSshCaptureTransport) From 260a792e0b7e470c0ca95acd290c5b66fdd6c7f5 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Mon, 16 Nov 2026 19:44:21 -0500 Subject: [PATCH 3/4] fix(capture): require successful screenshot response - Require returnValue true before reading capture bytes. - Cover cancellation cleanup, SFTP timeout, and default server capture behavior. --- src/lg_smtv_mcp/tv_core/capture.py | 4 +- tests/test_capture.py | 89 ++++++++++++++++++++++++++---- tests/test_server.py | 75 +++++++++++++++++++++---- 3 files changed, 144 insertions(+), 24 deletions(-) diff --git a/src/lg_smtv_mcp/tv_core/capture.py b/src/lg_smtv_mcp/tv_core/capture.py index 2b92d01..25fb6bf 100644 --- a/src/lg_smtv_mcp/tv_core/capture.py +++ b/src/lg_smtv_mcp/tv_core/capture.py @@ -160,10 +160,10 @@ class CaptureClient: f"executeOneShot failed: {exc.message}", ) from exc - if response.get("returnValue") is False: + if response.get("returnValue") is not True: raise TvError( ErrorCode.SCREENSHOT_UNAVAILABLE, - "executeOneShot returned returnValue false", + "executeOneShot did not return returnValue true", ) try: diff --git a/tests/test_capture.py b/tests/test_capture.py index da69b41..41f8102 100644 --- a/tests/test_capture.py +++ b/tests/test_capture.py @@ -149,12 +149,25 @@ async def test_async_ssh_capture_transport_sweeps_on_initial_connect_and_reconne assert "/tmp/keep.txt" not in sftp2.remove_calls -async def test_async_ssh_capture_transport_shields_remove_on_read_error(tmp_path: Path) -> None: - sftp = FakeSftpClient( - files={"/tmp/lg_smtv_cap_1.jpg": b"jpeg"}, - read_error=OSError("read failed"), - remove_delay=0.05, - ) +async def test_async_ssh_capture_transport_finishes_remove_after_cancellation( + tmp_path: Path, +) -> None: + remote_path = "/tmp/lg_smtv_cap_1.jpg" + + class BlockingRemoveSftp(FakeSftpClient): + def __init__(self) -> None: + super().__init__(files={remote_path: b"jpeg"}) + self.remove_started = asyncio.Event() + self.allow_remove = asyncio.Event() + self.remove_finished = asyncio.Event() + + async def remove(self, path: str) -> None: + self.remove_started.set() + await self.allow_remove.wait() + await super().remove(path) + self.remove_finished.set() + + sftp = BlockingRemoveSftp() conn = FakeSshConnection(sftp) async def fake_connect(**kwargs: Any) -> FakeSshConnection: @@ -162,10 +175,20 @@ async def test_async_ssh_capture_transport_shields_remove_on_read_error(tmp_path return conn transport = AsyncSshCaptureTransport(_make_config(tmp_path), connect_fn=fake_connect) - with pytest.raises(OSError, match="read failed"): - await transport.read_and_remove("/tmp/lg_smtv_cap_1.jpg", timeout=6.0, cleanup_grace=1.5) + read_task = asyncio.create_task(transport.read_and_remove(remote_path)) + try: + await asyncio.wait_for(sftp.remove_started.wait(), timeout=1.0) + read_task.cancel() + with pytest.raises(asyncio.CancelledError): + await read_task + finally: + sftp.allow_remove.set() + if not read_task.done(): + read_task.cancel() + await asyncio.gather(read_task, return_exceptions=True) - assert "/tmp/lg_smtv_cap_1.jpg" in sftp.remove_calls + await asyncio.wait_for(sftp.remove_finished.wait(), timeout=1.0) + assert remote_path in sftp.remove_calls async def test_capture_client_sends_execute_one_shot_and_returns_metadata(tmp_path: Path) -> None: @@ -246,8 +269,13 @@ async def test_capture_client_changed_since_last_and_close_resets(tmp_path: Path assert third.changed_since_last is True -async def test_capture_client_maps_execute_one_shot_failure_without_sftp_read( - tmp_path: Path, +@pytest.mark.parametrize( + "response", + [{"returnValue": False}, {}, {"returnValue": None}], + ids=["false", "missing", "null"], +) +async def test_capture_client_rejects_non_true_return_value_without_sftp_read( + tmp_path: Path, response: dict[str, Any] ) -> None: _ = tmp_path @@ -273,7 +301,7 @@ async def test_capture_client_maps_execute_one_shot_failure_without_sftp_read( async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]: _ = (uri, payload) - return {"returnValue": False} + return response with pytest.raises(TvError) as exc_info: await client.capture_frame(ssap_request) @@ -402,3 +430,40 @@ async def test_capture_client_maps_timeout_to_screenshot_unavailable(tmp_path: P with pytest.raises(TvError) as exc_info: await client.capture_frame(ssap_request) assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE + + +async def test_capture_client_maps_sftp_timeout_and_cancels_read(tmp_path: Path) -> None: + _ = tmp_path + + class BlockingTransport: + def __init__(self) -> None: + self.read_cancelled = asyncio.Event() + + async def read_and_remove( + self, remote_path: str, timeout: float = 6.0, cleanup_grace: float = 1.5 + ) -> bytes: + _ = (remote_path, timeout, cleanup_grace) + try: + await asyncio.Event().wait() + finally: + self.read_cancelled.set() + raise AssertionError("capture read should be cancelled by the timeout") + + async def sweep_temp_files(self, prefix: str = "/tmp/lg_smtv_cap_") -> None: + _ = prefix + + async def close(self) -> None: + return None + + transport = BlockingTransport() + client = CaptureClient(transport) + + async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]: + _ = (uri, payload) + return {"returnValue": True} + + with pytest.raises(TvError) as exc_info: + await asyncio.wait_for(client.capture_frame(ssap_request), timeout=7.0) + + assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE + assert transport.read_cancelled.is_set() diff --git a/tests/test_server.py b/tests/test_server.py index 805f054..c758518 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -10,6 +10,7 @@ from contextlib import asynccontextmanager from pathlib import Path from typing import Any +import asyncssh import httpx import pytest from mcp.server.mcpserver.exceptions import ToolError @@ -459,13 +460,17 @@ async def test_server_http_app_allows_authenticated_mcp_initialize_request( await asyncio.wait_for(lifespan_task, timeout=2.0) -async def test_server_create_mcp_server_wires_default_capture_client(tmp_path: Path) -> None: +async def test_server_create_mcp_server_wires_default_capture_client( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: import lg_smtv_mcp.server as server_mod - from lg_smtv_mcp.tv_core.capture import AsyncSshCaptureTransport, CaptureClient + from lg_smtv_mcp.tv_core.capture import CaptureClient config = _make_config(tmp_path) captured: dict[str, Any] = {} - original_tv_manager = server_mod.TvManager + remote_files: dict[str, bytes] = {} + removed_paths: list[str] = [] + connect_calls: list[dict[str, Any]] = [] class DummyManager: async def start(self) -> None: @@ -474,20 +479,70 @@ async def test_server_create_mcp_server_wires_default_capture_client(tmp_path: P async def close(self) -> None: return None + class FakeSftp: + def __init__(self) -> None: + self.closed = False + + async def listdir(self, path: str) -> list[str]: + _ = path + return [] + + async def read(self, path: str) -> bytes: + return remote_files[path] + + async def remove(self, path: str) -> None: + removed_paths.append(path) + remote_files.pop(path, None) + + async def exit(self) -> None: + self.closed = True + + sftp_sessions: list[FakeSftp] = [] + + class FakeSshConnection: + async def start_sftp_client(self) -> FakeSftp: + sftp = FakeSftp() + sftp_sessions.append(sftp) + return sftp + + def close(self) -> None: + return None + + async def wait_closed(self) -> None: + return None + def fake_tv_manager(cfg: Any, **kwargs: Any) -> DummyManager: captured["config"] = cfg captured["kwargs"] = kwargs return DummyManager() - server_mod.TvManager = fake_tv_manager # type: ignore[assignment] - try: - server_mod.create_mcp_server(config) - finally: - server_mod.TvManager = original_tv_manager # type: ignore[assignment] + async def fake_connect(**kwargs: Any) -> FakeSshConnection: + connect_calls.append(kwargs) + return FakeSshConnection() + + monkeypatch.setattr(server_mod, "TvManager", fake_tv_manager) + monkeypatch.setattr(asyncssh, "connect", fake_connect) + server_mod.create_mcp_server(config) assert captured["config"] is config assert "capture_client" in captured["kwargs"] capture_client = captured["kwargs"]["capture_client"] assert isinstance(capture_client, CaptureClient) - transport = capture_client._transport # pyright: ignore[reportPrivateUsage] - assert isinstance(transport, AsyncSshCaptureTransport) + + async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]: + assert uri == "ssap://com.webos.service.capture/executeOneShot" + remote_files[payload["path"]] = _TEST_JPEG + return {"returnValue": True} + + try: + result = await capture_client.capture_frame(ssap_request) + finally: + await capture_client.close() + + assert result.image_bytes == _TEST_JPEG + assert len(connect_calls) == 1 + assert connect_calls[0]["host"] == config.tv_ip + assert connect_calls[0]["port"] == 9922 + assert removed_paths == ["/tmp/lg_smtv_cap_1.jpg"] + assert len(sftp_sessions) == 1 + assert sftp_sessions[0].closed is True From 61d231523e25ec342beffe06c3233580db14da4e Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Mon, 16 Nov 2026 22:31:35 -0500 Subject: [PATCH 4/4] fix(capture): exclude in-flight screenshot from session sweep and harden error boundaries - src/lg_smtv_mcp/tv_core/capture.py: - Preserve in-flight remote_path by passing exclude=remote_path to _ensure_sftp and sweep_temp_files so new-session temp sweeps do not delete the pending frame (CR-01). - Deterministically close connection handles on start_sftp_client failure or cancellation (CR-03). - Enforce timeout budget with asyncio.timeout inside read_and_remove (CR-06). - Attach exception-consuming callback to shielded remove_task to prevent unobserved task warnings if cleanup grace expires (CR-07). - Collapse duplicate COMMAND_FAILED and fallback error mapping branches in capture_frame (CR-05). - src/lg_smtv_mcp/tv_core/protocols.py: - Add optional exclude: str | None = None parameter to CaptureTransport.sweep_temp_files. - tests/test_capture.py: - Update FakeSftpClient.listdir to return real files from self.files to eliminate test double discrepancy (CR-02). - Add tests for in-flight sweep preservation, connection cleanup on SFTP failure, and read timeout enforcement. - Hoist shared FakeCaptureTransport, deduplicate inline test doubles, and drop unused tmp_path fixtures (CR-09). - Use fast cleanup_grace=0.05 in cancellation test to avoid real-time stalls (CR-08). --- src/lg_smtv_mcp/tv_core/capture.py | 67 +++--- src/lg_smtv_mcp/tv_core/protocols.py | 6 +- tests/test_capture.py | 310 +++++++++++++-------------- 3 files changed, 192 insertions(+), 191 deletions(-) diff --git a/src/lg_smtv_mcp/tv_core/capture.py b/src/lg_smtv_mcp/tv_core/capture.py index 25fb6bf..8c137ca 100644 --- a/src/lg_smtv_mcp/tv_core/capture.py +++ b/src/lg_smtv_mcp/tv_core/capture.py @@ -54,12 +54,12 @@ class AsyncSshCaptureTransport: if asyncio.iscoroutine(res): await res - async def _ensure_sftp(self) -> Any: + async def _ensure_sftp(self, exclude: str | None = None) -> Any: if self._sftp is not None: return self._sftp config = self._config - self._conn = await self._connect_fn( + conn = await self._connect_fn( host=config.tv_ip, port=9922, username="prisoner", @@ -74,9 +74,22 @@ class AsyncSshCaptureTransport: client_keys=[str(config.ssh_key_path)] if config.ssh_key_path is not None else None, passphrase=config.webos_ssh_passphrase, ) - self._sftp = await self._conn.start_sftp_client() + try: + sftp = await conn.start_sftp_client() + except BaseException: + conn.close() + with suppress(Exception): + wait_closed = getattr(conn, "wait_closed", None) + if callable(wait_closed): + res = wait_closed() + if asyncio.iscoroutine(res): + await res + raise + + self._conn = conn + self._sftp = sftp with suppress(Exception): - await self.sweep_temp_files("/tmp/lg_smtv_cap_") + await self.sweep_temp_files("/tmp/lg_smtv_cap_", exclude=exclude) return self._sftp async def read_and_remove( @@ -85,32 +98,41 @@ class AsyncSshCaptureTransport: timeout: float = 6.0, cleanup_grace: float = 1.5, ) -> bytes: - _ = timeout # timeout budget is enforced by CaptureClient around the full operation + sftp = None try: - sftp = await self._ensure_sftp() - try: + async with asyncio.timeout(timeout): + sftp = await self._ensure_sftp(exclude=remote_path) data = await sftp.read(remote_path) - if not isinstance(data, (bytes, bytearray)): - data = bytes(data) - else: - data = bytes(data) - finally: - with suppress(Exception): - await asyncio.wait_for( - asyncio.shield(sftp.remove(remote_path)), - timeout=cleanup_grace, - ) - return data + return bytes(data) except asyncssh.Error, OSError: await self._close_handles() raise + finally: + if sftp is not None: + remove_task = asyncio.create_task(sftp.remove(remote_path)) - async def sweep_temp_files(self, prefix: str = "/tmp/lg_smtv_cap_") -> None: + def _consume_exception(task: asyncio.Task[Any]) -> None: + with suppress(Exception): + _ = task.exception() + + remove_task.add_done_callback(_consume_exception) + with suppress(Exception): + await asyncio.wait_for( + asyncio.shield(remove_task), + timeout=cleanup_grace, + ) + + async def sweep_temp_files( + self, + prefix: str = "/tmp/lg_smtv_cap_", + exclude: str | None = None, + ) -> None: sftp = self._sftp if sftp is None: return directory = os.path.dirname(prefix) or "/tmp" name_prefix = os.path.basename(prefix) + exclude_name = os.path.basename(exclude) if exclude else None try: entries = await sftp.listdir(directory) except Exception: @@ -118,6 +140,8 @@ class AsyncSshCaptureTransport: for entry in entries: if not isinstance(entry, str) or not entry.startswith(name_prefix): continue + if exclude_name is not None and entry == exclude_name: + continue remote_path = f"{directory.rstrip('/')}/{entry}" with suppress(Exception): await sftp.remove(remote_path) @@ -150,11 +174,6 @@ class CaptureClient: except TvError as exc: if exc.code in (ErrorCode.TV_OFFLINE_STANDBY, ErrorCode.PAIRING_REQUIRED): raise - if exc.code is ErrorCode.COMMAND_FAILED: - raise TvError( - ErrorCode.SCREENSHOT_UNAVAILABLE, - f"executeOneShot failed: {exc.message}", - ) from exc raise TvError( ErrorCode.SCREENSHOT_UNAVAILABLE, f"executeOneShot failed: {exc.message}", diff --git a/src/lg_smtv_mcp/tv_core/protocols.py b/src/lg_smtv_mcp/tv_core/protocols.py index 9f1793f..907845a 100644 --- a/src/lg_smtv_mcp/tv_core/protocols.py +++ b/src/lg_smtv_mcp/tv_core/protocols.py @@ -38,7 +38,11 @@ class CaptureTransport(Protocol): cleanup_grace: float = 1.5, ) -> bytes: ... - async def sweep_temp_files(self, prefix: str = "/tmp/lg_smtv_cap_") -> None: ... + async def sweep_temp_files( + self, + prefix: str = "/tmp/lg_smtv_cap_", + exclude: str | None = None, + ) -> None: ... async def close(self) -> None: ... diff --git a/tests/test_capture.py b/tests/test_capture.py index 41f8102..b3e9be3 100644 --- a/tests/test_capture.py +++ b/tests/test_capture.py @@ -17,13 +17,13 @@ class FakeSftpClient: self, *, files: dict[str, bytes] | None = None, - list_names: list[str] | None = None, + extra_names: list[str] | None = None, read_error: Exception | None = None, remove_delay: float = 0.0, remove_error: Exception | None = None, ) -> None: self.files = dict(files or {}) - self.list_names = list(list_names or []) + self.extra_names = list(extra_names or []) self.read_error = read_error self.remove_delay = remove_delay self.remove_error = remove_error @@ -46,12 +46,11 @@ class FakeSftpClient: if self.remove_error is not None: raise self.remove_error self.files.pop(path, None) - if path in self.list_names: - self.list_names.remove(path) async def listdir(self, path: str) -> list[str]: _ = path - return list(self.list_names) + names = {Path(p).name for p in self.files} | set(self.extra_names) + return sorted(names) async def exit(self) -> None: self.closed = True @@ -74,6 +73,48 @@ class FakeSshConnection: return None +class FakeCaptureTransport: + def __init__( + self, + *, + image_bytes: bytes = b"default-image", + read_error: Exception | None = None, + block_read: bool = False, + ) -> None: + self.image_bytes = image_bytes + self.read_error = read_error + self.block_read = block_read + self.read_calls: list[tuple[str, float, float]] = [] + self.read_cancelled = asyncio.Event() + self.closed = False + + async def read_and_remove( + self, + remote_path: str, + timeout: float = 6.0, + cleanup_grace: float = 1.5, + ) -> bytes: + self.read_calls.append((remote_path, timeout, cleanup_grace)) + if self.block_read: + try: + await asyncio.Event().wait() + finally: + self.read_cancelled.set() + if self.read_error is not None: + raise self.read_error + return self.image_bytes + + async def sweep_temp_files( + self, + prefix: str = "/tmp/lg_smtv_cap_", + exclude: str | None = None, + ) -> None: + _ = (prefix, exclude) + + async def close(self) -> None: + self.closed = True + + def _make_config(tmp_path: Path, *, with_ssh: bool = False) -> TvConfig: ssh_key = tmp_path / "id_rsa" known_hosts = tmp_path / "known_hosts" @@ -89,7 +130,7 @@ def _make_config(tmp_path: Path, *, with_ssh: bool = False) -> TvConfig: async def test_async_ssh_capture_transport_connect_uses_required_args(tmp_path: Path) -> None: - sftp = FakeSftpClient(files={"/tmp/lg_smtv_cap_1.jpg": b"jpeg"}, list_names=[]) + sftp = FakeSftpClient(files={"/tmp/lg_smtv_cap_1.jpg": b"jpeg"}) conn = FakeSshConnection(sftp) calls: list[dict[str, Any]] = [] @@ -119,12 +160,12 @@ async def test_async_ssh_capture_transport_sweeps_on_initial_connect_and_reconne ) -> None: sftp1 = FakeSftpClient( files={"/tmp/lg_smtv_cap_1.jpg": b"one"}, - list_names=["lg_smtv_cap_old.jpg", "other.txt"], + extra_names=["lg_smtv_cap_old.jpg", "other.txt"], ) conn1 = FakeSshConnection(sftp1) sftp2 = FakeSftpClient( files={"/tmp/lg_smtv_cap_2.jpg": b"two"}, - list_names=["lg_smtv_cap_stale.jpg", "keep.txt"], + extra_names=["lg_smtv_cap_stale.jpg", "keep.txt"], ) conn2 = FakeSshConnection(sftp2) conns = [conn1, conn2] @@ -149,6 +190,81 @@ async def test_async_ssh_capture_transport_sweeps_on_initial_connect_and_reconne assert "/tmp/keep.txt" not in sftp2.remove_calls +async def test_async_ssh_capture_transport_sweep_preserves_in_flight_remote_path( + tmp_path: Path, +) -> None: + remote_path = "/tmp/lg_smtv_cap_1.jpg" + sftp = FakeSftpClient( + files={ + remote_path: b"fresh-frame", + "/tmp/lg_smtv_cap_stale.jpg": b"stale-frame", + }, + extra_names=["other_file.txt"], + ) + conn = FakeSshConnection(sftp) + + async def fake_connect(**kwargs: Any) -> FakeSshConnection: + _ = kwargs + return conn + + transport = AsyncSshCaptureTransport(_make_config(tmp_path), connect_fn=fake_connect) + data = await transport.read_and_remove(remote_path) + + assert data == b"fresh-frame" + assert "/tmp/lg_smtv_cap_stale.jpg" in sftp.remove_calls + assert remote_path in sftp.remove_calls + assert "/tmp/other_file.txt" not in sftp.remove_calls + + +async def test_async_ssh_capture_transport_closes_connection_when_start_sftp_client_fails( + tmp_path: Path, +) -> None: + class FailingSshConnection: + def __init__(self) -> None: + self.closed = False + + async def start_sftp_client(self) -> Any: + raise OSError("sftp start failed") + + def close(self) -> None: + self.closed = True + + async def wait_closed(self) -> None: + return None + + conn = FailingSshConnection() + + async def fake_connect(**kwargs: Any) -> FailingSshConnection: + _ = kwargs + return conn + + transport = AsyncSshCaptureTransport(_make_config(tmp_path), connect_fn=fake_connect) + with pytest.raises(OSError): + await transport.read_and_remove("/tmp/lg_smtv_cap_1.jpg") + + assert conn.closed is True + + +async def test_async_ssh_capture_transport_enforces_read_timeout( + tmp_path: Path, +) -> None: + class HangingSftp(FakeSftpClient): + async def read(self, path: str) -> bytes: + await asyncio.sleep(10.0) + return b"never" + + sftp = HangingSftp(files={"/tmp/lg_smtv_cap_1.jpg": b"bytes"}) + conn = FakeSshConnection(sftp) + + async def fake_connect(**kwargs: Any) -> FakeSshConnection: + _ = kwargs + return conn + + transport = AsyncSshCaptureTransport(_make_config(tmp_path), connect_fn=fake_connect) + with pytest.raises(TimeoutError): + await transport.read_and_remove("/tmp/lg_smtv_cap_1.jpg", timeout=0.05) + + async def test_async_ssh_capture_transport_finishes_remove_after_cancellation( tmp_path: Path, ) -> None: @@ -175,7 +291,7 @@ async def test_async_ssh_capture_transport_finishes_remove_after_cancellation( return conn transport = AsyncSshCaptureTransport(_make_config(tmp_path), connect_fn=fake_connect) - read_task = asyncio.create_task(transport.read_and_remove(remote_path)) + read_task = asyncio.create_task(transport.read_and_remove(remote_path, cleanup_grace=0.05)) try: await asyncio.wait_for(sftp.remove_started.wait(), timeout=1.0) read_task.cancel() @@ -191,29 +307,11 @@ async def test_async_ssh_capture_transport_finishes_remove_after_cancellation( assert remote_path in sftp.remove_calls -async def test_capture_client_sends_execute_one_shot_and_returns_metadata(tmp_path: Path) -> None: - _ = tmp_path +async def test_capture_client_sends_execute_one_shot_and_returns_metadata() -> None: image = b"frame-bytes" expected_sha = hashlib.sha256(image).hexdigest() - class FakeTransport: - def __init__(self) -> None: - self.read_calls: list[tuple[str, float, float]] = [] - self.closed = False - - async def read_and_remove( - self, remote_path: str, timeout: float = 6.0, cleanup_grace: float = 1.5 - ) -> bytes: - self.read_calls.append((remote_path, timeout, cleanup_grace)) - return image - - async def sweep_temp_files(self, prefix: str = "/tmp/lg_smtv_cap_") -> None: - _ = prefix - - async def close(self) -> None: - self.closed = True - - transport = FakeTransport() + transport = FakeCaptureTransport(image_bytes=image) client = CaptureClient(transport) calls: list[tuple[str, dict[str, Any]]] = [] @@ -236,24 +334,8 @@ async def test_capture_client_sends_execute_one_shot_and_returns_metadata(tmp_pa assert result.size_bytes == len(image) -async def test_capture_client_changed_since_last_and_close_resets(tmp_path: Path) -> None: - _ = tmp_path - image = b"same" - - class FakeTransport: - async def read_and_remove( - self, remote_path: str, timeout: float = 6.0, cleanup_grace: float = 1.5 - ) -> bytes: - _ = (remote_path, timeout, cleanup_grace) - return image - - async def sweep_temp_files(self, prefix: str = "/tmp/lg_smtv_cap_") -> None: - _ = prefix - - async def close(self) -> None: - return None - - client = CaptureClient(FakeTransport()) +async def test_capture_client_changed_since_last_and_close_resets() -> None: + client = CaptureClient(FakeCaptureTransport(image_bytes=b"same")) async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]: _ = (uri, payload) @@ -275,28 +357,9 @@ async def test_capture_client_changed_since_last_and_close_resets(tmp_path: Path ids=["false", "missing", "null"], ) async def test_capture_client_rejects_non_true_return_value_without_sftp_read( - tmp_path: Path, response: dict[str, Any] + response: dict[str, Any], ) -> None: - _ = tmp_path - - class FakeTransport: - def __init__(self) -> None: - self.read_calls = 0 - - async def read_and_remove( - self, remote_path: str, timeout: float = 6.0, cleanup_grace: float = 1.5 - ) -> bytes: - _ = (remote_path, timeout, cleanup_grace) - self.read_calls += 1 - return b"nope" - - async def sweep_temp_files(self, prefix: str = "/tmp/lg_smtv_cap_") -> None: - _ = prefix - - async def close(self) -> None: - return None - - transport = FakeTransport() + transport = FakeCaptureTransport() client = CaptureClient(transport) async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]: @@ -306,26 +369,11 @@ async def test_capture_client_rejects_non_true_return_value_without_sftp_read( with pytest.raises(TvError) as exc_info: await client.capture_frame(ssap_request) assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE - assert transport.read_calls == 0 + assert len(transport.read_calls) == 0 -async def test_capture_client_preserves_standby_and_pairing_errors(tmp_path: Path) -> None: - _ = tmp_path - - class FakeTransport: - async def read_and_remove( - self, remote_path: str, timeout: float = 6.0, cleanup_grace: float = 1.5 - ) -> bytes: - _ = (remote_path, timeout, cleanup_grace) - return b"img" - - async def sweep_temp_files(self, prefix: str = "/tmp/lg_smtv_cap_") -> None: - _ = prefix - - async def close(self) -> None: - return None - - client = CaptureClient(FakeTransport()) +async def test_capture_client_preserves_standby_and_pairing_errors() -> None: + client = CaptureClient(FakeCaptureTransport()) async def standby_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]: _ = (uri, payload) @@ -344,27 +392,8 @@ async def test_capture_client_preserves_standby_and_pairing_errors(tmp_path: Pat assert pairing_exc.value.code is ErrorCode.PAIRING_REQUIRED -async def test_capture_client_maps_command_failed_without_sftp_read(tmp_path: Path) -> None: - _ = tmp_path - - class FakeTransport: - def __init__(self) -> None: - self.read_calls = 0 - - async def read_and_remove( - self, remote_path: str, timeout: float = 6.0, cleanup_grace: float = 1.5 - ) -> bytes: - _ = (remote_path, timeout, cleanup_grace) - self.read_calls += 1 - return b"nope" - - async def sweep_temp_files(self, prefix: str = "/tmp/lg_smtv_cap_") -> None: - _ = prefix - - async def close(self) -> None: - return None - - transport = FakeTransport() +async def test_capture_client_maps_command_failed_without_sftp_read() -> None: + transport = FakeCaptureTransport() client = CaptureClient(transport) async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]: @@ -374,26 +403,12 @@ async def test_capture_client_maps_command_failed_without_sftp_read(tmp_path: Pa with pytest.raises(TvError) as exc_info: await client.capture_frame(ssap_request) assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE - assert transport.read_calls == 0 + assert len(transport.read_calls) == 0 -async def test_capture_client_maps_sftp_os_error_to_screenshot_unavailable(tmp_path: Path) -> None: - _ = tmp_path - - class FakeTransport: - async def read_and_remove( - self, remote_path: str, timeout: float = 6.0, cleanup_grace: float = 1.5 - ) -> bytes: - _ = (remote_path, timeout, cleanup_grace) - raise OSError("sftp read failed") - - async def sweep_temp_files(self, prefix: str = "/tmp/lg_smtv_cap_") -> None: - _ = prefix - - async def close(self) -> None: - return None - - client = CaptureClient(FakeTransport()) +async def test_capture_client_maps_sftp_os_error_to_screenshot_unavailable() -> None: + transport = FakeCaptureTransport(read_error=OSError("sftp read failed")) + client = CaptureClient(transport) async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]: _ = (uri, payload) @@ -404,23 +419,8 @@ async def test_capture_client_maps_sftp_os_error_to_screenshot_unavailable(tmp_p assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE -async def test_capture_client_maps_timeout_to_screenshot_unavailable(tmp_path: Path) -> None: - _ = tmp_path - - class FakeTransport: - async def read_and_remove( - self, remote_path: str, timeout: float = 6.0, cleanup_grace: float = 1.5 - ) -> bytes: - _ = (remote_path, timeout, cleanup_grace) - return b"img" - - async def sweep_temp_files(self, prefix: str = "/tmp/lg_smtv_cap_") -> None: - _ = prefix - - async def close(self) -> None: - return None - - client = CaptureClient(FakeTransport()) +async def test_capture_client_maps_timeout_to_screenshot_unavailable() -> None: + client = CaptureClient(FakeCaptureTransport()) async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]: _ = (uri, payload) @@ -432,30 +432,8 @@ async def test_capture_client_maps_timeout_to_screenshot_unavailable(tmp_path: P assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE -async def test_capture_client_maps_sftp_timeout_and_cancels_read(tmp_path: Path) -> None: - _ = tmp_path - - class BlockingTransport: - def __init__(self) -> None: - self.read_cancelled = asyncio.Event() - - async def read_and_remove( - self, remote_path: str, timeout: float = 6.0, cleanup_grace: float = 1.5 - ) -> bytes: - _ = (remote_path, timeout, cleanup_grace) - try: - await asyncio.Event().wait() - finally: - self.read_cancelled.set() - raise AssertionError("capture read should be cancelled by the timeout") - - async def sweep_temp_files(self, prefix: str = "/tmp/lg_smtv_cap_") -> None: - _ = prefix - - async def close(self) -> None: - return None - - transport = BlockingTransport() +async def test_capture_client_maps_sftp_timeout_and_cancels_read() -> None: + transport = FakeCaptureTransport(block_read=True) client = CaptureClient(transport) async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]: