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
This commit is contained in:
HermenixandClaude Opus 5 committed 2026-09-28 05:25:37 +00:00
1 parent c0a59f5673
commit 75a05cd72f
17 files changed
+2131 -2

No files matched your search

+220
View File
@@ -0,0 +1,220 @@
"""Shared fixtures for the unit suite.
Everything here is standard library. The tests never touch a socket outside
their own `tmp_path`, never spawn a compositor, and never read the host's
configuration: the capture backend is a `python3 -c` one-liner and the server is
driven in-process.
"""
from __future__ import annotations
import os
import socket
import struct
import sys
import threading
import zlib
import pytest
CONTRACT_SOCKET = "/run/hyprland-headless-stream/stream.sock"
# AF_UNIX addresses are capped near 108 bytes; a long tmp_path would fail with a
# confusing OSError instead of the assertion the test is about.
SUN_PATH_MAX = 100
def make_png(width: int = 4, height: int = 3, value: int = 0x7F) -> bytes:
"""A minimal valid truecolour PNG, built with zlib+struct only."""
def chunk(kind: bytes, data: bytes) -> bytes:
return (
struct.pack(">I", len(data))
+ kind
+ data
+ struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
)
raw = (b"\x00" + bytes([value, value ^ 0x20, value ^ 0x40]) * width) * height
return (
b"\x89PNG\r\n\x1a\n"
+ chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0))
+ chunk(b"IDAT", zlib.compress(raw, 9))
+ chunk(b"IEND", b"")
)
@pytest.fixture
def tiny_png() -> bytes:
return make_png()
@pytest.fixture
def sock_path(tmp_path) -> str:
"""A short, unused AF_UNIX path inside the test's own directory."""
path = str(tmp_path / "s.sock")
if len(path) > SUN_PATH_MAX:
pytest.skip(f"tmp_path too long for an AF_UNIX socket: {len(path)} bytes")
return path
@pytest.fixture
def emit_bytes():
"""Build an argv that writes exactly `data` to stdout and exits 0."""
def build(data: bytes) -> list[str]:
return [
sys.executable,
"-c",
"import sys;sys.stdout.buffer.write(bytes.fromhex(sys.argv[1]))",
data.hex(),
]
return build
@pytest.fixture
def python_argv():
"""Build an argv running an inline python program with extra arguments."""
def build(program: str, *args: str) -> list[str]:
return [sys.executable, "-c", program, *args]
return build
class StubCapture:
"""A capture backend under the test's control.
Satisfies `hhstream.capture.CaptureBackend` structurally: `grab()` and
`size()`. Counts calls so a test can tell whether the server actually
captured, and can be told to raise so failure semantics are observable.
"""
def __init__(self, frames=None, size=(1280, 720), raise_first: int = 0):
self._frames = list(frames) if frames is not None else [make_png()]
self._size = size
self._raise_first = raise_first
self.grabs = 0
self.lock = threading.Lock()
def grab(self) -> bytes:
with self.lock:
self.grabs += 1
n = self.grabs
if n <= self._raise_first:
raise RuntimeError(f"stub capture failing on purpose (call {n})")
return self._frames[(n - 1) % len(self._frames)]
def size(self) -> tuple[int, int]:
return self._size
@pytest.fixture
def stub_capture():
return StubCapture
@pytest.fixture
def connect():
"""Connect to an AF_UNIX socket, retrying until the server has bound it."""
opened: list[socket.socket] = []
def _connect(path: str, timeout: float = 10.0, deadline: float = 10.0) -> socket.socket:
import time
end = time.monotonic() + deadline
last: Exception | None = None
while time.monotonic() < end:
try:
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.settimeout(timeout)
s.connect(path)
opened.append(s)
return s
except OSError as exc:
last = exc
s.close()
time.sleep(0.05)
raise AssertionError(f"never connected to {path}: {last!r}")
yield _connect
for s in opened:
try:
s.close()
except OSError:
pass
@pytest.fixture
def run_bg():
"""Run a callable on a daemon thread and surface the exception it raised.
The server's public surface has no shutdown hook (see README.dev.md), so the
thread is a daemon and the interpreter is allowed to drop it at exit.
"""
threads: list[tuple[threading.Thread, list]] = []
def _run(fn, *args, **kwargs) -> list:
box: list = []
def target():
try:
fn(*args, **kwargs)
except BaseException as exc: # recorded, re-raised by the test
box.append(exc)
t = threading.Thread(target=target, daemon=True)
t.start()
threads.append((t, box))
return box
yield _run
for t, box in threads:
t.join(timeout=0.5)
@pytest.fixture
def socket_mode():
def _mode(path: str) -> int:
return os.stat(path).st_mode & 0o7777
return _mode
@pytest.fixture(scope="session")
def rejects():
"""`pytest.raises`, but a stub does not count as a rejection.
docs/CONTRACT.md says which inputs are invalid, not which exception type
signals it, so these tests cannot pin the type. A bare
`pytest.raises(Exception)` would then be satisfied by the unimplemented
stubs' own `NotImplementedError` -- a test that is green precisely because
nothing is written yet. This refuses that one exception explicitly.
"""
import contextlib
@contextlib.contextmanager
def _rejects(*allowed: type[BaseException]):
expected = allowed or (Exception,)
try:
yield
except NotImplementedError as exc:
raise AssertionError(
"the code under test raised NotImplementedError, so it did not "
f"reject anything: {exc!r}"
) from exc
except expected:
return
except BaseException as exc:
raise AssertionError(
f"expected one of {[e.__name__ for e in expected]}, got {exc!r}"
) from exc
raise AssertionError(
f"expected one of {[e.__name__ for e in expected]}, nothing was raised"
)
return _rejects
+94
View File
@@ -0,0 +1,94 @@
"""`CommandCapture`: the injected capture backend.
docs/CONTRACT.md fixes the *shape* of this backend (a command that writes one
frame to stdout, plus the pixel size that goes into the Hello) but not the
mechanism by which the size is discovered. So these tests assert the observable
contract -- the bytes are whatever the command wrote, and `size()` agrees with
the frame `grab()` returns -- and never how the size is obtained.
"""
from __future__ import annotations
import struct
import subprocess
import sys
from hhstream.capture import CommandCapture
from conftest import make_png
def png_size(data: bytes) -> tuple[int, int]:
w, h = struct.unpack(">II", data[16:24])
return w, h
def test_grab_returns_exactly_what_the_command_wrote(emit_bytes, tiny_png):
cap = CommandCapture(emit_bytes(tiny_png))
assert cap.grab() == tiny_png
def test_grab_is_binary_safe(emit_bytes):
payload = bytes(range(256)) + b"\n\r\x00\xff"
assert CommandCapture(emit_bytes(payload)).grab() == payload
def test_grab_can_be_called_repeatedly(emit_bytes, tiny_png):
cap = CommandCapture(emit_bytes(tiny_png))
assert cap.grab() == cap.grab() == tiny_png
def test_grab_raises_when_the_command_fails(python_argv, rejects):
cap = CommandCapture(python_argv("import sys;sys.exit(3)"))
with rejects():
cap.grab()
def test_grab_raises_when_the_command_does_not_exist(tmp_path, rejects):
cap = CommandCapture([str(tmp_path / "definitely-not-a-program")])
with rejects(OSError):
cap.grab()
def test_grab_does_not_swallow_stderr_noise(python_argv, tiny_png):
"""A capture tool that warns on stderr but succeeds still yields its frame."""
cap = CommandCapture(
python_argv(
"import sys;sys.stderr.write('warning: no XDG_RUNTIME_DIR\\n');"
"sys.stdout.buffer.write(bytes.fromhex(sys.argv[1]))",
tiny_png.hex(),
)
)
assert cap.grab() == tiny_png
def test_env_is_handed_to_the_child(python_argv):
"""The compositor is reached through WAYLAND_DISPLAY/XDG_RUNTIME_DIR in env."""
cap = CommandCapture(
python_argv("import os,sys;sys.stdout.write(os.environ['WAYLAND_DISPLAY'])"),
env={"WAYLAND_DISPLAY": "wayland-9", "PATH": "/nonexistent"},
)
assert cap.grab().strip() == b"wayland-9"
def test_timeout_is_enforced(python_argv, rejects):
cap = CommandCapture(python_argv("import time;time.sleep(30)"), timeout=0.5)
with rejects(subprocess.TimeoutExpired, OSError):
cap.grab()
def test_size_reports_the_size_of_the_frame_it_captures(emit_bytes):
frame = make_png(width=640, height=360)
cap = CommandCapture(emit_bytes(frame))
assert cap.size() == png_size(cap.grab()) == (640, 360)
def test_size_is_a_pair_of_positive_ints(emit_bytes, tiny_png):
w, h = CommandCapture(emit_bytes(tiny_png)).size()
assert isinstance(w, int) and isinstance(h, int)
assert w > 0 and h > 0, "the contract forbids a Hello with zero size"
def test_size_never_reports_zero_for_a_real_frame(emit_bytes):
cap = CommandCapture(emit_bytes(make_png(width=1, height=1)))
assert cap.size() == (1, 1)
+155
View File
@@ -0,0 +1,155 @@
"""`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
+38
View File
@@ -0,0 +1,38 @@
"""The parts of the package that are plain constants, checked against the contract.
These are the only tests here that do not depend on an implementation, which
makes them the canary for the `unit` check's own wiring: if they fail, the
package is not importable from the build sandbox and nothing else means anything.
"""
from __future__ import annotations
import hhstream
from hhstream import capture, client, protocol, server
from conftest import CONTRACT_SOCKET
def test_magic_matches_the_contract():
# docs/CONTRACT.md: {"magic":"HHS1", ...}
assert hhstream.MAGIC == "HHS1"
assert protocol.MAGIC == "HHS1"
def test_default_socket_path_matches_the_contract():
assert server.DEFAULT_SOCKET == CONTRACT_SOCKET
assert client.DEFAULT_SOCKET == CONTRACT_SOCKET
def test_public_surface_is_present():
for name in ("hello", "parse_hello", "frame", "read_frame", "read_hello"):
assert callable(getattr(protocol, name)), f"protocol.{name}"
assert callable(client.fetch)
assert callable(client.main)
assert callable(server.main)
assert isinstance(server.FrameServer, type)
assert isinstance(capture.CommandCapture, type)
def test_version_is_the_packaged_version():
assert hhstream.__version__ == "0.1.0"
+169
View File
@@ -0,0 +1,169 @@
"""Framing, byte for byte, against docs/CONTRACT.md.
The contract is unusually specific about the length prefix ("plain ASCII digits;
no leading zeros, no `+`, no spaces"), so these tests assert on exact bytes
rather than on round-trips alone -- a reader and writer that agree with each
other but not with the document would pass a round-trip test.
"""
from __future__ import annotations
import io
import json
import pytest
from hhstream import protocol
# -- Hello ----------------------------------------------------------------
def test_hello_is_one_json_line():
line = protocol.hello(1280, 720, "image/png", 30)
assert isinstance(line, bytes)
assert line.endswith(b"\n")
assert line.count(b"\n") == 1, "the Hello is exactly one line"
def test_hello_fields_match_the_contract():
obj = json.loads(protocol.hello(1280, 720, "image/png", 30).decode("utf-8"))
assert obj["magic"] == "HHS1"
assert obj["width"] == 1280
assert obj["height"] == 720
assert obj["format"] == "image/png"
assert obj["fps"] == 30
def test_hello_carries_the_jpeg_format_too():
obj = json.loads(protocol.hello(640, 480, "image/jpeg", 15).decode("utf-8"))
assert obj["format"] == "image/jpeg"
def test_hello_round_trips_through_parse_hello():
obj = protocol.parse_hello(protocol.hello(1920, 1080, "image/png", 60))
assert obj["magic"] == "HHS1"
assert (obj["width"], obj["height"]) == (1920, 1080)
assert obj["fps"] == 60
def test_parse_hello_tolerates_the_trailing_newline_or_not():
line = protocol.hello(800, 600, "image/png", 24)
assert protocol.parse_hello(line) == protocol.parse_hello(line.rstrip(b"\n"))
def test_parse_hello_rejects_a_foreign_magic(rejects):
bad = json.dumps(
{"magic": "HHS0", "width": 1, "height": 1, "format": "image/png", "fps": 1}
).encode()
with rejects():
protocol.parse_hello(bad)
@pytest.mark.parametrize("missing", ["width", "height", "format", "fps"])
def test_parse_hello_rejects_a_missing_field(missing, rejects):
obj = {
"magic": "HHS1",
"width": 1280,
"height": 720,
"format": "image/png",
"fps": 30,
}
del obj[missing]
with rejects():
protocol.parse_hello(json.dumps(obj).encode())
@pytest.mark.parametrize("junk", [b"", b"not json", b"[]", b"null", b'{"magic":"HHS1"'])
def test_parse_hello_rejects_junk(junk, rejects):
with rejects():
protocol.parse_hello(junk)
# -- frames ---------------------------------------------------------------
def test_frame_prefixes_the_payload_length_in_ascii():
assert protocol.frame(b"hello") == b"5\n" + b"hello"
def test_frame_length_counts_the_payload_only():
payload = b"\x00" * 1234
framed = protocol.frame(payload)
prefix, _, body = framed.partition(b"\n")
assert prefix == b"1234"
assert int(prefix) == len(payload) == len(body)
def test_frame_length_has_no_leading_zeros_sign_or_spaces():
for n in (1, 7, 10, 99, 100, 65536):
prefix = protocol.frame(b"x" * n).split(b"\n", 1)[0]
assert prefix == str(n).encode()
assert not prefix.startswith(b"0")
assert not prefix.startswith(b"+")
assert b" " not in prefix
def test_frame_is_binary_safe():
payload = bytes(range(256)) + b"\n42\n" + b"\xff\xfe"
framed = protocol.frame(payload)
assert framed == str(len(payload)).encode() + b"\n" + payload
def test_read_frame_round_trips():
payload = bytes(range(256)) * 8
assert protocol.read_frame(io.BytesIO(protocol.frame(payload))) == payload
def test_read_frame_reads_exactly_one_frame_and_stops():
stream = io.BytesIO(protocol.frame(b"aaa") + protocol.frame(b"bbbb"))
assert protocol.read_frame(stream) == b"aaa"
assert protocol.read_frame(stream) == b"bbbb"
assert protocol.read_frame(stream) is None
def test_read_frame_returns_none_on_a_clean_eof():
assert protocol.read_frame(io.BytesIO(b"")) is None
def test_read_frame_raises_on_a_truncated_payload(rejects):
with rejects(EOFError):
protocol.read_frame(io.BytesIO(b"10\nshort"))
@pytest.mark.parametrize(
"bad",
[
b"007\n0000000", # leading zeros
b"+5\nhello", # sign
b" 5\nhello", # leading space
b"5 \nhello", # trailing space
b"abc\nhello", # not a number
b"-1\n", # negative
b"1_0\nxxxxxxxxxx", # python's int() accepts this; the contract does not
],
)
def test_read_frame_rejects_a_malformed_length_prefix(bad, rejects):
with rejects(ValueError):
protocol.read_frame(io.BytesIO(bad))
def test_read_frame_handles_a_megabyte_payload():
payload = bytes(range(256)) * 4096
assert len(payload) == 1024 * 1024
assert protocol.read_frame(io.BytesIO(protocol.frame(payload))) == payload
def test_read_hello_then_frames_is_the_contract_sequence():
wire = (
protocol.hello(1280, 720, "image/png", 30)
+ protocol.frame(b"one")
+ protocol.frame(b"two")
)
stream = io.BytesIO(wire)
hello = protocol.read_hello(stream)
assert hello["magic"] == "HHS1"
assert (hello["width"], hello["height"]) == (1280, 720)
assert protocol.read_frame(stream) == b"one"
assert protocol.read_frame(stream) == b"two"
assert protocol.read_frame(stream) is None
+202
View File
@@ -0,0 +1,202 @@
"""`FrameServer` against a real (temporary) socket.
These drive the server in-process on a daemon thread and talk to it over an
AF_UNIX socket inside `tmp_path`. Nothing here touches the host: no compositor,
no /run, no network. The reader is `hhstream.protocol`, which its own tests pin
to the document.
"""
from __future__ import annotations
import os
import socket
import time
import pytest
from hhstream import protocol
from hhstream.server import FrameServer
from conftest import make_png
def wait_for_socket(path: str, deadline: float = 10.0) -> None:
end = time.monotonic() + deadline
while time.monotonic() < end:
if os.path.exists(path):
return
time.sleep(0.02)
raise AssertionError(f"server never bound {path}")
def read_stream(sock: socket.socket):
"""A file object over the socket, for protocol.read_* to consume."""
return sock.makefile("rb")
def test_serves_the_hello_then_frames(sock_path, stub_capture, run_bg, connect):
cap = stub_capture(frames=[make_png(width=64, height=32)], size=(64, 32))
box = run_bg(FrameServer(sock_path, cap, fps=30).serve_forever)
wait_for_socket(sock_path)
with read_stream(connect(sock_path)) as stream:
hello = protocol.read_hello(stream)
assert hello["magic"] == "HHS1"
assert (hello["width"], hello["height"]) == (64, 32)
assert hello["format"] == "image/png"
assert hello["fps"] == 30
first = protocol.read_frame(stream)
second = protocol.read_frame(stream)
assert not box, f"server thread died: {box}"
assert first and second
assert len(first) > 0 and len(second) > 0
def test_hello_format_follows_the_constructor(sock_path, stub_capture, run_bg, connect):
cap = stub_capture()
run_bg(FrameServer(sock_path, cap, fps=15, fmt="image/jpeg").serve_forever)
wait_for_socket(sock_path)
with read_stream(connect(sock_path)) as stream:
hello = protocol.read_hello(stream)
assert hello["format"] == "image/jpeg"
assert hello["fps"] == 15
def test_socket_mode_is_0660(sock_path, stub_capture, run_bg):
# docs/CONTRACT.md -> Socket: "mode 0660".
run_bg(FrameServer(sock_path, stub_capture(), fps=30).serve_forever)
wait_for_socket(sock_path)
assert os.stat(sock_path).st_mode & 0o777 == 0o660
def test_a_stale_socket_file_does_not_prevent_startup(sock_path, stub_capture, run_bg, connect):
# docs/CONTRACT.md: "The socket path is removed and recreated on start."
with open(sock_path, "wb") as fh:
fh.write(b"leftover from a crashed run")
run_bg(FrameServer(sock_path, stub_capture(), fps=30).serve_forever)
wait_for_socket(sock_path)
with read_stream(connect(sock_path)) as stream:
assert protocol.read_hello(stream)["magic"] == "HHS1"
def test_every_client_gets_its_own_hello_and_frames(sock_path, stub_capture, run_bg, connect):
# docs/CONTRACT.md: "Each client gets its own copy of the header and of
# every subsequent frame."
run_bg(FrameServer(sock_path, stub_capture(size=(128, 96)), fps=30).serve_forever)
wait_for_socket(sock_path)
streams = [read_stream(connect(sock_path)) for _ in range(3)]
try:
for stream in streams:
hello = protocol.read_hello(stream)
assert (hello["width"], hello["height"]) == (128, 96)
assert len(protocol.read_frame(stream)) > 0
finally:
for stream in streams:
stream.close()
def test_a_client_disconnecting_does_not_take_the_server_down(
sock_path, stub_capture, run_bg, connect
):
# docs/CONTRACT.md: "A client disconnecting (or dying mid-frame) must never
# take the server down and must never disturb the other clients."
box = run_bg(FrameServer(sock_path, stub_capture(), fps=30).serve_forever)
wait_for_socket(sock_path)
survivor = read_stream(connect(sock_path))
assert protocol.read_hello(survivor)["magic"] == "HHS1"
for _ in range(3):
doomed = connect(sock_path)
doomed.recv(1) # take one byte of the Hello, then die mid-message
doomed.close()
assert len(protocol.read_frame(survivor)) > 0
survivor.close()
with read_stream(connect(sock_path)) as latecomer:
assert protocol.read_hello(latecomer)["magic"] == "HHS1"
assert not box, f"server thread died: {box}"
def test_a_stalled_client_does_not_stall_the_others(sock_path, stub_capture, run_bg, connect):
# docs/CONTRACT.md: "A client that stalls or reads slowly is *slowed*, not
# queued" -- observably, it must not hold up anybody else.
run_bg(FrameServer(sock_path, stub_capture(), fps=30).serve_forever)
wait_for_socket(sock_path)
stalled = connect(sock_path) # connects and never reads
with read_stream(connect(sock_path)) as stream:
assert protocol.read_hello(stream)["magic"] == "HHS1"
for _ in range(5):
assert len(protocol.read_frame(stream)) > 0
stalled.close()
def test_bytes_sent_by_a_client_are_read_and_ignored(sock_path, stub_capture, run_bg, connect):
# docs/CONTRACT.md -> "Client -> server direction": reserved in v1.
box = run_bg(FrameServer(sock_path, stub_capture(), fps=30).serve_forever)
wait_for_socket(sock_path)
sock = connect(sock_path)
sock.sendall(b"a future control channel says hello\n" * 64)
with read_stream(sock) as stream:
assert protocol.read_hello(stream)["magic"] == "HHS1"
assert len(protocol.read_frame(stream)) > 0
assert not box, f"server thread died: {box}"
def test_a_failing_capture_does_not_kill_the_server(sock_path, stub_capture, run_bg, connect):
# docs/CONTRACT.md -> Failure semantics: "the server keeps the socket up and
# retries; it does not exit and it does not send partial frames."
cap = stub_capture(raise_first=3)
box = run_bg(FrameServer(sock_path, cap, fps=30).serve_forever)
wait_for_socket(sock_path)
with read_stream(connect(sock_path)) as stream:
assert protocol.read_hello(stream)["magic"] == "HHS1"
payload = protocol.read_frame(stream)
assert payload and payload.startswith(b"\x89PNG"), "no partial frame was sent"
assert cap.grabs > 3, "the server never retried after the capture failed"
assert not box, f"server thread died: {box}"
def test_never_announces_a_zero_size_hello(sock_path, stub_capture, run_bg, connect):
# docs/CONTRACT.md -> Failure semantics: "It never sends a Hello with zero
# size." The size only becomes known after the first successful capture.
cap = stub_capture(size=(0, 0))
cap_sizes = [(0, 0), (0, 0), (1280, 720)]
calls = {"n": 0}
def size():
n = calls["n"]
calls["n"] = min(n + 1, len(cap_sizes) - 1)
return cap_sizes[n]
cap.size = size
run_bg(FrameServer(sock_path, cap, fps=30).serve_forever)
wait_for_socket(sock_path)
with read_stream(connect(sock_path)) as stream:
hello = protocol.read_hello(stream)
assert hello["width"] > 0 and hello["height"] > 0
def test_build_parser_exposes_the_options_the_module_needs():
from hhstream import server
parser = server.build_parser()
args = parser.parse_args(
["--socket", "/run/x.sock", "--fps", "24", "--format", "png", "--", "grim", "-t", "png", "-"]
)
assert args.socket == "/run/x.sock"
assert args.fps == 24
def test_main_rejects_an_unknown_flag():
from hhstream import server
with pytest.raises(SystemExit):
server.main(["--definitely-not-a-flag"])