Files
hyprland-headless-stream-pl…/tests/unit/test_client.py
T
HermenixandClaude Opus 5 75a05cd72f tests: checks.{unit,vm-basic,vm-hyprland} + the harness behind them
Wires a `checks` output into the flake, one file per check under checks/,
all three asserting docs/CONTRACT.md rather than the implementation:

- unit: pytest over tests/unit/ in the build sandbox, against the
  nix/package.nix build. Refuses an empty suite -- pytest exits 0 when
  every test was skipped or deselected, so checks/lib/check_report.py
  parses the JUnit report and fails on zero collected or zero executed.
- vm-basic: nixosTest with captureCommand pointed at tests/fake_capture.py,
  which emits one fixed deterministic PNG. Because the image never changes,
  "two frames arrived and they are the same bytes" is an assertion about
  the framing rather than a coincidence.
- vm-hyprland: the same machine with no captureCommand override, so grim
  captures the real compositor. Deliberately impatient -- bounded timeouts,
  no retry loops, and a full diagnostics dump (compositor log, hyprctl
  monitors, both journals) before any failure propagates.

tests/assert_stream.py is a second, independent reader of the contract: it
shares no code with hhstream.client, so a framing bug present in both the
server's writer and the shipped client's reader still fails. The unit
suite's negative tests use a `rejects` fixture instead of
pytest.raises(Exception), which an unimplemented stub's
NotImplementedError would otherwise satisfy.

Three defects found in code this branch does not own, recorded in
README.dev.md rather than worked around:
- nix/module.nix has no config side, so neither unit exists and both VM
  checks fail at their first wait;
- services.hyprland-headless-stream.package is declared with no default,
  against docs/CONTRACT.md;
- src/hhstream/*.py is all stubs, so 66 of 70 unit tests fail.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017YXMoCNxzScTaKNr43GQNz
2026-09-28 05:25:37 +00:00

156 lines
4.8 KiB
Python

"""`hhstream.client` read against a hand-written, contract-conformant server.
The stand-in server is written straight from docs/CONTRACT.md rather than with
`hhstream.protocol`, so `fetch` is measured against the document instead of
against its own framing helpers.
"""
from __future__ import annotations
import json
import os
import socket
import threading
import pytest
from hhstream import client
from conftest import make_png
class ContractServer:
"""Writes the Hello and `frames` exactly as docs/CONTRACT.md specifies."""
def __init__(self, path: str, frames, width=1280, height=720, fps=30,
fmt="image/png", send_hello=True, hang=False):
self.path = path
self.frames = list(frames)
self.meta = dict(magic="HHS1", width=width, height=height, format=fmt, fps=fps)
self.send_hello = send_hello
self.hang = hang
self.connections = 0
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
if os.path.exists(path):
os.unlink(path)
self.sock.bind(path)
os.chmod(path, 0o660)
self.sock.listen(8)
self._stop = threading.Event()
self._thread = threading.Thread(target=self._serve, daemon=True)
self._thread.start()
def _serve(self):
while not self._stop.is_set():
try:
conn, _ = self.sock.accept()
except OSError:
return
self.connections += 1
threading.Thread(target=self._handle, args=(conn,), daemon=True).start()
def _handle(self, conn):
try:
if self.hang:
self._stop.wait(30)
return
if self.send_hello:
conn.sendall(json.dumps(self.meta).encode("utf-8") + b"\n")
for payload in self.frames:
conn.sendall(str(len(payload)).encode("ascii") + b"\n" + payload)
self._stop.wait(5)
except OSError:
pass
finally:
conn.close()
def close(self):
self._stop.set()
self.sock.close()
@pytest.fixture
def contract_server(sock_path):
made = []
def build(frames, **kw):
srv = ContractServer(sock_path, frames, **kw)
made.append(srv)
return srv
yield build
for srv in made:
srv.close()
def test_fetch_returns_one_payload_by_default(contract_server, sock_path):
frame = make_png(width=32, height=16)
contract_server([frame] * 4)
assert client.fetch(sock_path) == [frame]
def test_fetch_consumes_the_hello_and_returns_only_payloads(contract_server, sock_path):
frames = [make_png(value=v) for v in (0x11, 0x22, 0x33)]
contract_server(frames)
got = client.fetch(sock_path, count=3)
assert got == frames
assert not any(b"HHS1" in payload for payload in got)
def test_fetch_stops_at_count(contract_server, sock_path):
contract_server([make_png()] * 10)
assert len(client.fetch(sock_path, count=2)) == 2
def test_fetch_handles_a_payload_with_a_newline_in_it(contract_server, sock_path):
payload = b"12\n" + bytes(range(256))
contract_server([payload, payload])
assert client.fetch(sock_path, count=2) == [payload, payload]
def test_fetch_raises_when_the_socket_does_not_exist(tmp_path, rejects):
with rejects(OSError):
client.fetch(str(tmp_path / "absent.sock"))
def test_fetch_times_out_on_a_silent_server(contract_server, sock_path, rejects):
contract_server([], hang=True)
with rejects(OSError, EOFError, TimeoutError):
client.fetch(sock_path, count=1, timeout=1.0)
def test_fetch_does_not_hang_when_the_server_hangs_up_early(
contract_server, sock_path, rejects
):
contract_server([make_png()])
with rejects(OSError, EOFError, TimeoutError):
client.fetch(sock_path, count=5, timeout=2.0)
def test_build_parser_matches_the_documented_invocation():
# README.md: hhstream-client --socket <path> --count 1 --out frame.png
parser = client.build_parser()
args = parser.parse_args(["--socket", "/run/x.sock", "--count", "1", "--out", "frame.png"])
assert args.socket == "/run/x.sock"
assert args.count == 1
assert args.out == "frame.png"
def test_parser_defaults_to_the_contract_socket():
args = client.build_parser().parse_args([])
assert args.socket == client.DEFAULT_SOCKET == "/run/hyprland-headless-stream/stream.sock"
def test_main_writes_the_frame_it_read(contract_server, sock_path, tmp_path):
frame = make_png(width=8, height=8)
contract_server([frame])
out = tmp_path / "frame.png"
rc = client.main(["--socket", sock_path, "--count", "1", "--out", str(out)])
assert rc == 0
assert out.read_bytes() == frame
def test_main_reports_failure_without_a_traceback(tmp_path):
rc = client.main(["--socket", str(tmp_path / "absent.sock"), "--count", "1"])
assert rc != 0