Files
hyprland-headless-stream-pl…/tests/live/test_live_cli.py
HermenixandClaude Opus 5 bd3ca2e644 fix(live): hhstream-live with no subcommand serves, and SIGTERM stops it
`cmd_serve` read `args.capture_command`, which only exists on the `serve`
subparser, so a bare `hhstream-live` died with an `AttributeError`. The word
`serve` is now inserted before parsing rather than defaulted afterwards: the
top-level parser would otherwise reject `hhstream-live --port 9999` for an
unknown option before anything could be filled in. `--help` is left alone so
it still shows the program's own help. `--log-level` gained a copy on each
subparser, defaulting to `SUPPRESS` so that naming the subcommand does not
reset it.

SIGTERM had no handler, so the default action killed the process and
`server.stop()` never ran -- the exit status was a signal, not a 0. The
handler is installed before the listener is bound, so a supervisor's first
signal is never the fatal one.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01URhyHGQnmKH9zBXxoznfQY
2026-10-06 16:20:00 +00:00

126 lines
4.3 KiB
Python

"""The command line: it aims a capture at an output, and it can mint a phrase."""
from __future__ import annotations
import io
import os
import pathlib
import re
import signal
import subprocess
import sys
import time
from contextlib import redirect_stdout
import pytest
from hhstream_live.__main__ import (DEFAULT_CAPTURE, capture_argv, main, parse_args,
parse_stream)
#: What `hhstream-live phrase` must print: four alphabetic words and a tail.
PHRASE_SHAPE = re.compile(r"^[a-z]+(?:-[a-z]+){3}-[a-z0-9]{5}$")
_SRC = pathlib.Path(__file__).resolve().parents[2] / "src"
def test_capture_command_is_aimed_by_inserting_the_output_before_stdout():
assert capture_argv(DEFAULT_CAPTURE, "hh-demo") == [
"grim", "-c", "-t", "jpeg", "-q", "80", "-o", "hh-demo", "-",
]
def test_capture_command_without_a_trailing_dash_gets_the_output_appended():
assert capture_argv(["grim", "-t", "jpeg"], "hh-x") == [
"grim", "-t", "jpeg", "-o", "hh-x",
]
def test_parse_stream_reads_a_pair_and_normalizes_the_phrase():
assert parse_stream("Amber-Otter-Lantern-Harbor-7K2QP=hh-demo") == (
"amber-otter-lantern-harbor-7k2qp", "hh-demo",
)
@pytest.mark.parametrize("bad", ["no-equals-sign", "=hh-demo", "phrase=", "ab=hh"])
def test_parse_stream_rejects_a_bad_pair(bad):
import argparse
with pytest.raises(argparse.ArgumentTypeError):
parse_stream(bad)
def test_the_phrase_subcommand_prints_a_phrase():
out = io.StringIO()
with redirect_stdout(out):
assert main(["phrase"]) == 0
printed = out.getvalue().strip()
# Not just `count("-") == 4`: a hyphenated word on the list would satisfy
# the count with five words and four hyphens in the wrong places.
assert PHRASE_SHAPE.match(printed), printed
def test_the_phrase_subcommand_can_print_several():
out = io.StringIO()
with redirect_stdout(out):
main(["phrase", "--count", "3"])
assert len(out.getvalue().split()) == 3
# ---- the default subcommand, and shutdown ----------------------------------
def test_a_bare_command_line_means_serve():
"""`hhstream-live` with no subcommand is `hhstream-live serve`.
The serve options live on the `serve` subparser, so the namespace has to be
the subparser's; reading `capture_command` off the top-level one is the
`AttributeError` this guards.
"""
args = parse_args([])
assert args.command == "serve"
assert args.capture_command is None
assert args.port and args.bind and args.stream == []
assert args.log_level == "info"
def test_serve_options_work_without_naming_the_subcommand():
args = parse_args(["--port", "0", "--bind", "0.0.0.0"])
assert (args.command, args.port, args.bind) == ("serve", 0, "0.0.0.0")
def test_a_global_option_survives_the_subcommand():
"""`--log-level` is on both parsers; the subparser must not reset it."""
assert parse_args(["--log-level", "debug"]).log_level == "debug"
assert parse_args(["--log-level", "debug", "serve"]).log_level == "debug"
assert parse_args(["--log-level", "debug", "phrase"]).log_level == "debug"
def test_a_bare_run_serves_and_sigterm_stops_it_cleanly():
"""The whole path: no subcommand, then the signal a service is stopped with.
`SIGTERM`'s default action kills the process outright, so without a handler
`server.stop()` never runs and the exit status is a signal, not a 0.
"""
env = dict(os.environ, PYTHONPATH=os.pathsep.join(
[str(_SRC), os.environ.get("PYTHONPATH", "")]).rstrip(os.pathsep))
proc = subprocess.Popen(
[sys.executable, "-m", "hhstream_live", "--port", "0"],
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, env=env,
)
try:
deadline = time.monotonic() + 20
banner = ""
while "landing page:" not in banner and time.monotonic() < deadline:
line = proc.stderr.readline()
if not line:
break
banner += line
assert "landing page:" in banner, banner
assert "bound to 127.0.0.1:" in banner, banner
proc.send_signal(signal.SIGTERM)
out, err = proc.communicate(timeout=20)
except BaseException:
proc.kill()
proc.communicate()
raise
assert proc.returncode == 0, (proc.returncode, banner, err)
assert "Traceback" not in err, err