"""The driver's XKB flags โ€” the only path a layout has to the uploaded keymap. This file exists where a `tests/sessions/unit/test_settings.py` case would have gone, and that is the point. The broker's TOML is read by `hhstreamd` for its lease numbers; `hhstream-pointer` is a different unit and never opens that file. So a `[keyboard]` table there would be a setting an operator could change with no effect at all, and a test asserting its default would be green while every injected key stayed on `us`. The layout therefore arrives as `--xkb-layout`, and these are the assertions about that flag: what it defaults to, that a bad value is exit **2**, and that a bad value is exit 2 **without the compositor being touched** โ€” because a layout xkbcommon will not compile is the operator's typo, and reporting it as exit 10 sends them to the wrong unit. """ from __future__ import annotations import os from pathlib import Path import pytest from hhstream_pointer import __main__ as entry class _Unreached(Exception): """Raised if the Wayland side is reached when it should not have been.""" class _RefusingSink: """A sink that fails the test if anything asks it to talk to a compositor. The review asked for an injected connect that can be asserted *not* to have been called; this is that, as a type rather than a flag, so a future code path that connects earlier fails loudly instead of silently reordering start-up. """ instances = 0 def __init__(self, runtime_dir, display_name=None) -> None: type(self).instances += 1 def connect(self) -> None: raise _Unreached("connect") def upload_keymap(self, text: str) -> None: raise _Unreached("upload_keymap") def close(self) -> None: pass @pytest.fixture def no_compositor(monkeypatch): _RefusingSink.instances = 0 monkeypatch.setattr(entry, "WaylandSink", _RefusingSink) return _RefusingSink # -- defaults --------------------------------------------------------------- def test_the_xkb_flags_default_to_the_frozen_values(): args = entry.build_parser().parse_args([]) assert args.xkb_layout == "us" assert args.xkb_model == "pc105" assert (args.xkb_variant, args.xkb_options) == ("", "") def test_the_defaults_are_the_ones_the_module_option_defaults_to(): # Stated as constants so the NixOS option and the hand-run binary cannot # drift into typing different characters. assert (entry.DEFAULT_LAYOUT, entry.DEFAULT_MODEL) == ("us", "pc105") def test_a_layout_is_taken_from_the_flag(): assert entry.build_parser().parse_args(["--xkb-layout", "de"]).xkb_layout == "de" def test_the_contract_command_line_still_parses(): """CONTRACT-sessions.md ยง3.4's exact line, plus the keymap flags.""" args = entry.build_parser().parse_args( [ "--socket", "/run/hhstream/pointer.sock", "--compositor-runtime-dir", "/run/hypr-stream", "--xkb-layout", "us", "--xkb-model", "pc105", "--xkb-variant", "", "--xkb-options", "", ] ) assert str(args.socket) == "/run/hhstream/pointer.sock" assert str(args.compositor_runtime_dir) == "/run/hypr-stream" assert args.xkb_layout == "us" # -- refusals, before any Wayland call -------------------------------------- def test_a_comma_separated_layout_exits_2_without_connecting(no_compositor, caplog): """v1 sends group 0 in every `modifiers`, so a second group is unreachable. xkbcommon accepts `us,ru` and hands back a two-group keymap, so nothing downstream would notice: a caller asking for Cyrillic would get Latin and no error. Refused here, and the NixOS option's type refuses it too โ€” this one is for the binary run by hand, which that type cannot reach. """ code = entry.main(["--xkb-layout", "us,ru"]) assert code == entry.EXIT_USAGE assert no_compositor.instances == 0, "the compositor must not be touched" def test_a_layout_xkbcommon_rejects_exits_2_without_connecting(no_compositor): code = entry.main(["--xkb-layout", "zzz-no-such-layout"]) assert code == entry.EXIT_USAGE assert no_compositor.instances == 0 def test_a_usable_layout_gets_as_far_as_the_compositor(no_compositor): """The other half: exit 2 must not be how a *good* layout fails. A test that only asserted the refusals would pass against a `main` that returned 2 for everything, so this one proves the good path reaches the Wayland side and fails there instead. """ with pytest.raises(_Unreached, match="connect"): entry.main(["--xkb-layout", "us"]) assert no_compositor.instances == 1 def test_the_exit_codes_match_the_brokers_table(): """Mirrored constants, compared against the table they mirror. The driver keeps its own copies on purpose -- it is a separate package and must not import the broker's internals -- so the two can drift, and asserting the literals alone would not notice. This imports the broker's enum to compare, which a test may do where the shipped driver may not. """ from hhstreamd.protocol import ExitCode assert entry.EXIT_OK == ExitCode.OK assert entry.EXIT_USAGE == ExitCode.USAGE assert entry.EXIT_COMPOSITOR == ExitCode.COMPOSITOR def test_the_module_passes_the_same_defaults_this_binary_has(): """The drift this guards is silent: a unit and a hand-run binary that type different characters, with nothing to compare them against but prose.""" module = Path(__file__).resolve().parents[2] / "nix/module.nix" if not module.is_file(): pytest.skip("not running from a checkout") text = module.read_text() assert f'default = "{entry.DEFAULT_LAYOUT}";' in text assert f'default = "{entry.DEFAULT_MODEL}";' in text # And the unit really passes them, rather than relying on these defaults: # a unit that relied on them would stop matching the contract's command # line the moment either moved. for flag in ("--xkb-layout", "--xkb-model", "--xkb-variant", "--xkb-options"): assert f'"{flag}"' in text, f"{flag} is not on the unit's ExecStart" # -- the keymap upload, which nothing else in the suite can see -------------- # # The dispatcher tests record tuples from a sink, so they are blind to the # Wayland `keymap` request: its format, its fd and its size never reach them. # That is the review's finding 3 -- a `main` that connected and listened # WITHOUT ever uploading passed every other test in this tree, and so did a # backend that re-uploaded on every `type`. #: One ordering log shared by the sink and the server stand-ins, because the #: assertion is about the order of events *between* the two objects: an upload #: after `listen` is a socket that promised a working device before it had one. ORDER: list[str] = [] class _UploadingSink: """A sink whose connect succeeds, recording what it was asked to upload.""" def __init__(self, runtime_dir, display_name=None) -> None: self.uploads: list[str] = [] self.connected = 0 _UploadingSink.last = self def connect(self) -> None: self.connected += 1 ORDER.append("connect") def upload_keymap(self, text: str) -> None: self.uploads.append(text) ORDER.append("upload") def has_keyboard(self) -> bool: return True def outputs(self) -> list[str]: return [] def close(self) -> None: pass class _RecordingServer: """Stands in for `PointerServer`, so no socket is bound. `serve_forever` raises, which is how the test gets control back at exactly the point the real process would start answering requests -- and therefore how it can assert the upload happened *before* that. """ class Served(Exception): pass def __init__(self, socket_path, handle, *, socket_mode=0o660) -> None: self.events: list[str] = [] _RecordingServer.last = self def listen(self) -> None: self.events.append("listen") ORDER.append("listen") def serve_forever(self) -> None: self.events.append("serve") ORDER.append("serve") raise _RecordingServer.Served def close(self) -> None: self.events.append("close") @pytest.fixture def uploading(monkeypatch): ORDER.clear() monkeypatch.setattr(entry, "WaylandSink", _UploadingSink) monkeypatch.setattr(entry, "PointerServer", _RecordingServer) return _UploadingSink def test_the_keymap_is_uploaded_once_before_the_socket_listens(uploading): """The ordering rule, asserted rather than described. `key` or `modifiers` before `keymap` is the protocol error `no_keymap`, which kills the connection instead of returning something the broker could report. So the upload has to happen between `connect` and `listen` -- a listening socket is a promise that the device works. """ with pytest.raises(_RecordingServer.Served): entry.main([]) sink = _UploadingSink.last assert sink.connected == 1 assert len(sink.uploads) == 1, "uploaded once, not per request" # The order across both objects, which is the whole assertion. A `main` # that never uploaded, or uploaded after `listen`, fails here -- and before # this test existed, both passed every other test in the tree. assert ORDER == ["connect", "upload", "listen", "serve"] def test_the_uploaded_text_is_the_keymap_for_the_flag(uploading): with pytest.raises(_RecordingServer.Served): entry.main(["--xkb-layout", "de"]) (text,) = _UploadingSink.last.uploads assert text.lstrip().startswith("xkb_keymap {") # The symbols name, which is what the VM check greps: a `de` layout that # silently compiled as `us` would say `pc_us_inet(evdev)` here. assert 'xkb_symbols "pc_de_inet(evdev)"' in text def test_the_payload_is_nul_terminated_and_the_size_counts_the_nul(): """The one value Hyprland reads off the end of the mapping if it is wrong. It `mmap`s exactly `size` bytes and hands the pointer to `xkb_keymap_new_from_string`, which wants a C string. A `size` of `len(text)` therefore has no terminator inside the mapping. The symptom is a keymap that will not compile, which from our side looks exactly like a compositor that has no keyboard at all -- so this is asserted on the real `WaylandSink.upload_keymap`, against a keyboard object that records the request. """ pytest.importorskip("pywayland") from hhstream_pointer import keymap as keymaps from hhstream_pointer.backend import WaylandSink class _Keyboard: def __init__(self) -> None: self.keymap_calls: list[tuple[int, bytes, int]] = [] self.modifier_calls: list[tuple] = [] def keymap(self, format_: int, fd: int, size: int) -> None: # Read it back through the fd the compositor is handed, not through # the string we started from: that is what the compositor sees. with os.fdopen(os.dup(fd), "rb", closefd=True) as handle: handle.seek(0) self.keymap_calls.append((format_, handle.read(size), size)) def modifiers(self, *args) -> None: self.modifier_calls.append(args) class _Manager: def __init__(self, keyboard) -> None: self.keyboard = keyboard def create_virtual_keyboard(self, seat): return self.keyboard keyboard = _Keyboard() sink = WaylandSink(Path("/nonexistent")) sink._keyboard_manager = _Manager(keyboard) sink._display = _NullDisplay() text = keymaps.build(layout="us").text() sink.upload_keymap(text) (format_, payload, size) = keyboard.keymap_calls[0] assert format_ == keymaps.XKB_V1 == 1 assert payload.endswith(b"\0"), "no terminator inside the mapping" assert payload.count(b"\0") == 1, "one terminator, not two" assert size == len(text.encode("utf-8")) + 1 assert payload[:-1].decode("utf-8") == text # And the mask is zeroed straight afterwards, because `destroy` of a # previous driver's keyboard cleared no mask and a client keeps the last # one it was sent. assert keyboard.modifier_calls == [(0, 0, 0, 0)] assert sink.has_keyboard() is True def test_a_compositor_with_no_keyboard_manager_uploads_nothing_and_still_works(): pytest.importorskip("pywayland") from hhstream_pointer.backend import WaylandSink sink = WaylandSink(Path("/nonexistent")) sink._display = _NullDisplay() # No `_keyboard_manager`: the global was never advertised. sink.upload_keymap("xkb_keymap {};") assert sink.has_keyboard() is False class _NullDisplay: """Enough of `pywayland.client.Display` for the two calls upload makes.""" def roundtrip(self) -> None: pass def flush(self) -> None: pass