Files
hyprland-headless-stream-pl…/tests/unit/mcp_fake.py
T
HermenixandClaude Opus 5 fea55eecde test(mcp): the argv each tool builds, the mapping, and the server in a guest
101 unit tests under `tests/unit/` and one new VM check.

The unit suite's subject is the only thing this layer decides: the argv list.
`mcp_fake.FakeCli` is a recording stand-in put where the CLI goes, so every
test can assert on the exact argv a tool handed over -- the `=` form of each
flag, the `--` before each positional, the omission of a flag the caller did
not give. Three tests drive the **real** entry point against a control socket
that does not exist, which proves the dispatch, the capture and the exit-code
mapping against the CLI's actual parser with no daemon standing up: argparse's
exit 2 for a bad `--button`, exit 5 for the unreachable broker, exit 9 for a
gesture with no lease.

`test_mcp_server.py` imports the MCP SDK unconditionally and runs the server
in process over the SDK's memory transport. It is not allowed to skip: the tool
table is stdlib and tested without the SDK, but whether every schema validates
and every name is one the specification allows is a question only the SDK can
answer, and a file that skipped when it was absent would be green in exactly
the build where that mattered. `checks/unit.nix` therefore puts `mcp` in the
test environment and `hhstream-mcp` on PYTHONPATH beside `hhstream`.

`checks/vm-mcp.nix` boots the session machine with `mcp.enable = true` and
drives the real binary over a real pipe with `checks/lib/mcp_client.py` -- raw
JSON-RPC, deliberately not the SDK's client, for the reason
`tests/assert_stream.py` is a second implementation of the frame contract. It
asserts the handshake, the 26-tool listing with its annotations and its two
rules, a call that reaches the live broker, `shot` as image content, the lease
granted/used/returned against the real driver, and exits 9 and 3 arriving as
tool errors.

The geometry assertion in that check is one it got wrong first time and now
records: the published frame is 2560x720 on a guest configured for 1280x720,
because the publisher's default capture takes the whole compositor layout and a
session's container is a second output beside the main one. `shot` with the
container's own `output` is the one that is exactly 1280x720.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011ZeH65zd6pFTgBSu52W9PE
2026-10-11 06:32:55 +00:00

153 lines
5.1 KiB
Python

"""A recording stand-in for the CLI, and two image fixtures, for the MCP tests.
The MCP server calls ``hhstream.cli``'s handlers in this process, so what sits
between a tool and the broker is **the argv list** -- and that list is the only
thing this layer decides. :class:`FakeCli` is therefore an entry point that
records the argv it was given, prints whatever the test told it to, and returns
the exit code the test chose: everything the real entry point is, minus the
broker.
That is also why there is no live socket anywhere in this suite. The broker's
behaviour is `tests/sessions`' subject and the VM checks'; what is left here is
the shim. Two tests in ``test_mcp_invoke.py`` do drive the **real** entry point
against a socket path that does not exist, which is the honest way to prove the
dispatch, the capture and the exit-code mapping without standing a daemon up.
"""
from __future__ import annotations
import json
import pathlib
import struct
import sys
import zlib
from typing import Any
class FakeCli:
"""Where :func:`hhstream_mcp.invoke.dispatch` goes in a test.
Prints through ``sys.stdout``/``sys.stderr`` rather than returning text, so
the capture under test is exercised rather than bypassed.
"""
def __init__(
self,
*,
stdout: str = "",
stderr: str = "",
exit_code: int = 0,
write_png: bytes | None = None,
raises: BaseException | None = None,
) -> None:
self.stdout = stdout
self.stderr = stderr
self.exit_code = exit_code
self.write_png = write_png
self.raises = raises
#: Every argv this was called with, in order.
self.calls: list[list[str]] = []
def __call__(self, argv: list[str]) -> int:
self.calls.append(list(argv))
if self.write_png is not None:
destination = _value_of("--out", argv)
if destination:
pathlib.Path(destination).write_bytes(self.write_png)
if self.stdout:
sys.stdout.write(self.stdout)
if self.stderr:
sys.stderr.write(self.stderr)
if self.raises is not None:
raise self.raises
return self.exit_code
@property
def argv(self) -> list[str]:
"""The single call's argv. Fails loudly if there was not exactly one."""
assert len(self.calls) == 1, f"expected one CLI call, got {self.calls}"
return self.calls[0]
def _value_of(name: str, argv: list[str]) -> str | None:
prefix = f"{name}="
for argument in argv:
if argument.startswith(prefix):
return argument[len(prefix) :]
return None
def reply(**fields: Any) -> str:
"""A protocol object the way the CLI prints one: ``json.dumps(indent=2)``."""
return json.dumps(fields, indent=2, sort_keys=True) + "\n"
def png(width: int = 8, height: int = 4) -> bytes:
"""A minimal valid truecolour PNG of a known size.
Built here rather than shared with the suite's other helper because what is
under test is "the server reports the geometry the file actually has", so
the size has to be the test's to choose.
"""
def chunk(kind: bytes, data: bytes) -> bytes:
return (
struct.pack(">I", len(data))
+ kind
+ data
+ struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
)
raster = (b"\x00" + b"\x10\x20\x30" * width) * height
return (
b"\x89PNG\r\n\x1a\n"
+ chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0))
+ chunk(b"IDAT", zlib.compress(raster, 9))
+ chunk(b"IEND", b"")
)
def jpeg(width: int = 6, height: int = 3) -> bytes:
"""Enough of a JPEG to carry a SOF0: magic, APP0, SOF0, EOI.
Not a decodable image, deliberately: what is under test is the header scan
that has to skip a segment it does not care about and find the one it does.
"""
app0 = (
b"\xff\xe0"
+ struct.pack(">H", 16)
+ b"JFIF\x00"
+ b"\x01\x01\x00"
+ b"\x00\x01" * 2
+ b"\x00\x00"
)
sof0 = (
b"\xff\xc0"
+ struct.pack(">H", 11)
+ b"\x08"
+ struct.pack(">HH", height, width)
+ b"\x01\x01\x11\x00"
)
return b"\xff\xd8" + app0 + sof0 + b"\xff\xd9"
def isolate(monkeypatch, tmp_path: pathlib.Path) -> None:
"""Point every path the CLI reads from the environment at ``tmp_path``.
A developer's shell has `$HHSTREAM_SOCKET` set, and the real entry point
reads it -- so without this a test could reach a live broker on the machine
it is running on. The lease directory is redirected for the same reason:
`pointer acquire` writes a cache there, and a test must not touch the one a
real session is using.
"""
monkeypatch.setenv("HHSTREAM_SOCKET", str(tmp_path / "control.sock"))
monkeypatch.setenv("HHSTREAM_FRAME_SOCKET", str(tmp_path / "stream.sock"))
monkeypatch.setenv("HHSTREAM_LEASE_DIR", str(tmp_path / "leases"))
# `$HHSTREAM_LEASE` outranks the cache in `hhstream_session.lease.recall`,
# so an inherited one would hand a gesture a lease it never acquired.
monkeypatch.delenv("HHSTREAM_LEASE", raising=False)