"""The integration contract: ``register(subparsers)`` into someone else's CLI. The registrant is assumed to know nothing about the daemon beyond the socket path, so these tests drive the handlers through a host parser they build themselves and stub out the transport. """ from __future__ import annotations import argparse import io import json from contextlib import redirect_stderr, redirect_stdout import pytest import hhstream_session from hhstream_session import register from hhstream_session.client import ClientError from hhstreamd.protocol import ExitCode @pytest.fixture def host_cli(): """A stand-in for the pre-existing ``hhstream`` CLI.""" parser = argparse.ArgumentParser(prog="hhstream") sub = parser.add_subparsers(dest="command") existing = sub.add_parser("frame", help="an existing subcommand") existing.set_defaults(func=lambda args: 0) register(sub) return parser @pytest.fixture def sent(monkeypatch): """Capture what the handlers would send, and reply with what the test wants.""" class Transport(list): """The captured requests, plus the canned replies to hand back.""" replies = [ { "ok": True, "id": "stub-aaaaaa", "session": {"id": "stub-aaaaaa", "state": "ready"}, "sessions": [], "lines": [], } ] calls = Transport() def fake_call(op, *, socket_path=None, timeout=None, **fields): # Mirror protocol.request(): unset fields are not put on the wire, so # the tests below can assert on what is actually sent. wire = {k: v for k, v in fields.items() if v is not None} calls.append({"op": op, "socket_path": socket_path, **wire}) return calls.replies[min(len(calls) - 1, len(calls.replies) - 1)] monkeypatch.setattr(hhstream_session, "call", fake_call) return calls def run(parser: argparse.ArgumentParser, argv: list[str]) -> tuple[int, str, str]: args = parser.parse_args(argv) out, err = io.StringIO(), io.StringIO() with redirect_stdout(out), redirect_stderr(err): code = hhstream_session.dispatch(args) return code, out.getvalue(), err.getvalue() # --------------------------------------------------------------------------- # registration # --------------------------------------------------------------------------- def test_registration_adds_exactly_one_subcommand_and_leaves_the_host_alone(host_cli): args = host_cli.parse_args(["frame"]) assert args.func(args) == 0 # the pre-existing subcommand still works args = host_cli.parse_args(["session", "list"]) assert callable(args.func) def test_the_handler_is_exposed_under_both_the_common_name_and_a_namespaced_one(host_cli): args = host_cli.parse_args(["session", "status", "foo-aaaaaa"]) assert args.func is args.hhstream_session_handler def test_every_v1_verb_is_registered(host_cli): for verb in ["start", "list", "status", "touch", "kill", "gc", "adopt", "logs"]: argv = ["session", verb] if verb in ("status", "touch", "kill", "logs"): argv.append("foo-aaaaaa") if verb == "start": argv.append("foot") if verb == "adopt": argv += ["--pid", "1234"] args = host_cli.parse_args(argv) assert callable(args.func), verb def test_session_with_no_verb_lists(host_cli, sent): code, _, _ = run(host_cli, ["session"]) assert code == ExitCode.OK assert sent[0]["op"] == "list" def test_the_socket_may_be_given_before_or_after_the_verb(host_cli, sent): run(host_cli, ["session", "--socket", "/a.sock", "list"]) run(host_cli, ["session", "list", "--socket", "/b.sock"]) assert sent[0]["socket_path"] == "/a.sock" assert sent[1]["socket_path"] == "/b.sock" def test_the_socket_falls_back_to_the_environment(host_cli, sent, monkeypatch): """The registrant's only piece of daemon knowledge.""" monkeypatch.setenv("HHSTREAM_SOCKET", "/env.sock") run(host_cli, ["session", "list"]) # The handler passes None through; the client resolves the default. assert sent[0]["socket_path"] is None from hhstream_session.client import default_socket_path assert default_socket_path() == "/env.sock" # --------------------------------------------------------------------------- # request shapes # --------------------------------------------------------------------------- def test_start_sends_the_app_and_an_argv_list_never_a_command_string(host_cli, sent): run(host_cli, ["session", "start", "chromium", "--", "--new-window", "https://example.com"]) assert sent[0]["op"] == "start" assert sent[0]["app"] == "chromium" assert sent[0]["argv"] == ["--new-window", "https://example.com"] def test_this_commands_own_flags_still_parse_after_the_app_name(host_cli, sent): """The separator divides the two argvs; it does not divide the parsers.""" run(host_cli, ["session", "start", "chromium", "--idle-timeout", "5m", "--", "--new-window"]) assert sent[0]["idle_timeout_s"] == 300.0 assert sent[0]["argv"] == ["--new-window"] def test_an_application_flag_after_the_separator_is_never_read_as_ours(host_cli, sent): run(host_cli, ["session", "start", "chromium", "--", "--idle-timeout", "5m"]) assert "idle_timeout_s" not in sent[0] assert sent[0]["argv"] == ["--idle-timeout", "5m"] def test_durations_are_parsed_on_the_way_in(host_cli, sent): run(host_cli, ["session", "start", "foot", "--idle-timeout", "3h"]) assert sent[0]["idle_timeout_s"] == 10800.0 run(host_cli, ["session", "kill", "foo-aaaaaa", "--grace", "30s"]) assert sent[1]["grace_s"] == 30.0 def test_a_bad_duration_is_rejected_by_argparse(host_cli): with pytest.raises(SystemExit): host_cli.parse_args(["session", "start", "foot", "--idle-timeout", "soon"]) def test_home_and_ephemeral_home_are_mutually_exclusive(host_cli): with pytest.raises(SystemExit): host_cli.parse_args(["session", "start", "foot", "--home", "/x", "--ephemeral-home"]) def test_ephemeral_home_is_opt_in_and_absent_by_default(host_cli, sent): run(host_cli, ["session", "start", "foot"]) assert "ephemeral_home" not in sent[0] run(host_cli, ["session", "start", "foot", "--ephemeral-home"]) assert sent[1]["ephemeral_home"] is True def test_list_all_is_only_sent_when_asked(host_cli, sent): run(host_cli, ["session", "list"]) assert "all" not in sent[0] run(host_cli, ["session", "list", "--all"]) assert sent[1]["all"] is True def test_request_ids_are_forwarded_on_mutating_verbs(host_cli, sent): run(host_cli, ["session", "start", "foot", "--request-id", "abc"]) assert sent[0]["request_id"] == "abc" # --------------------------------------------------------------------------- # output and exit codes # --------------------------------------------------------------------------- def test_start_prints_the_bare_id_on_stdout_and_detail_on_stderr(host_cli, sent): sent.replies[:] = [ { "ok": True, "id": "foot-k3f9qx", "session": { "id": "foot-k3f9qx", "app": "foot", "pid": 48812, "pgid": 48812, "sid": 48812, "state": "ready", "ready_signal": "spawned", "idle_timeout_s": 10800, }, } ] code, out, err = run(host_cli, ["session", "start", "foot"]) assert code == ExitCode.OK assert out == "foot-k3f9qx\n" # exactly the id, so $(...) works assert "pid 48812" in err assert "touch foot-k3f9qx" in err # the keepalive is named where it is needed def test_start_json_puts_one_object_on_stdout_and_nothing_on_stderr(host_cli, sent): sent.replies[:] = [{"ok": True, "id": "foot-k3f9qx", "session": {"id": "foot-k3f9qx"}}] code, out, err = run(host_cli, ["session", "start", "--json", "foot"]) assert code == ExitCode.OK assert json.loads(out) == {"id": "foot-k3f9qx"} assert err == "" def test_json_is_available_on_every_read_verb(host_cli, sent): sent.replies[:] = [{"ok": True, "sessions": []}] code, out, _ = run(host_cli, ["session", "list", "--json"]) assert json.loads(out)["ok"] is True sent.replies[:] = [{"ok": True, "session": {"id": "a"}, "id": "a"}] code, out, _ = run(host_cli, ["session", "status", "--json", "a"]) assert json.loads(out)["session"] == {"id": "a"} sent.replies[:] = [{"ok": True, "lines": ["hello"], "offset": 6, "eof": True}] code, out, _ = run(host_cli, ["session", "logs", "--json", "a"]) assert json.loads(out)["lines"] == ["hello"] def test_errors_go_to_stderr_with_the_machine_field_in_json_mode(host_cli, sent): sent.replies[:] = [ {"ok": False, "error": "not_allowlisted", "reason": "app 'sh' is not in the allowlist"} ] code, out, err = run(host_cli, ["session", "start", "--json", "sh"]) assert code == ExitCode.POLICY assert out == "" assert json.loads(err)["error"] == "not_allowlisted" def test_errors_are_human_readable_without_json(host_cli, sent): sent.replies[:] = [ {"ok": False, "error": "no_such_session", "reason": "no session 'x'", "hint": "try list"} ] code, out, err = run(host_cli, ["session", "status", "x"]) assert code == ExitCode.NO_SUCH_SESSION assert "no session 'x'" in err and "try list" in err def test_a_transport_failure_becomes_exit_five_not_a_traceback(host_cli, monkeypatch): def boom(*args, **kwargs): raise ClientError("daemon_unreachable", "nothing is listening", hint="start it") monkeypatch.setattr(hhstream_session, "call", boom) code, _, err = run(host_cli, ["session", "list"]) assert code == ExitCode.DAEMON_UNREACHABLE assert "nothing is listening" in err and "start it" in err # --------------------------------------------------------------------------- # the activity contract, as documented to the user # --------------------------------------------------------------------------- def test_the_help_text_says_touch_is_the_only_mark_of_activity(host_cli): out = io.StringIO() with redirect_stdout(out): with pytest.raises(SystemExit): host_cli.parse_args(["session", "--help"]) text = out.getvalue() assert "touch" in text assert "ONLY" in text for verb in ["list", "status", "logs", "gc"]: assert verb in text @pytest.mark.parametrize("verb", ["list", "status", "logs", "gc"]) def test_each_read_verbs_help_says_it_does_not_count(host_cli, verb): out = io.StringIO() with redirect_stdout(out): with pytest.raises(SystemExit): host_cli.parse_args(["session", "--help"]) line = [l for l in out.getvalue().splitlines() if l.strip().startswith(verb)] assert line, verb assert "does NOT count" in " ".join(out.getvalue().split()) def test_touchs_help_calls_itself_the_only_mark_of_activity(host_cli): out = io.StringIO() with redirect_stdout(out): with pytest.raises(SystemExit): host_cli.parse_args(["session", "touch", "--help"]) assert "only verb that counts as activity" in " ".join(out.getvalue().split())