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
148 lines
5.5 KiB
Python
148 lines
5.5 KiB
Python
"""The client, against the real server and against a hand-written stub server."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import contextlib
|
|
import json
|
|
import socket
|
|
import threading
|
|
|
|
import pytest
|
|
from helpers import FakeCapture, connect, distinct_frames
|
|
|
|
from hhstream import client, protocol
|
|
|
|
|
|
@contextlib.contextmanager
|
|
def stub_server(path: str, payload: bytes):
|
|
"""A server that writes exactly `payload` to one client, then hangs up."""
|
|
listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
listener.bind(path)
|
|
listener.listen(1)
|
|
|
|
def run():
|
|
try:
|
|
conn, _ = listener.accept()
|
|
except OSError:
|
|
return
|
|
with conn:
|
|
try:
|
|
conn.sendall(payload)
|
|
except OSError:
|
|
pass
|
|
|
|
thread = threading.Thread(target=run, daemon=True)
|
|
thread.start()
|
|
try:
|
|
yield
|
|
finally:
|
|
listener.close()
|
|
thread.join(5)
|
|
|
|
|
|
def test_fetch_returns_the_payloads(sock_path, serve):
|
|
frames = distinct_frames(30)
|
|
with serve(sock_path, FakeCapture(frames=frames), fps=50):
|
|
got = client.fetch(sock_path, count=3, timeout=5)
|
|
assert len(got) == 3
|
|
assert all(payload in frames for payload in got)
|
|
|
|
|
|
def test_read_stream_also_returns_the_hello(sock_path, serve):
|
|
with serve(sock_path, FakeCapture(frames=distinct_frames(5)), fps=25):
|
|
hello, frames = client.read_stream(sock_path, count=1, timeout=5)
|
|
assert hello == {"magic": "HHS1", "width": 1280, "height": 720,
|
|
"format": "image/png", "fps": 25}
|
|
assert len(frames) == 1
|
|
|
|
|
|
def test_fetch_returns_fewer_frames_when_the_server_hangs_up(sock_path):
|
|
wire = protocol.hello(4, 2, "image/png", 1) + protocol.frame(b"only one")
|
|
with stub_server(sock_path, wire):
|
|
assert client.fetch(sock_path, count=5, timeout=5) == [b"only one"]
|
|
|
|
|
|
def test_fetch_on_a_missing_socket_raises_oserror(sock_path):
|
|
with pytest.raises(OSError):
|
|
client.fetch(sock_path, count=1, timeout=1)
|
|
|
|
|
|
def test_fetch_rejects_a_bad_hello(sock_path):
|
|
with stub_server(sock_path, b'{"magic":"NOPE"}\n'):
|
|
with pytest.raises(ValueError):
|
|
client.fetch(sock_path, count=1, timeout=5)
|
|
|
|
|
|
def test_fetch_rejects_a_truncated_frame(sock_path):
|
|
wire = protocol.hello(4, 2, "image/png", 1) + b"100\nshort"
|
|
with stub_server(sock_path, wire):
|
|
with pytest.raises(EOFError):
|
|
client.fetch(sock_path, count=1, timeout=5)
|
|
|
|
|
|
# -- the CLI -------------------------------------------------------------
|
|
|
|
def test_main_prints_the_hello_and_writes_one_frame(sock_path, serve, workdir, capsys):
|
|
frames = distinct_frames(5)
|
|
with serve(sock_path, FakeCapture(frames=frames), fps=25):
|
|
out = workdir / "frame.png"
|
|
assert client.main(["--socket", sock_path, "--count", "1",
|
|
"--out", str(out), "--timeout", "5"]) == 0
|
|
printed = capsys.readouterr().out.splitlines()
|
|
assert json.loads(printed[0])["magic"] == "HHS1"
|
|
assert f"-> {out}" in printed[1]
|
|
assert out.read_bytes() in frames
|
|
|
|
|
|
def test_main_suffixes_the_output_when_count_is_more_than_one(sock_path, serve,
|
|
workdir, capsys):
|
|
with serve(sock_path, FakeCapture(frames=distinct_frames(20)), fps=50):
|
|
assert client.main(["--socket", sock_path, "--count", "2",
|
|
"--out", str(workdir / "shot.png"), "--timeout", "5"]) == 0
|
|
assert (workdir / "shot-1.png").exists()
|
|
assert (workdir / "shot-2.png").exists()
|
|
assert not (workdir / "shot.png").exists()
|
|
assert len(capsys.readouterr().out.splitlines()) == 3 # hello + two frames
|
|
|
|
|
|
def test_main_writes_payloads_to_stdout_with_out_dash(sock_path, serve, capsysbinary):
|
|
frame = distinct_frames(1)[0]
|
|
with serve(sock_path, FakeCapture(frames=[frame]), fps=25):
|
|
assert client.main(["--socket", sock_path, "--count", "2", "--out", "-",
|
|
"--timeout", "5"]) == 0
|
|
captured = capsysbinary.readouterr()
|
|
assert captured.out == frame * 2, "payloads must be the only thing on stdout"
|
|
assert b'"magic":"HHS1"' in captured.err
|
|
|
|
|
|
def test_main_reports_a_missing_socket_without_a_traceback(sock_path, capsys):
|
|
assert client.main(["--socket", sock_path, "--timeout", "1"]) == 1
|
|
assert "hhstream-client:" in capsys.readouterr().err
|
|
|
|
|
|
def test_main_reports_a_short_stream(sock_path, capsys):
|
|
wire = protocol.hello(4, 2, "image/png", 1) + protocol.frame(b"one")
|
|
with stub_server(sock_path, wire):
|
|
assert client.main(["--socket", sock_path, "--count", "3",
|
|
"--timeout", "5"]) == 1
|
|
assert "wanted 3 frames, got 1" in capsys.readouterr().err
|
|
|
|
|
|
def test_main_rejects_a_negative_count(sock_path, capsys):
|
|
assert client.main(["--socket", sock_path, "--count", "-1"]) == 2
|
|
assert "--count" in capsys.readouterr().err
|
|
|
|
|
|
def test_default_socket_matches_the_contract():
|
|
assert client.DEFAULT_SOCKET == "/run/hyprland-headless-stream/stream.sock"
|
|
assert client.build_parser().parse_args([]).socket == client.DEFAULT_SOCKET
|
|
|
|
|
|
def test_a_client_can_be_interrupted_without_disturbing_the_server(sock_path, serve):
|
|
"""Two sequential fetches: the first client's exit leaves the socket usable."""
|
|
with serve(sock_path, FakeCapture(frames=distinct_frames(40)), fps=50):
|
|
assert len(client.fetch(sock_path, count=2, timeout=5)) == 2
|
|
conn = connect(sock_path)
|
|
conn.close() # leave mid-stream
|
|
assert len(client.fetch(sock_path, count=2, timeout=5)) == 2
|