"""A real compositor-shaped socket, because the sockets are what break. Nothing here mocks :mod:`socket`. Each helper binds an actual ``AF_UNIX`` listener in a temporary directory laid out the way Hyprland lays one out (``/hypr//.socket.sock``) and answers canned bytes, so the tests drive the client's real connect, half-close, read-to-EOF and timeout paths. A mocked socket would pass while the thing that actually fails in production — a path that is gone, a peer that closes early, a reply that is plain text where JSON was promised — went untested. ``AF_UNIX`` caps a path at 108 bytes, so the sockets live in a shallow ``mkdtemp`` rather than under ``tmp_path``, whose name encodes the test's. """ from __future__ import annotations import shutil import socket import tempfile import threading from pathlib import Path import pytest #: Linux's sun_path is 108 bytes including the NUL. SUN_PATH_MAX = 107 #: Returned by a handler that should keep the connection open and say nothing, #: which is how a wedged compositor behaves and the only way to reach the #: client's read timeout. HANG = object() #: Shapes taken from Hyprland's own ``-j`` output. Trimmed to the keys the #: client reads, plus a few it must ignore. MONITORS_JSON = """ [{"id": 0, "name": "HEADLESS-2", "description": "headless", "make": "", "model": "", "x": 0, "y": 0, "width": 1280, "height": 720, "refreshRate": 60.0, "scale": 1.0, "transform": 0, "focused": true, "activeWorkspace": {"id": 1000, "name": "1000"}, "specialWorkspace": {"id": 0, "name": ""}, "dpmsStatus": true}, {"id": 1, "name": "HEADLESS-3", "x": 1280, "y": 0, "width": 800, "height": 600, "scale": 1.5, "focused": false}] """ WORKSPACES_JSON = """ [{"id": 1000, "name": "1000", "monitor": "HEADLESS-2", "monitorID": 0, "windows": 1, "hasfullscreen": false, "lastwindow": "0x5d3d1c0", "lastwindowtitle": "foot"}, {"id": -99, "name": "special:quarantine", "monitor": "HEADLESS-2", "windows": 0}] """ CLIENTS_JSON = """ [{"address": "0x5d3d1c0", "mapped": true, "hidden": false, "at": [0, 0], "size": [1280, 720], "workspace": {"id": 1000, "name": "1000"}, "floating": false, "monitor": 0, "class": "foot", "initialClass": "hh-foot-v7r4li", "title": "hermes: ~, build, and notes", "initialTitle": "foot", "pid": 4242, "xwayland": false, "pinned": false, "fullscreen": 0}, {"address": "0x5d4aa10", "mapped": false, "hidden": true, "class": "chromium", "initialClass": "", "title": "", "pid": 0, "monitor": null}] """ CURSORPOS_JSON = '{"x": 640, "y": 360}' VERSION_TEXT = ( "Hyprland 0.41.2 built from branch at commit 0000000 (). Date: 2026-01-01\n" "Tag: v0.41.2, commits: 5000\n\nflags: (if any)\ndebug\n" ) #: What a well-behaved compositor answers, keyed by the bare command. GOOD_REPLIES = { "monitors": MONITORS_JSON, "workspaces": WORKSPACES_JSON, "clients": CLIENTS_JSON, "cursorpos": CURSORPOS_JSON, "version": VERSION_TEXT, } def check_path(path: Path) -> None: if len(str(path).encode()) > SUN_PATH_MAX: pytest.skip(f"socket path too long for AF_UNIX ({len(str(path))} bytes): {path}") class RequestServer: """One listening request socket, answering through a handler. The handler is called with ``(flags, command)`` split the way Hyprland splits them — everything before the first ``/`` is flags — and returns the reply, ``None`` to close without answering, or :data:`HANG`. """ def __init__(self, path: Path, handler) -> None: check_path(path) self.path = path self.handler = handler self.requests: list[tuple[str, str]] = [] self._stop = threading.Event() self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) self._sock.bind(str(path)) self._sock.listen(8) self._sock.settimeout(0.05) self._thread = threading.Thread(target=self._serve, daemon=True) self._thread.start() def _serve(self) -> None: while not self._stop.is_set(): conn = self._accept() if conn is None: continue try: self._handle(conn) finally: conn.close() def _accept(self): """``None`` on a poll timeout, so :meth:`stop` is not waited out. Closing a listening socket does not reliably wake a thread blocked in ``accept``, which would make every test pay the join timeout. """ try: conn, _ = self._sock.accept() except (TimeoutError, socket.timeout): return None except OSError: self._stop.set() return None return conn def _handle(self, conn: socket.socket) -> None: # The client half-closes after writing, so the request ends at EOF. conn.settimeout(5.0) received = b"" while True: try: chunk = conn.recv(4096) except OSError: return if not chunk: break received += chunk text = received.decode("utf-8", errors="replace") flags, separator, command = text.partition("/") if not separator: flags, command = "", text self.requests.append((flags, command)) reply = self.handler(flags, command) if reply is HANG: self._stop.wait(5.0) return if reply is None: return data = reply.encode() if isinstance(reply, str) else reply try: conn.sendall(data) except OSError: pass def stop(self) -> None: self._stop.set() self._sock.close() self._thread.join(timeout=5.0) class EventServer: """One listening event socket that writes chunks, then closes or holds. Chunks are written as given — not line by line — so a test can split an event across two writes and prove the client reassembles it. """ def __init__(self, path: Path, chunks, close_after: bool = True) -> None: check_path(path) self.path = path self.chunks = [c.encode() if isinstance(c, str) else c for c in chunks] self.close_after = close_after self.connections = 0 self._stop = threading.Event() self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) self._sock.bind(str(path)) self._sock.listen(8) self._sock.settimeout(0.05) self._thread = threading.Thread(target=self._serve, daemon=True) self._thread.start() def _serve(self) -> None: while not self._stop.is_set(): try: conn, _ = self._sock.accept() except (TimeoutError, socket.timeout): continue except OSError: return self.connections += 1 try: for chunk in self.chunks: conn.sendall(chunk) # Let the client see this write on its own, so a chunk # boundary inside a line is a real boundary. self._stop.wait(0.01) if not self.close_after: self._stop.wait(5.0) except OSError: pass finally: conn.close() def stop(self) -> None: self._stop.set() self._sock.close() self._thread.join(timeout=5.0) @pytest.fixture def runtime_dir(): """A shallow temporary directory standing in for ``/run/hypr-stream``.""" path = Path(tempfile.mkdtemp(prefix="hhipc")) try: yield path finally: shutil.rmtree(path, ignore_errors=True) @pytest.fixture def instance(runtime_dir): """``/hypr/`` for one instance, created.""" directory = runtime_dir / "hypr" / "a1b2c3_1700000000" directory.mkdir(parents=True) return directory @pytest.fixture def servers(instance): """Factory for request/event servers on one instance, stopped at teardown.""" started: list = [] def start(handler=None, event_chunks=None, close_after=True): request = None events = None if handler is not None: request = RequestServer(instance / ".socket.sock", handler) started.append(request) if event_chunks is not None: events = EventServer(instance / ".socket2.sock", event_chunks, close_after) started.append(events) return request, events try: yield start finally: for server in started: server.stop() @pytest.fixture def good_handler(): """Answers every wrapped command the way a live compositor does.""" def handler(flags, command): return GOOD_REPLIES.get(command.strip(), "unknown request") return handler