ipc: a client that asks the compositor instead of guessing
The broker reported `workspace: null` and `window: null` for every session because nothing in it could talk to Hyprland. This is that voice, and the only place that knows the compositor's wire format: one connection per request on `.socket.sock` (leading `/` so an argument containing a slash is never read as output flags, `j/` where JSON is wanted), and a held, blocking stream on `.socket2.sock`. Every failure is CompositorUnavailable -- no instance directory, two of them and no signature, a socket that is gone, a peer that refuses or closes mid-reply, a reply that is not the JSON it promised, an event stream that ends. Nothing returns an empty list or a None to stand in for "I could not ask", because a caller that cannot tell those apart writes a guess into a session record. Inside the defined shape the parse is forgiving instead: Hyprland's JSON has changed keys across releases, so a missing key is a defined value and never a KeyError reaching the broker. Tests bind real AF_UNIX sockets in a temporary directory laid out the way Hyprland lays one out and serve canned bytes, so they drive the actual connect, half-close, read-to-EOF and timeout paths rather than a mock that would pass while the sockets broke. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MLiQAZCmJf66CEcLx8siYF
This commit is contained in:
1 parent
98374b8457
commit
9b77c77ee8
5 files changed
+1421
No files matched your search
@@ -0,0 +1,264 @@
|
||||
"""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
|
||||
(``<runtime>/hypr/<signature>/.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):
|
||||
"""``<runtime_dir>/hypr/<signature>`` 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
|
||||
@@ -0,0 +1,131 @@
|
||||
"""Finding the instance, and refusing to pick one when there is a choice.
|
||||
|
||||
Two instances and no signature is the dangerous case: a broker that guessed
|
||||
would aim its queries — and later its pointer — at someone else's desktop.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import socket
|
||||
|
||||
import pytest
|
||||
|
||||
from hhstreamd.ipc import SIGNATURE_ENV, CompositorUnavailable, HyprlandIPC
|
||||
|
||||
|
||||
def bind(path):
|
||||
"""A bound, listening socket at ``path``, so discovery sees a real one."""
|
||||
|
||||
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
sock.bind(str(path))
|
||||
sock.listen(1)
|
||||
return sock
|
||||
|
||||
|
||||
def test_single_instance_is_discovered(runtime_dir, instance, monkeypatch):
|
||||
monkeypatch.delenv(SIGNATURE_ENV, raising=False)
|
||||
sock = bind(instance / ".socket.sock")
|
||||
try:
|
||||
ipc = HyprlandIPC.discover(runtime_dir)
|
||||
finally:
|
||||
sock.close()
|
||||
assert ipc.request_socket == instance / ".socket.sock"
|
||||
assert ipc.event_socket == instance / ".socket2.sock"
|
||||
|
||||
|
||||
def test_no_instance_directory_at_all(runtime_dir, monkeypatch):
|
||||
monkeypatch.delenv(SIGNATURE_ENV, raising=False)
|
||||
with pytest.raises(CompositorUnavailable) as caught:
|
||||
HyprlandIPC.discover(runtime_dir)
|
||||
assert str(runtime_dir / "hypr") in str(caught.value)
|
||||
|
||||
|
||||
def test_zero_instances_under_hypr(runtime_dir, monkeypatch):
|
||||
monkeypatch.delenv(SIGNATURE_ENV, raising=False)
|
||||
(runtime_dir / "hypr").mkdir()
|
||||
with pytest.raises(CompositorUnavailable, match="no instance"):
|
||||
HyprlandIPC.discover(runtime_dir)
|
||||
|
||||
|
||||
def test_two_instances_without_a_signature_refuses(runtime_dir, instance, monkeypatch):
|
||||
monkeypatch.delenv(SIGNATURE_ENV, raising=False)
|
||||
other = runtime_dir / "hypr" / "deadbee_1700000001"
|
||||
other.mkdir()
|
||||
bind(instance / ".socket.sock").close()
|
||||
with pytest.raises(CompositorUnavailable) as caught:
|
||||
HyprlandIPC.discover(runtime_dir)
|
||||
message = str(caught.value)
|
||||
assert "2 instances" in message
|
||||
assert instance.name in message and other.name in message
|
||||
assert SIGNATURE_ENV in message
|
||||
|
||||
|
||||
def test_two_instances_with_an_explicit_signature(runtime_dir, instance, monkeypatch):
|
||||
monkeypatch.delenv(SIGNATURE_ENV, raising=False)
|
||||
other = runtime_dir / "hypr" / "deadbee_1700000001"
|
||||
other.mkdir()
|
||||
sock = bind(other / ".socket.sock")
|
||||
try:
|
||||
ipc = HyprlandIPC.discover(runtime_dir, signature=other.name)
|
||||
finally:
|
||||
sock.close()
|
||||
assert ipc.request_socket == other / ".socket.sock"
|
||||
|
||||
|
||||
def test_signature_from_the_environment(runtime_dir, instance, monkeypatch):
|
||||
other = runtime_dir / "hypr" / "deadbee_1700000001"
|
||||
other.mkdir()
|
||||
monkeypatch.setenv(SIGNATURE_ENV, other.name)
|
||||
sock = bind(other / ".socket.sock")
|
||||
try:
|
||||
ipc = HyprlandIPC.discover(runtime_dir)
|
||||
finally:
|
||||
sock.close()
|
||||
assert ipc.request_socket == other / ".socket.sock"
|
||||
|
||||
|
||||
def test_explicit_signature_beats_the_environment(runtime_dir, instance, monkeypatch):
|
||||
monkeypatch.setenv(SIGNATURE_ENV, "not_this_one")
|
||||
sock = bind(instance / ".socket.sock")
|
||||
try:
|
||||
ipc = HyprlandIPC.discover(runtime_dir, signature=instance.name)
|
||||
finally:
|
||||
sock.close()
|
||||
assert ipc.request_socket == instance / ".socket.sock"
|
||||
|
||||
|
||||
def test_signature_naming_a_missing_instance(runtime_dir, instance, monkeypatch):
|
||||
monkeypatch.setenv(SIGNATURE_ENV, "gone_1700000002")
|
||||
with pytest.raises(CompositorUnavailable, match="request socket"):
|
||||
HyprlandIPC.discover(runtime_dir)
|
||||
|
||||
|
||||
def test_instance_without_a_request_socket(runtime_dir, instance, monkeypatch):
|
||||
monkeypatch.delenv(SIGNATURE_ENV, raising=False)
|
||||
with pytest.raises(CompositorUnavailable) as caught:
|
||||
HyprlandIPC.discover(runtime_dir)
|
||||
assert ".socket.sock" in str(caught.value)
|
||||
|
||||
|
||||
def test_a_regular_file_is_not_a_socket(runtime_dir, instance, monkeypatch):
|
||||
monkeypatch.delenv(SIGNATURE_ENV, raising=False)
|
||||
(instance / ".socket.sock").write_text("not a socket")
|
||||
with pytest.raises(CompositorUnavailable, match="is not a socket"):
|
||||
HyprlandIPC.discover(runtime_dir)
|
||||
|
||||
|
||||
def test_a_signature_cannot_be_a_path(runtime_dir, instance):
|
||||
with pytest.raises(CompositorUnavailable, match="not a directory name"):
|
||||
HyprlandIPC.discover(runtime_dir, signature="../../elsewhere")
|
||||
|
||||
|
||||
def test_an_empty_environment_signature_falls_through(runtime_dir, instance, monkeypatch):
|
||||
"""An exported-but-empty variable is no signature, not a signature of ""."""
|
||||
|
||||
monkeypatch.setenv(SIGNATURE_ENV, "")
|
||||
sock = bind(instance / ".socket.sock")
|
||||
try:
|
||||
ipc = HyprlandIPC.discover(runtime_dir)
|
||||
finally:
|
||||
sock.close()
|
||||
assert ipc.request_socket == instance / ".socket.sock"
|
||||
@@ -0,0 +1,197 @@
|
||||
"""Event parsing, and a stream that must fail loudly when it stops.
|
||||
|
||||
The payload cases here are the ones that bite: a title full of commas (the
|
||||
whole reason the last field absorbs the rest of the line), an event with no
|
||||
payload at all, an event this module has never heard of, and a line delivered
|
||||
in two pieces by the kernel.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from hhstreamd.ipc import CompositorUnavailable, HyprlandIPC, parse_event
|
||||
|
||||
|
||||
def test_openwindow_names_its_fields():
|
||||
event = parse_event("openwindow>>0x5d3d1c0,1000,foot,hermes: ~")
|
||||
assert event.name == "openwindow"
|
||||
assert event.data["address"] == "0x5d3d1c0"
|
||||
assert event.data["workspace"] == "1000"
|
||||
assert event.data["class"] == "foot"
|
||||
assert event.data["title"] == "hermes: ~"
|
||||
assert event.data["args"] == ["0x5d3d1c0", "1000", "foot", "hermes: ~"]
|
||||
assert event.data["raw"] == "0x5d3d1c0,1000,foot,hermes: ~"
|
||||
|
||||
|
||||
def test_a_title_keeps_its_commas():
|
||||
"""A naive split(",") loses the end of the title; this is that regression."""
|
||||
|
||||
event = parse_event("openwindow>>0x1,1000,foot,hermes: ~, build, and notes")
|
||||
assert event.data["title"] == "hermes: ~, build, and notes"
|
||||
assert len(event.data["args"]) == 4
|
||||
|
||||
|
||||
def test_windowtitle_v2_absorbs_commas_too():
|
||||
event = parse_event("windowtitlev2>>0x1,a,b,c")
|
||||
assert event.data == {
|
||||
"raw": "0x1,a,b,c",
|
||||
"args": ["0x1", "a,b,c"],
|
||||
"address": "0x1",
|
||||
"title": "a,b,c",
|
||||
}
|
||||
|
||||
|
||||
def test_an_empty_payload_names_nothing():
|
||||
"""``configreloaded>>`` carried no values; "" is not a value."""
|
||||
|
||||
event = parse_event("configreloaded>>")
|
||||
assert event.name == "configreloaded"
|
||||
assert event.data == {"raw": "", "args": []}
|
||||
|
||||
|
||||
def test_a_single_field_event():
|
||||
event = parse_event("monitorremoved>>HEADLESS-3")
|
||||
assert event.data["name"] == "HEADLESS-3"
|
||||
assert event.data["args"] == ["HEADLESS-3"]
|
||||
|
||||
|
||||
def test_a_short_payload_names_only_what_arrived():
|
||||
"""An older Hyprland sending fewer fields must not invent the rest."""
|
||||
|
||||
event = parse_event("openwindow>>0x1,1000")
|
||||
assert event.data["address"] == "0x1"
|
||||
assert event.data["workspace"] == "1000"
|
||||
assert "class" not in event.data
|
||||
assert "title" not in event.data
|
||||
|
||||
|
||||
def test_an_unknown_event_is_still_usable():
|
||||
event = parse_event("somethingnew>>a,b,c")
|
||||
assert event.name == "somethingnew"
|
||||
assert event.data == {"raw": "a,b,c", "args": ["a", "b", "c"]}
|
||||
|
||||
|
||||
def test_trailing_newline_is_not_part_of_the_payload():
|
||||
assert parse_event("workspace>>1000\n").data["name"] == "1000"
|
||||
assert parse_event("workspace>>1000\r\n").data["name"] == "1000"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("line", ["workspace", "", " ", ">>1000", "workspace>1000"])
|
||||
def test_a_line_with_no_separator_is_malformed(line):
|
||||
with pytest.raises(CompositorUnavailable, match="name>>payload"):
|
||||
parse_event(line)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def ipc(instance):
|
||||
client = HyprlandIPC(instance / ".socket.sock", instance / ".socket2.sock")
|
||||
yield client
|
||||
client.close()
|
||||
|
||||
|
||||
def test_the_stream_yields_events_then_raises_at_eof(servers, ipc):
|
||||
chunks = [
|
||||
"openwindow>>0x1,1000,foot,hermes: ~, build\n",
|
||||
# One line split across two writes: the client must reassemble it
|
||||
# rather than parse half of it.
|
||||
"closewin",
|
||||
"dow>>0x1\nworkspacev2>>1000,1000\n",
|
||||
]
|
||||
servers(event_chunks=chunks)
|
||||
|
||||
stream = ipc.events()
|
||||
first = next(stream)
|
||||
assert first.name == "openwindow"
|
||||
assert first.data["title"] == "hermes: ~, build"
|
||||
assert next(stream).name == "closewindow"
|
||||
third = next(stream)
|
||||
assert (third.data["id"], third.data["name"]) == ("1000", "1000")
|
||||
|
||||
# The compositor closed. An iterator that merely stopped would be
|
||||
# indistinguishable from an idle desktop.
|
||||
with pytest.raises(CompositorUnavailable, match="event stream ended"):
|
||||
next(stream)
|
||||
|
||||
|
||||
def test_an_unterminated_tail_is_reported(servers, ipc):
|
||||
servers(event_chunks=["openwindow>>0x1,1000,foot,t\nhalf-an-ev"])
|
||||
stream = ipc.events()
|
||||
assert next(stream).name == "openwindow"
|
||||
with pytest.raises(CompositorUnavailable, match="unterminated"):
|
||||
next(stream)
|
||||
|
||||
|
||||
def test_a_malformed_line_in_the_stream(servers, ipc):
|
||||
servers(event_chunks=["this is not an event\n"])
|
||||
stream = ipc.events()
|
||||
with pytest.raises(CompositorUnavailable, match="name>>payload"):
|
||||
next(stream)
|
||||
|
||||
|
||||
def test_a_missing_event_socket(instance, ipc):
|
||||
with pytest.raises(CompositorUnavailable) as caught:
|
||||
ipc.events()
|
||||
assert ".socket2.sock" in str(caught.value)
|
||||
|
||||
|
||||
def test_no_event_socket_configured(instance):
|
||||
ipc = HyprlandIPC(instance / ".socket.sock")
|
||||
with pytest.raises(CompositorUnavailable, match="no event socket"):
|
||||
ipc.events()
|
||||
|
||||
|
||||
def test_the_connection_is_made_by_events_not_by_the_first_next(servers, ipc):
|
||||
"""So the caller that asked for the stream is the one told it failed."""
|
||||
|
||||
_, events = servers(event_chunks=["workspace>>1000\n"], close_after=False)
|
||||
stream = ipc.events()
|
||||
# ``connect`` returns as soon as the listen backlog takes it, so the
|
||||
# server's own accept lags by a scheduling quantum; the claim is that the
|
||||
# connection exists before anything iterates, not that it is instantaneous.
|
||||
deadline = time.monotonic() + 5.0
|
||||
while events.connections == 0 and time.monotonic() < deadline:
|
||||
time.sleep(0.01)
|
||||
assert events.connections == 1
|
||||
assert next(stream).name == "workspace"
|
||||
|
||||
|
||||
def test_close_unblocks_a_waiting_reader(servers, ipc):
|
||||
"""A blocked reader must end when the broker shuts the client down.
|
||||
|
||||
``close()`` shuts the socket down rather than only closing it, because a
|
||||
bare close does not wake a thread already sitting in ``recv``.
|
||||
"""
|
||||
|
||||
servers(event_chunks=["workspace>>1000\n"], close_after=False)
|
||||
stream = ipc.events()
|
||||
assert next(stream).name == "workspace"
|
||||
|
||||
outcome = []
|
||||
|
||||
def read_until_it_fails():
|
||||
try:
|
||||
next(stream)
|
||||
except BaseException as exc: # noqa: BLE001 - recorded, then asserted
|
||||
outcome.append(exc)
|
||||
|
||||
reader = threading.Thread(target=read_until_it_fails, daemon=True)
|
||||
reader.start()
|
||||
# The reader is blocked in recv on an open, silent socket.
|
||||
reader.join(timeout=0.2)
|
||||
assert reader.is_alive()
|
||||
|
||||
ipc.close()
|
||||
reader.join(timeout=5.0)
|
||||
assert not reader.is_alive()
|
||||
assert isinstance(outcome[0], CompositorUnavailable)
|
||||
|
||||
|
||||
def test_close_is_idempotent(servers, ipc):
|
||||
servers(event_chunks=["workspace>>1000\n"], close_after=False)
|
||||
ipc.events()
|
||||
ipc.close()
|
||||
ipc.close()
|
||||
@@ -0,0 +1,240 @@
|
||||
"""The request socket, against a real listener.
|
||||
|
||||
Every test here connects over ``AF_UNIX`` to a socket the fixture bound, so the
|
||||
failures that matter — a path that is gone, a peer that refuses, a peer that
|
||||
closes mid-reply, a peer that never answers — are produced rather than
|
||||
simulated.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import socket
|
||||
|
||||
import pytest
|
||||
|
||||
from hhstreamd.ipc import CompositorUnavailable, CursorPos, HyprlandIPC
|
||||
|
||||
from conftest import HANG
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def ipc(instance):
|
||||
client = HyprlandIPC(instance / ".socket.sock", instance / ".socket2.sock")
|
||||
yield client
|
||||
client.close()
|
||||
|
||||
|
||||
def test_version_is_the_banner_verbatim(servers, good_handler, ipc):
|
||||
request, _ = servers(good_handler)
|
||||
assert ipc.version().startswith("Hyprland 0.41.2 built from branch")
|
||||
assert "Tag: v0.41.2" in ipc.version()
|
||||
# Text, not JSON, and the command carries a leading "/" so an argument
|
||||
# containing a slash could never be read as output flags.
|
||||
assert request.requests[0] == ("", "version")
|
||||
|
||||
|
||||
def test_monitors(servers, good_handler, ipc):
|
||||
request, _ = servers(good_handler)
|
||||
monitors = ipc.monitors()
|
||||
assert [m.name for m in monitors] == ["HEADLESS-2", "HEADLESS-3"]
|
||||
first = monitors[0]
|
||||
assert (first.x, first.y, first.width, first.height) == (0, 0, 1280, 720)
|
||||
assert first.scale == 1.0
|
||||
assert first.active_workspace_id == 1000
|
||||
# The second monitor carries no activeWorkspace at all: a defined None.
|
||||
assert monitors[1].active_workspace_id is None
|
||||
assert monitors[1].scale == 1.5
|
||||
assert request.requests == [("j", "monitors")]
|
||||
|
||||
|
||||
def test_workspaces(servers, good_handler, ipc):
|
||||
servers(good_handler)
|
||||
workspaces = ipc.workspaces()
|
||||
assert [w.id for w in workspaces] == [1000, -99]
|
||||
assert workspaces[0].monitor == "HEADLESS-2"
|
||||
assert workspaces[0].windows == 1
|
||||
assert workspaces[0].is_special is False
|
||||
# No "special" key in this reply: the negative id and the name prefix are
|
||||
# what every Hyprland has agreed on.
|
||||
assert workspaces[1].is_special is True
|
||||
|
||||
|
||||
def test_clients(servers, good_handler, ipc):
|
||||
request, _ = servers(good_handler)
|
||||
clients = ipc.clients()
|
||||
assert len(clients) == 2
|
||||
foot, chromium = clients
|
||||
assert foot.address == "0x5d3d1c0"
|
||||
assert foot.pid == 4242
|
||||
assert foot.workspace_id == 1000
|
||||
assert foot.class_ == "foot"
|
||||
assert foot.initial_class == "hh-foot-v7r4li"
|
||||
# A title with commas in it survives whole; the broker shows this to a user.
|
||||
assert foot.title == "hermes: ~, build, and notes"
|
||||
assert foot.stable_id == "hh-foot-v7r4li:4242"
|
||||
assert foot.visible is True
|
||||
# clients -j reports the monitor as an index, not a name; the field is text
|
||||
# so that None keeps its one meaning of "the reply said nothing".
|
||||
assert foot.monitor == "0"
|
||||
|
||||
assert chromium.visible is False
|
||||
assert chromium.monitor is None
|
||||
assert chromium.workspace_id is None
|
||||
assert chromium.stable_id == "0x5d4aa10"
|
||||
assert request.requests == [("j", "clients")]
|
||||
|
||||
|
||||
def test_cursorpos(servers, good_handler, ipc):
|
||||
servers(good_handler)
|
||||
assert ipc.cursorpos() == CursorPos(x=640, y=360)
|
||||
|
||||
|
||||
def test_query_passes_a_command_through_untouched(servers, ipc):
|
||||
seen = []
|
||||
|
||||
def handler(flags, command):
|
||||
seen.append((flags, command))
|
||||
return "ok"
|
||||
|
||||
servers(handler)
|
||||
assert ipc.query("dispatch exec /usr/bin/true") == "ok"
|
||||
# The slash in the argument must not be read as a flag separator.
|
||||
assert seen == [("", "dispatch exec /usr/bin/true")]
|
||||
|
||||
|
||||
def test_query_keeps_an_explicit_flag_prefix(servers, ipc):
|
||||
seen = []
|
||||
|
||||
def handler(flags, command):
|
||||
seen.append((flags, command))
|
||||
return "[]"
|
||||
|
||||
servers(handler)
|
||||
assert ipc.query("j/devices") == "[]"
|
||||
assert seen == [("j", "devices")]
|
||||
|
||||
|
||||
def test_an_empty_request_is_refused_before_connecting(ipc):
|
||||
with pytest.raises(CompositorUnavailable, match="empty request"):
|
||||
ipc.query(" ")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("method", ["monitors", "workspaces", "clients", "cursorpos"])
|
||||
def test_plain_text_where_json_was_promised(servers, ipc, method):
|
||||
"""What Hyprland answers for a command it does not know."""
|
||||
|
||||
servers(lambda flags, command: "unknown request")
|
||||
with pytest.raises(CompositorUnavailable, match="not JSON"):
|
||||
getattr(ipc, method)()
|
||||
|
||||
|
||||
def test_a_json_object_where_a_list_belongs(servers, ipc):
|
||||
servers(lambda flags, command: '{"monitors": []}')
|
||||
with pytest.raises(CompositorUnavailable, match="expected a JSON list"):
|
||||
ipc.monitors()
|
||||
|
||||
|
||||
def test_a_list_of_scalars(servers, ipc):
|
||||
servers(lambda flags, command: '["HEADLESS-2"]')
|
||||
with pytest.raises(CompositorUnavailable, match="expected objects"):
|
||||
ipc.monitors()
|
||||
|
||||
|
||||
def test_a_client_without_an_address_is_malformed(servers, ipc):
|
||||
"""The one key whose absence makes the record meaningless."""
|
||||
|
||||
servers(lambda flags, command: '[{"class": "foot", "pid": 1}]')
|
||||
with pytest.raises(CompositorUnavailable, match="no address"):
|
||||
ipc.clients()
|
||||
|
||||
|
||||
def test_a_monitor_without_a_name_is_malformed(servers, ipc):
|
||||
servers(lambda flags, command: '[{"width": 1280}]')
|
||||
with pytest.raises(CompositorUnavailable, match="no name"):
|
||||
ipc.monitors()
|
||||
|
||||
|
||||
def test_a_workspace_without_an_id_is_malformed(servers, ipc):
|
||||
servers(lambda flags, command: '[{"name": "1000"}]')
|
||||
with pytest.raises(CompositorUnavailable, match="no id"):
|
||||
ipc.workspaces()
|
||||
|
||||
|
||||
def test_missing_keys_degrade_rather_than_raise_keyerror(servers, ipc):
|
||||
"""A reply from a Hyprland that reports less than this one expects."""
|
||||
|
||||
servers(lambda flags, command: '[{"address": "0x1"}]')
|
||||
(client,) = ipc.clients()
|
||||
assert client.pid == -1
|
||||
assert client.workspace_id is None
|
||||
assert client.monitor is None
|
||||
assert (client.class_, client.initial_class, client.title) == ("", "", "")
|
||||
assert client.stable_id == "0x1"
|
||||
# Nothing said it was unmapped, so it is not reported as gone.
|
||||
assert client.visible is True
|
||||
|
||||
|
||||
def test_cursorpos_without_coordinates(servers, ipc):
|
||||
servers(lambda flags, command: '{"ok": true}')
|
||||
with pytest.raises(CompositorUnavailable, match="x and y"):
|
||||
ipc.cursorpos()
|
||||
|
||||
|
||||
def test_cursorpos_with_non_numeric_coordinates(servers, ipc):
|
||||
servers(lambda flags, command: '{"x": "left", "y": null}')
|
||||
with pytest.raises(CompositorUnavailable, match="not numbers"):
|
||||
ipc.cursorpos()
|
||||
|
||||
|
||||
def test_connection_closed_mid_reply(servers, ipc):
|
||||
"""The compositor dies while writing: a truncated reply, never a guess."""
|
||||
|
||||
servers(lambda flags, command: '[{"address": "0x5d3d1c0", "pid": 4242, "cla')
|
||||
with pytest.raises(CompositorUnavailable, match="not JSON"):
|
||||
ipc.clients()
|
||||
|
||||
|
||||
def test_connection_closed_with_no_reply_at_all(servers, ipc):
|
||||
servers(lambda flags, command: None)
|
||||
with pytest.raises(CompositorUnavailable, match="empty reply"):
|
||||
ipc.workspaces()
|
||||
with pytest.raises(CompositorUnavailable, match="empty reply"):
|
||||
ipc.version()
|
||||
|
||||
|
||||
def test_missing_socket(instance):
|
||||
ipc = HyprlandIPC(instance / ".socket.sock")
|
||||
with pytest.raises(CompositorUnavailable) as caught:
|
||||
ipc.clients()
|
||||
assert str(instance / ".socket.sock") in str(caught.value)
|
||||
|
||||
|
||||
def test_nothing_listening(instance, ipc):
|
||||
"""A socket left behind by a compositor that is gone: ECONNREFUSED."""
|
||||
|
||||
stale = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
stale.bind(str(instance / ".socket.sock"))
|
||||
try:
|
||||
with pytest.raises(CompositorUnavailable, match="request socket"):
|
||||
ipc.monitors()
|
||||
finally:
|
||||
stale.close()
|
||||
|
||||
|
||||
def test_a_compositor_that_never_answers(servers, ipc):
|
||||
"""Accepted, then silence: the read timeout, exercised for real."""
|
||||
|
||||
servers(lambda flags, command: HANG)
|
||||
ipc.request_timeout_s = 0.3
|
||||
with pytest.raises(CompositorUnavailable, match="did not answer"):
|
||||
ipc.clients()
|
||||
|
||||
|
||||
def test_each_request_is_its_own_connection(servers, good_handler, ipc):
|
||||
"""What hyprctl does, and what the compositor expects: no session state."""
|
||||
|
||||
request, _ = servers(good_handler)
|
||||
ipc.monitors()
|
||||
ipc.clients()
|
||||
ipc.clients()
|
||||
assert request.requests == [("j", "monitors"), ("j", "clients"), ("j", "clients")]
|
||||
Reference in new issue
Block a user