Files
hapi/tests/test_serve.py
T
BobbyandClaude Opus 5.5 2beb581c6d new: project skeleton with a live probe (#74)
uv project on Python 3.14 with Ruff (incl. DTZ), pyright strict, and
import-linter contracts: composition root above domains above platform,
each domain reachable from others only through its `service` module, and
`bots/` forbidden from importing `hapi`. `just dev/test/lint` recipes and
pre-commit running the same checks plus gitleaks. `just` and `pre-commit`
are dev dependencies, so uv is the only tool needed outside the venv.

`hapi serve` runs the public API (:8000) and the internal probe listener
(:8081) as two uvicorn servers in one event loop (ADR-0009); `/livez` is
constant and served only on :8081.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 16:56:02 -05:00

79 lines
2.1 KiB
Python

"""`hapi serve` runs the public API and the internal probe listener in one process.
Unlike other CLI tests, these run `hapi serve` as a real subprocess: binding real
ports and receiving SIGTERM are the behaviour under test.
"""
import signal
import socket
import subprocess
import sys
import time
from collections.abc import Iterator
from typing import NamedTuple
import httpx
import pytest
def _free_port() -> int:
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
return sock.getsockname()[1]
def _wait_until_listening(url: str, process: subprocess.Popen[bytes]) -> None:
deadline = time.monotonic() + 10
while time.monotonic() < deadline:
if process.poll() is not None:
pytest.fail(f"hapi serve exited early with {process.returncode}")
try:
httpx.get(url, timeout=0.5)
except httpx.TransportError:
time.sleep(0.05)
else:
return
pytest.fail(f"nothing listening at {url}")
class Served(NamedTuple):
process: subprocess.Popen[bytes]
api_port: int
probe_port: int
@pytest.fixture
def served() -> Iterator[Served]:
api_port, probe_port = _free_port(), _free_port()
process = subprocess.Popen(
[
sys.executable,
"-m",
"hapi",
"serve",
"--api-port",
str(api_port),
"--probe-port",
str(probe_port),
],
)
try:
_wait_until_listening(f"http://127.0.0.1:{api_port}/", process)
_wait_until_listening(f"http://127.0.0.1:{probe_port}/", process)
yield Served(process, api_port, probe_port)
finally:
if process.poll() is None:
process.kill()
process.wait()
def test_probes_answer_on_the_probe_port_only(served: Served) -> None:
assert httpx.get(f"http://127.0.0.1:{served.probe_port}/livez").status_code == 200
assert httpx.get(f"http://127.0.0.1:{served.api_port}/livez").status_code == 404
def test_sigterm_stops_both_listeners_cleanly(served: Served) -> None:
served.process.send_signal(signal.SIGTERM)
assert served.process.wait(timeout=10) == 0