Files
Hermenix e8b3855a05 move every live default to /run/hypr-stream, and resolve the slices' contract gaps
Slice A renamed the runtime directory in the module, but the old path was still
live in the code and checks it does not own, so the VM gates pointed at a
directory the module no longer creates. This moves the 21 remaining live
occurrences (client/server defaults, the unit tests that pin them, all three VM
checks, the diagnostics script, both READMEs) and deliberately leaves the three
mentions that are history rather than configuration: the plan's problem
statement, module.nix's note about the previous name, and cli.py's explanation
for spelling its default out.

Also here: docs/CONTRACT-sessions.md is now v2 with every gap the four slices
reported resolved as a decision (Monitor.id, stable_id, pid -1, Event.data,
mark(), the quarantine argv type, the corrected wlr XML path, and the state
dir/frame socket rows), and docs/CONTRACT.md is v2 because its documented socket
default moved -- wire format unchanged.

Two comments that stated the old, wrong diagnosis (a 'misnamed' IPC socket) now
state the measured one: the event socket did not fit in sun_path.
2026-10-02 18:11:46 +00:00

263 lines
7.4 KiB
Python

"""Shared fixtures for the unit suite.
Two workstreams wrote fixtures for this directory (the server's own, and the
test harness's); this file is the merge of both. 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 an inline ``python3 -c`` program and the server is driven in-process.
"""
from __future__ import annotations
import contextlib
import os
import pathlib
import shutil
import socket
import struct
import sys
import tempfile
import threading
import zlib
import pytest
_HERE = pathlib.Path(__file__).resolve().parent
_SRC = _HERE.parents[1] / "src"
for _path in (str(_HERE), str(_SRC)):
if _path not in sys.path:
sys.path.insert(0, _path)
from hhstream.server import FrameServer # noqa: E402 (needs sys.path above)
#: The path named in docs/CONTRACT.md and in the module's option default.
CONTRACT_SOCKET = "/run/hypr-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 workdir():
"""A short-lived directory with a short path (AF_UNIX paths are ~108 bytes)."""
path = tempfile.mkdtemp(prefix="hhs")
try:
yield pathlib.Path(path)
finally:
shutil.rmtree(path, ignore_errors=True)
@pytest.fixture
def sock_path(workdir):
path = str(workdir / "s.sock")
if len(path) > SUN_PATH_MAX:
pytest.skip(f"workdir too long for an AF_UNIX socket: {len(path)} bytes")
return path
@pytest.fixture
def serve():
"""`with serve(path, capture, fps=...) as server:` -- bound and listening."""
started: list[tuple[FrameServer, threading.Thread]] = []
@contextlib.contextmanager
def _serve(path, capture, fps=20, fmt="image/png"):
server = FrameServer(path, capture, fps, fmt=fmt)
thread = threading.Thread(target=server.serve_forever, daemon=True)
started.append((server, thread))
thread.start()
assert server.ready.wait(5), "server never bound its socket"
try:
yield server
finally:
server.stop()
thread.join(5)
yield _serve
for server, thread in started:
server.stop()
thread.join(5)
@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."""
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.
"""
@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