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
This commit is contained in:
HermenixandClaude Opus 5 committed 2026-10-06 16:20:00 +00:00
1 parent a9299682d2
commit bd3ca2e644
2 files changed
+157 -23

No files matched your search

+77 -2
View File
@@ -3,10 +3,22 @@
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_stream
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():
@@ -40,7 +52,9 @@ def test_the_phrase_subcommand_prints_a_phrase():
with redirect_stdout(out):
assert main(["phrase"]) == 0
printed = out.getvalue().strip()
assert printed.count("-") == 4 # four words + tail
# 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():
@@ -48,3 +62,64 @@ def test_the_phrase_subcommand_can_print_several():
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