Three layers, because the stream has three and each one can be wrong on its own. `tests/live/test_live_control.py` (20 tests) runs `Control` against a fake capture: the four ops, `attach` idempotent on the phrase, the same phrase aimed at another output refused, a malformed phrase refused *without the value in the message*, and `fps` defaulting to the daemon's when the broker sends none. `tests/sessions/unit/test_stream_verbs.py` (24 tests) runs the broker against a fake daemon, and its subjects are the decisions rather than the plumbing: no container output is a refusal and never a fallback to the main output; a re-`enable` returns the same phrase and a different one is exit 8; a down daemon turns `attached` false rather than failing a read; the sweep touches a watched session and leaves an unwatched one alone; teardown detaches before the container is destroyed. `tests/unit/test_mcp_*` grow the two tools, the two resources and the three `session_start` arguments, with the read-only half asserted *absent* as a tool by name -- re-adding one should be a failure, not a silent widening. `checks/vm-stream.nix` is the new guest check, and it exists for the two things none of the above can say: 1. **That `grim` captures a real compositor from inside a unit.** It reads actual JPEGs off `/<phrase>/stream.mjpg` with `checks/lib/mjpeg_read.py`, a hand-rolled multipart reader that shares no code with the server -- a parser that did could not tell you the boundary was wrong. It framed on SOI/EOI rather than `Content-Length` for the same reason. This is what caught the unit's missing `XDG_RUNTIME_DIR`: `frames: [25827, 25827, 25827]` now, ten capture failures and a stream that gave up before. 2. **That a connected viewer moves the idle clock.** That needs the broker's real sweep, on a real timer, with a client genuinely still there a minute later -- hence `--hold`, and hence a check that spends ~90 seconds twice. The negative control runs first, because if the sweep touched an unwatched stream the positive case would pass for the wrong reason. Measured in the guest: with nobody watching `580s -> 502s` remaining, with a viewer `499s -> 596s`. It also asserts the phrase is in neither the audit log nor a 404 body, that the old URL stops serving after `disable`, that `disable` then `enable` rotates it, that `kill` takes the stream down and leaves the daemon up, and that `start --stream` yields an id and a URL that serves frames. No clock is injected anywhere in this check. An injected one would prove the arithmetic, which the unit tests already do, and not the daemon. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011ZeH65zd6pFTgBSu52W9PE
350 lines
14 KiB
Python
350 lines
14 KiB
Python
"""The resource table: which URI runs which CLI call, and what comes back.
|
|
|
|
Same subject as ``test_mcp_tools.py`` and the same stand-in: what this layer
|
|
decides is the argv list, and here also the *routing* -- which entry a URI
|
|
resolves to, and which query parameters it will accept. Nothing here imports
|
|
the MCP SDK; the protocol wiring is ``test_mcp_server.py``.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
|
|
import mcp_fake
|
|
import pytest
|
|
from hhstreamd.protocol import ExitCode
|
|
from hhstream_mcp import invoke, resources, tools
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _isolated(monkeypatch, tmp_path):
|
|
mcp_fake.isolate(monkeypatch, tmp_path)
|
|
|
|
|
|
@pytest.fixture
|
|
def read():
|
|
"""`read("hhstream://sessions")` -> (Reading, [argv, ...])."""
|
|
|
|
def _read(uri, **script):
|
|
fake = mcp_fake.FakeCli(**script)
|
|
reading = resources.read(invoke.Runner(fake), uri)
|
|
return reading, fake.calls
|
|
|
|
return _read
|
|
|
|
|
|
# ── the table ──────────────────────────────────────────────────────────────
|
|
|
|
#: Every resource `docs/CONTRACT-mcp.md` §4 freezes, written out rather than
|
|
#: derived, for the reason the tool list is.
|
|
EXPECTED_FIXED = {
|
|
"hhstream://status",
|
|
"hhstream://sessions",
|
|
"hhstream://pointer",
|
|
"hhstream://containers",
|
|
"hhstream://streams",
|
|
"hhstream://screen",
|
|
}
|
|
EXPECTED_TEMPLATES = {
|
|
"hhstream://sessions/{id}{?events}",
|
|
"hhstream://sessions/{id}/logs{?lines}",
|
|
"hhstream://sessions/{id}/stream",
|
|
"hhstream://outputs/{name}",
|
|
}
|
|
|
|
|
|
def test_the_whole_surface_is_there_and_nothing_else_is():
|
|
assert {entry.uri for entry in resources.FIXED} == EXPECTED_FIXED
|
|
assert {entry.uri_template for entry in resources.TEMPLATES} == EXPECTED_TEMPLATES
|
|
assert len(resources.ENTRIES) == len(EXPECTED_FIXED) + len(EXPECTED_TEMPLATES)
|
|
|
|
|
|
def test_every_entry_has_a_unique_name_and_a_description():
|
|
names = [entry.name for entry in resources.ENTRIES]
|
|
assert len(names) == len(set(names))
|
|
for entry in resources.ENTRIES:
|
|
assert entry.title, entry.name
|
|
assert len(entry.description) > 40, entry.name
|
|
assert entry.media_type
|
|
|
|
|
|
def test_a_template_is_exactly_an_entry_with_a_capture():
|
|
for entry in resources.FIXED:
|
|
assert entry.captures == ()
|
|
for entry in resources.TEMPLATES:
|
|
assert entry.captures
|
|
|
|
|
|
def test_the_three_reads_the_activity_rule_names_say_so_themselves():
|
|
"""The rule has to be where it is read, and these are read, not called."""
|
|
|
|
for name in ("sessions", "session", "session-logs", "pointer", "containers",
|
|
"streams", "session-stream"):
|
|
description = resources.BY_NAME[name].description
|
|
assert "does NOT reset" in description, name
|
|
assert "`session_touch`" in description, name
|
|
|
|
|
|
# ── routing ────────────────────────────────────────────────────────────────
|
|
|
|
|
|
def test_a_literal_route_beats_a_template_that_would_also_match():
|
|
"""`hhstream://sessions` is the listing, not a session with a blank id."""
|
|
|
|
entry, arguments = resources.resolve("hhstream://sessions")
|
|
assert entry.name == "sessions"
|
|
assert arguments == {}
|
|
|
|
|
|
def test_a_capture_becomes_the_argument_the_cli_takes(read):
|
|
_, calls = read("hhstream://sessions/foot-abc", stdout=mcp_fake.reply(ok=True))
|
|
assert calls == [["session", "status", "--json", "--", "foot-abc"]]
|
|
|
|
|
|
def test_a_deeper_route_is_its_own_entry(read):
|
|
_, calls = read("hhstream://sessions/foot-abc/logs", stdout=mcp_fake.reply(ok=True))
|
|
assert calls == [["session", "logs", "--json", "--", "foot-abc"]]
|
|
|
|
|
|
def test_each_fixed_resource_runs_the_verb_it_names(read):
|
|
cases = {
|
|
"hhstream://status": ["status"],
|
|
"hhstream://sessions": ["session", "list", "--json"],
|
|
"hhstream://pointer": ["session", "pointer", "state", "--json"],
|
|
"hhstream://containers": ["session", "container", "--json"],
|
|
"hhstream://streams": ["session", "stream", "list", "--json"],
|
|
}
|
|
for uri, argv in cases.items():
|
|
_, calls = read(uri, stdout=mcp_fake.reply(ok=True))
|
|
assert calls == [argv], uri
|
|
|
|
|
|
def test_the_status_resource_is_text_because_the_verb_has_no_json(read):
|
|
reading, calls = read("hhstream://status", stdout="services:\n up\n")
|
|
assert calls == [["status"]]
|
|
assert reading.media_type == "text/plain"
|
|
assert reading.text == "services:\n up"
|
|
assert reading.blob is None
|
|
|
|
|
|
def test_a_json_resource_passes_the_protocol_object_through_unchanged(read):
|
|
reply = {"ok": True, "sessions": [{"id": "s-1", "state": "running"}]}
|
|
reading, _ = read("hhstream://sessions", stdout=json.dumps(reply, indent=2))
|
|
|
|
assert reading.media_type == "application/json"
|
|
assert json.loads(reading.text) == reply
|
|
|
|
|
|
def test_a_scheme_this_server_does_not_serve_is_refused(read):
|
|
with pytest.raises(resources.ReadRefused) as caught:
|
|
read("file:///etc/passwd")
|
|
assert "not a hhstream resource" in str(caught.value)
|
|
|
|
|
|
def test_a_uri_that_names_nothing_is_refused_and_points_at_the_listing(read):
|
|
for uri in ("hhstream://nonsense", "hhstream://sessions/a/b/c", "hhstream://"):
|
|
with pytest.raises(resources.ReadRefused) as caught:
|
|
read(uri)
|
|
assert "resources/list" in str(caught.value) or "names no resource" in str(
|
|
caught.value
|
|
)
|
|
|
|
|
|
def test_nothing_was_run_for_a_uri_that_did_not_resolve(monkeypatch, tmp_path):
|
|
"""The routing refuses before the CLI is reached, as a schema would."""
|
|
|
|
fake = mcp_fake.FakeCli()
|
|
with pytest.raises(resources.ReadRefused):
|
|
resources.read(invoke.Runner(fake), "hhstream://nonsense")
|
|
assert fake.calls == []
|
|
|
|
|
|
# ── query parameters ───────────────────────────────────────────────────────
|
|
|
|
|
|
def test_a_declared_parameter_becomes_the_flag_the_cli_takes(read):
|
|
_, calls = read(
|
|
"hhstream://sessions/foot-abc/logs?lines=250", stdout=mcp_fake.reply(ok=True)
|
|
)
|
|
assert calls == [["session", "logs", "--json", "--lines=250", "--", "foot-abc"]]
|
|
|
|
_, calls = read(
|
|
"hhstream://sessions/foot-abc?events=5", stdout=mcp_fake.reply(ok=True)
|
|
)
|
|
assert calls == [["session", "status", "--json", "--events=5", "--", "foot-abc"]]
|
|
|
|
|
|
def test_a_switch_parameter_is_a_bare_flag_or_nothing(read):
|
|
"""`--all=false` is not a thing the CLI takes, so false must omit it."""
|
|
|
|
_, calls = read("hhstream://sessions?all=true", stdout=mcp_fake.reply(ok=True))
|
|
assert calls == [["session", "list", "--json", "--all"]]
|
|
|
|
for falsey in ("false", "0", "no", "off", ""):
|
|
_, calls = read(f"hhstream://sessions?all={falsey}", stdout=mcp_fake.reply(ok=True))
|
|
assert calls == [["session", "list", "--json"]], falsey
|
|
|
|
|
|
def test_an_undeclared_parameter_is_refused_rather_than_dropped(read):
|
|
"""A parameter silently ignored is a read that answered another question."""
|
|
|
|
with pytest.raises(resources.ReadRefused) as caught:
|
|
read("hhstream://sessions?lines=5")
|
|
assert "'lines'" in str(caught.value)
|
|
assert "all" in str(caught.value)
|
|
|
|
|
|
def test_a_resource_with_no_parameters_says_so_when_given_one(read):
|
|
with pytest.raises(resources.ReadRefused) as caught:
|
|
read("hhstream://pointer?id=s-1")
|
|
assert "accepts: none" in str(caught.value)
|
|
|
|
|
|
def test_a_parameter_given_twice_is_refused(read):
|
|
with pytest.raises(resources.ReadRefused) as caught:
|
|
read("hhstream://sessions/s-1/logs?lines=1&lines=2")
|
|
assert "more than once" in str(caught.value)
|
|
|
|
|
|
def test_the_template_advertises_the_parameters_it_accepts():
|
|
"""So a client can construct a URI without guessing."""
|
|
|
|
logs = resources.BY_NAME["session-logs"]
|
|
assert logs.uri_template == "hhstream://sessions/{id}/logs{?lines}"
|
|
assert logs.parameters == ("lines",)
|
|
|
|
|
|
# ── refusals ───────────────────────────────────────────────────────────────
|
|
|
|
|
|
def test_a_cli_refusal_is_raised_and_never_returned_as_the_body(read):
|
|
"""A resource has no `isError`; returning the failure object would lie."""
|
|
|
|
reply = {"ok": False, "error": "no_such_session", "reason": "no session 'nope'"}
|
|
with pytest.raises(resources.ReadRefused) as caught:
|
|
read(
|
|
"hhstream://sessions/nope",
|
|
stderr=mcp_fake.reply(**reply),
|
|
exit_code=int(ExitCode.NO_SUCH_SESSION),
|
|
)
|
|
refused = caught.value
|
|
assert "exit 3 (NO_SUCH_SESSION)" in refused.message
|
|
assert "no session 'nope'" in refused.message
|
|
# And the structured detail carries what a tool error would have carried.
|
|
assert refused.detail["exit_code"] == int(ExitCode.NO_SUCH_SESSION)
|
|
assert refused.detail["error"] == "no_such_session"
|
|
assert "hhstream://sessions" in refused.detail["remedy"]
|
|
|
|
|
|
def test_an_unreachable_broker_is_refused_with_the_operator_s_remedy(read):
|
|
with pytest.raises(resources.ReadRefused) as caught:
|
|
read(
|
|
"hhstream://sessions",
|
|
stderr=mcp_fake.reply(ok=False, error="daemon_unreachable", reason="no socket"),
|
|
exit_code=int(ExitCode.DAEMON_UNREACHABLE),
|
|
)
|
|
assert "HHSTREAM_SOCKET" in caught.value.message
|
|
|
|
|
|
# ── frames ─────────────────────────────────────────────────────────────────
|
|
|
|
|
|
def test_the_screen_resource_is_the_frame_bytes_with_its_real_media_type(read):
|
|
frame = mcp_fake.png(width=320, height=180)
|
|
reading, calls = read("hhstream://screen", write_png=frame)
|
|
|
|
assert calls[0][0] == "shot"
|
|
assert calls[0][1].startswith("--out=")
|
|
assert len(calls[0]) == 2, "the screen takes no --output"
|
|
assert reading.blob == frame
|
|
assert reading.text is None
|
|
assert reading.media_type == "image/png"
|
|
|
|
|
|
def test_an_output_resource_captures_that_output_alone(read):
|
|
frame = mcp_fake.png()
|
|
reading, calls = read("hhstream://outputs/hh-foot-abc", write_png=frame)
|
|
|
|
assert "--output=hh-foot-abc" in calls[0]
|
|
assert reading.blob == frame
|
|
|
|
|
|
def test_a_frame_s_media_type_is_sniffed_and_not_assumed(read):
|
|
"""The entry declares image/png; a JPEG publisher must still be told truly."""
|
|
|
|
assert resources.BY_NAME["screen"].media_type == "image/png"
|
|
reading, _ = read("hhstream://screen", write_png=mcp_fake.jpeg())
|
|
assert reading.media_type == "image/jpeg"
|
|
|
|
|
|
def test_a_capture_that_wrote_no_file_is_refused_rather_than_empty(read):
|
|
with pytest.raises(resources.ReadRefused) as caught:
|
|
read("hhstream://screen")
|
|
assert "no readable file" in str(caught.value)
|
|
|
|
|
|
def test_a_refused_capture_carries_the_cli_s_own_words(read):
|
|
with pytest.raises(resources.ReadRefused) as caught:
|
|
read(
|
|
"hhstream://outputs/hh-gone",
|
|
stderr="hhstream: could not capture output 'hh-gone': unknown output\n",
|
|
exit_code=1,
|
|
)
|
|
assert "unknown output" in str(caught.value)
|
|
assert "hh-gone" in str(caught.value)
|
|
|
|
|
|
# ── the stream ─────────────────────────────────────────────────────────────
|
|
|
|
|
|
def test_one_session_s_stream_reads_through_its_own_route(read):
|
|
_, calls = read("hhstream://sessions/foot-abc/stream", stdout=mcp_fake.reply(ok=True))
|
|
assert calls == [["session", "stream", "status", "--json", "--", "foot-abc"]]
|
|
|
|
|
|
def test_the_stream_routes_do_not_collide_with_the_logs_route():
|
|
"""Three templates under `sessions/{id}`; each must resolve to its own."""
|
|
|
|
assert resources.resolve("hhstream://sessions/x")[0].name == "session"
|
|
assert resources.resolve("hhstream://sessions/x/logs")[0].name == "session-logs"
|
|
assert resources.resolve("hhstream://sessions/x/stream")[0].name == "session-stream"
|
|
|
|
|
|
def test_reading_a_stream_never_enables_one(read):
|
|
"""The read is `status`, not `enable` -- switching one on is a tool."""
|
|
|
|
_, calls = read("hhstream://sessions/x/stream", stdout=mcp_fake.reply(ok=True))
|
|
assert "enable" not in calls[0]
|
|
_, calls = read("hhstream://streams", stdout=mcp_fake.reply(ok=True))
|
|
assert "enable" not in calls[0]
|
|
|
|
|
|
def test_both_stream_reads_warn_that_the_url_carries_its_credential():
|
|
"""The URL is in these bodies, so the warning has to be on them."""
|
|
|
|
for name in ("streams", "session-stream"):
|
|
description = resources.BY_NAME[name].description
|
|
assert "PHRASE" in description, name
|
|
assert "only thing protecting" in resources.BY_NAME["streams"].description
|
|
|
|
|
|
def test_the_streams_listing_says_a_viewer_is_the_activity_exception():
|
|
"""The one exception to `session_touch`, where somebody will read it."""
|
|
|
|
description = resources.BY_NAME["streams"].description
|
|
assert "does NOT reset" in description
|
|
assert "connected viewer" in description
|
|
|
|
|
|
# ── the one read that must not be a resource ───────────────────────────────
|
|
|
|
|
|
def test_there_is_no_resource_for_the_reconciling_container_read():
|
|
"""`session container <id>` writes. Only the no-id list is a resource."""
|
|
|
|
assert "hhstream://containers" in EXPECTED_FIXED
|
|
for entry in resources.ENTRIES:
|
|
assert entry.route[:1] != ("containers",) or entry.captures == ()
|
|
# ...and the writing form is still reachable, as a tool.
|
|
assert "session_container" in tools.BY_NAME
|