"""`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)