utils/gatelock/gatelock/tests/conftest.py
Krzysztof kuhy Rudnicki a9b65812d7 gatelock v0.2.0: per-output locking, monotonic recovery, N-app arbitration
On 2026-07-25 the PC appeared frozen and needed an SSH rescue. Three defects
stacked:

1. DP-0 came up `connected` with a valid EDID and no mode/CRTC -- physically
   dark, while X still reserved its 3840px slice of the root window.
2. diet-guard-gate and workout-locker each mapped an override-redirect window
   spanning the WHOLE root (6400x1440+0+0), centring their controls on the
   primary output -- the dark one. The escape UI was invisible.
3. They deadlocked on the X grab, and the loser logged "another app -- e.g. a
   fullscreen game -- holds it". No game was running; the holder was the other
   locker. That guess sent the diagnosis the wrong way for the whole outage.

The library had no concept of an individual output: setup() sized the window
from winfo_screenwidth(), the union bounding box of every output.

What changes:

* _outputs.py  An output is LIVE only if connected AND has a mode/CRTC.
               RandR (crtc==0 or mode==0) and an xrandr --query parser derive
               that predicate independently; verified to agree exactly on the
               real DP-0/HDMI-0 layout. Fails closed three distinct ways.
* _surfaces.py One window per live output at its own geometry, and the only
               module allowed to create/move/destroy windows. Explicit
               geometry replaces attributes(fullscreen=True), which an
               override-redirect window is invisible to anyway.
* _detect.py   RandR events + Tk <Configure> + xrandr polling, coalesced. The
               RandR thread runs on a private X connection and may only call
               queue.put -- Tk is not thread-safe.
* _recovery.py Re-asserts coverage, placement, grab and VT on a timer. Proven
               monotonic: it may only ADD coverage or RE-ACQUIRE the grab. An
               ast test asserts the file contains none of grab_release /
               restore_vt_switching / close / destroy / quit / withdraw, while
               disable_vt_switching and grab_set_global ARE present. Yanking
               every cable therefore does not unlock anything.
* _arbiter.py  N-app priority: wake_alarm > screen_locker > diet_guard.
               Liveness is proved by flock-on-death -- no heartbeat, no PID
               scan, no clock. A two-axis strength check stops rank ever
               weakening the lock: an app stands down only for an incumbent
               at least as strong on BOTH grab kind and VT disabling.
* _guards.py   wait_for_x_server replaces wait_for_display and gates ONLY on
               an X server existing. Output count must never gate arming:
               zero live outputs means lock without showing, not decline to
               lock. That inversion is what left the machine unlocked.
* _window.py   Arms first, renders second. Names the real grab holder instead
               of blaming a fullscreen game. Releases the arbiter on close so
               the alarm -> workout handoff cannot strand the next app.

Two bugs found by running it, not reading it:

* acquire_holder() opened the holder file "w", which truncates at open() --
  before the lock attempt. A losing contender erased the incumbent's claim, so
  the app that most needed to know who held the screen found an empty file.
* tk.Toplevel over a MagicMock sends real tkinter into infinite mock recursion;
  the suite hung instead of failing, and an unpatched setup() would have run
  setxkbmap against the developer's own machine. conftest now has an autouse
  hermetic fixture; the suite went from >120s to 0.7s.

235 tests, 100% branch coverage, ruff (select=ALL) and mypy --strict clean.
No suppressions added: Protocols replace Any for python-xlib, public attribute
access replaces ._data, and type-only Protocols live under TYPE_CHECKING.

Consumers still pin gatelock-v0.1.1 and are unmigrated; nothing ships until a
tag and a reinstall into system python.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-25 14:30:03 +02:00

113 lines
4.1 KiB
Python

"""Shared fixtures for gatelock tests.
``LockWindow`` takes its Tk root as a constructor argument (composition, not
inheritance), so tests never need a real display -- a plain ``MagicMock``
stands in for the root everywhere. ``GateRoot`` does subclass ``tk.Tk``
directly (that's the point: Tkinter calls ``report_callback_exception`` on
the real root), so its tests build an instance via ``__new__`` to exercise
the overridden method without running ``tk.Tk.__init__`` (which requires a
display).
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
import pytest
from gatelock._outputs import Output, OutputRect
from gatelock._window import LockConfig, LockWindow
if TYPE_CHECKING:
from collections.abc import Generator
from pathlib import Path
DEFAULT_OUTPUTS = (
Output(
"VIRTUAL-1", connected=True, rect=OutputRect(0, 0, 1920, 1080), primary=True
),
)
"""One live output matching ``mock_root``'s screen size."""
def make_toplevel(_parent: object = None, **_kwargs: object) -> MagicMock:
"""A Toplevel stand-in that remembers the geometry it was given.
Real ``tk.Toplevel`` cannot be constructed over a ``MagicMock`` master --
tkinter's widget-naming path recurses through the mock forever and the test
run hangs rather than failing. So every surface window is faked here.
"""
win = MagicMock()
state = {"x": 0, "y": 0, "w": 0, "h": 0, "mapped": False}
def geometry(spec: str) -> None:
size, x, y = spec.split("+")
width, height = size.split("x")
state.update(x=int(x), y=int(y), w=int(width), h=int(height))
win.geometry.side_effect = geometry
win.deiconify.side_effect = lambda: state.update(mapped=True)
win.withdraw.side_effect = lambda: state.update(mapped=False)
win.winfo_ismapped.side_effect = lambda: state["mapped"]
win.winfo_rootx.side_effect = lambda: state["x"]
win.winfo_rooty.side_effect = lambda: state["y"]
win.winfo_width.side_effect = lambda: state["w"]
win.winfo_height.side_effect = lambda: state["h"]
return win
@pytest.fixture(autouse=True)
def _hermetic(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Generator[None]:
"""Keep the whole suite off the real machine.
Autouse and deliberately broad. A lock window takes a global input grab and
disables VT switching; a test that reached the real display or the real
``setxkbmap`` would black out the developer's own machine, and one that
reached the real runtime directory could stand a *production* locker down.
Blocking all of that centrally beats remembering to patch it per test.
"""
monkeypatch.setenv("GATELOCK_RUNTIME_DIR", str(tmp_path / "runtime"))
with (
patch("gatelock._surfaces.tk.Toplevel", side_effect=make_toplevel),
patch("gatelock._outputs.RandrBackend.create", return_value=None),
patch("gatelock._outputs.scan_xrandr", return_value=DEFAULT_OUTPUTS),
patch("gatelock._detect._RandrEventSource.start", return_value=False),
patch("gatelock._vt.shutil.which", return_value="/usr/bin/setxkbmap"),
patch("gatelock._vt.subprocess.run"),
):
yield
@pytest.fixture
def mock_root() -> MagicMock:
"""A MagicMock standing in for a tkinter root window."""
root = MagicMock()
root.winfo_screenwidth.return_value = 1920
root.winfo_screenheight.return_value = 1080
root.grab_current.return_value = root
return root
@pytest.fixture
def mock_subprocess_run() -> Generator[MagicMock]:
"""Block real subprocess calls (setxkbmap) and fake its presence."""
with (
patch("gatelock._vt.shutil.which", return_value="/usr/bin/setxkbmap"),
patch("gatelock._vt.subprocess.run") as mock,
):
yield mock
def make_window(
root: MagicMock,
*,
config: LockConfig | None = None,
hooks: MagicMock | None = None,
) -> tuple[LockWindow, MagicMock]:
"""Build a LockWindow over a mock root, returning it with its hooks mock."""
hooks = hooks if hooks is not None else MagicMock()
window = LockWindow(root, config or LockConfig(), hooks)
return window, hooks