Files
hyprland-headless-stream-pl…/tests/unit/test_protocol.py
HermenixandClaude Opus 5 4af6f7072a server, client: implement the v1 frame protocol end to end
Fill in the bodies the skeleton left as NotImplementedError, to docs/CONTRACT.md:

- protocol: the `\n`-terminated JSON Hello and the `<ascii length>\n<payload>`
  frame, both directions. Malformed input raises (ValueError for a bad length
  prefix, EOFError for a truncated payload), never hangs on endless garbage and
  never silently truncates; a huge length prefix is not pre-allocated.
- capture: CommandCapture runs the configured command and reports a missing
  binary, a non-zero exit, a timeout and empty output as CaptureError, with the
  helper's stderr folded into the message so nothing leaks to the server's own
  stdio. The Hello's pixel size is read from the frame's PNG/JPEG header, so no
  compositor query is needed and an injected fake command behaves the same.
- server: one capture thread holding only the newest frame plus one thread per
  client, which is what drops frames for a slow client instead of queueing
  them. Survives a client dying mid-write, keeps the socket up across capture
  failures, withholds the Hello until a size is known, replaces a stale socket
  file (but never a non-socket one) and publishes it mode 0660.
- client: fetch()/read_stream() and the CLI, with --out suffixing per frame.

--capture-command folds its separated form into `--flag=value` before argparse
sees it, so the contract's default `grim -t png -` can actually be passed: its
tokens start with a dash.

Unit tests under tests/unit cover framing round-trips (including a payload
containing `\n` and a zero-length frame), truncated and garbage prefixes, a
stalled client not blocking a second one, a client dying mid-frame, frames being
dropped rather than queued, and every capture failure mode. A fake capture
command stands in for grim, so nothing needs a compositor or a GPU. They are
deliberately not wired into flake.nix: `checks` belongs to another workstream.

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

187 lines
6.2 KiB
Python

"""The framing. Other people's clients depend on these bytes being exact."""
from __future__ import annotations
import io
import json
import pytest
from hhstream import MAGIC, protocol
# -- Hello ---------------------------------------------------------------
def test_hello_matches_the_contract_byte_for_byte():
assert protocol.hello(1280, 720, "image/png", 30) == (
b'{"magic":"HHS1","width":1280,"height":720,"format":"image/png","fps":30}\n'
)
def test_hello_round_trip():
line = protocol.hello(640, 480, "image/jpeg", 15)
assert line.endswith(b"\n") and line.count(b"\n") == 1
assert protocol.parse_hello(line) == {
"magic": MAGIC, "width": 640, "height": 480,
"format": "image/jpeg", "fps": 15,
}
def test_parse_hello_tolerates_a_missing_trailing_newline():
line = protocol.hello(8, 8, "image/png", 1)
assert protocol.parse_hello(line.rstrip(b"\n")) == protocol.parse_hello(line)
@pytest.mark.parametrize("width,height,fps", [(0, 720, 30), (1280, 0, 30),
(1280, 720, 0), (-1, 720, 30)])
def test_hello_refuses_a_zero_or_negative_size(width, height, fps):
with pytest.raises(ValueError):
protocol.hello(width, height, "image/png", fps)
@pytest.mark.parametrize("payload", [
b"",
b"not json at all",
b"[1,2,3]",
b'"a string"',
b'{"magic":"HHS0","width":1,"height":1,"format":"image/png","fps":1}',
b'{"width":1,"height":1,"format":"image/png","fps":1}',
b'{"magic":"HHS1","height":1,"format":"image/png","fps":1}',
b'{"magic":"HHS1","width":1,"height":1,"fps":1}',
b'{"magic":"HHS1","width":1,"height":1,"format":"image/png"}',
b'{"magic":"HHS1","width":0,"height":1,"format":"image/png","fps":1}',
b'{"magic":"HHS1","width":"1","height":1,"format":"image/png","fps":1}',
b'{"magic":"HHS1","width":true,"height":1,"format":"image/png","fps":1}',
b'{"magic":"HHS1","width":1,"height":1,"format":"","fps":1}',
b'{"magic":"HHS1","width":1,"height":1,"format":"image/png","fps":1}\xff',
])
def test_parse_hello_rejects_bad_input(payload):
with pytest.raises(ValueError):
protocol.parse_hello(payload)
def test_read_hello_then_frames_from_one_stream():
stream = io.BytesIO(
protocol.hello(2, 2, "image/png", 5) + protocol.frame(b"one") + protocol.frame(b"two")
)
assert protocol.read_hello(stream)["width"] == 2
assert protocol.read_frame(stream) == b"one"
assert protocol.read_frame(stream) == b"two"
assert protocol.read_frame(stream) is None
def test_read_hello_on_a_truncated_line():
with pytest.raises(EOFError):
protocol.read_hello(io.BytesIO(b'{"magic":"HHS1"'))
def test_read_hello_gives_up_on_an_endless_line():
with pytest.raises(ValueError):
protocol.read_hello(_Endless(b"x"))
# -- frames --------------------------------------------------------------
@pytest.mark.parametrize("payload", [
b"",
b"\n",
b"a\nb",
b"\n\n\n",
b"12\n34", # payload that looks like a frame itself
b"\x89PNG\r\n\x1a\n",
bytes(range(256)),
b"x" * (1 << 20),
])
def test_frame_round_trip(payload):
wire = protocol.frame(payload)
assert wire.startswith(str(len(payload)).encode("ascii") + b"\n")
assert len(wire) == len(payload) + len(str(len(payload))) + 1
assert protocol.read_frame(io.BytesIO(wire)) == payload
def test_zero_length_frame_is_a_frame_not_an_eof():
stream = io.BytesIO(protocol.frame(b"") + protocol.frame(b"after"))
assert protocol.frame(b"") == b"0\n"
assert protocol.read_frame(stream) == b""
assert protocol.read_frame(stream) == b"after"
def test_payload_containing_newlines_is_not_resplit():
payload = b"row1\nrow2\n" * 500
stream = io.BytesIO(protocol.frame(payload) + protocol.frame(b"next"))
assert protocol.read_frame(stream) == payload
assert protocol.read_frame(stream) == b"next"
def test_length_prefix_has_no_leading_zeros_and_no_sign():
assert protocol.frame(b"abc") == b"3\nabc"
assert not protocol.frame(b"x" * 10).startswith(b"+")
def test_read_frame_stops_exactly_at_the_end_of_the_payload():
stream = io.BytesIO(protocol.frame(b"abc") + b"LEFTOVER")
assert protocol.read_frame(stream) == b"abc"
assert stream.read() == b"LEFTOVER"
def test_clean_eof_between_frames_is_none():
assert protocol.read_frame(io.BytesIO(b"")) is None
@pytest.mark.parametrize("wire", [
b"\nabc", # empty length prefix
b"007\nabcdefg", # leading zero
b"0012\n", # leading zeros
b"12x\nabc", # not a digit
b" 3\nabc", # leading space
b"+3\nabc", # sign
b"-3\nabc", # negative
b"3.0\nabc", # not an integer
b"1" * 21 + b"\n", # absurdly long prefix
])
def test_garbage_length_prefix_raises_value_error(wire):
with pytest.raises(ValueError):
protocol.read_frame(io.BytesIO(wire))
@pytest.mark.parametrize("wire", [
b"5\nabc", # payload short
b"5\n", # payload absent
b"1048576\n" + b"x" * 1000,
b"12", # EOF inside the length prefix
])
def test_truncated_payload_raises_eof_error(wire):
with pytest.raises(EOFError):
protocol.read_frame(io.BytesIO(wire))
def test_read_frame_gives_up_on_endless_digits_instead_of_hanging():
with pytest.raises(ValueError):
protocol.read_frame(_Endless(b"1"))
def test_a_huge_length_prefix_does_not_preallocate():
# 10**19 bytes is not going to arrive; we must notice the EOF, not the RAM.
with pytest.raises(EOFError):
protocol.read_frame(io.BytesIO(b"9999999999999999999\nshort"))
def test_frame_rejects_non_bytes():
with pytest.raises(ValueError):
protocol.frame("a str is not bytes") # type: ignore[arg-type]
def test_hello_is_valid_json_with_the_documented_field_order():
line = protocol.hello(1280, 720, "image/png", 30).decode("utf-8")
assert list(json.loads(line)) == ["magic", "width", "height", "format", "fps"]
class _Endless:
"""A stream that never ends and never blocks -- proves we bail out."""
def __init__(self, byte: bytes):
self.byte = byte
def read(self, size: int = -1) -> bytes:
return self.byte * (1 if size in (-1, None) else size)