wake-alarm/wake_alarm/tests/conftest.py
Krzysztof kuhy Rudnicki e8f50828e6 Phase 5: the power button no longer ends the alarm (item 2)
Two defences, because one press and one held press are different problems.

**Prevention — _inhibit.py.** A logind block-mode inhibitor on
handle-power-key:shutdown:idle, taken while the alarm is audible and released
in on_close(). Confirmed on the host before writing it that
PowerKeyIgnoreInhibited=no is in force, so no logind.conf drop-in is needed --
and none is added: a drop-in changes the machine permanently, an inhibitor is
scoped to the alarm.

Verified live: the inhibitor appears in `systemd-inhibit --list` as
`wake-alarm ... shutdown:idle:handle-power-key ... block` and disappears on
release.

The child runs `sleep 7200`, never `sleep infinity`. An orphaned block-mode
inhibitor would hold the power button down until reboot -- worse than the bug
being fixed -- so it self-terminates, and a stale one is cleared at startup.

That cleanup was wrong on the first attempt and the host run caught it:
`pkill -f "--who=wake-alarm"` matched the *shell that had just typed the
pattern* and killed it, leaving the real inhibitor alive (`killed 0`, one
inhibitor still listed). Substring matching is inherently self-matching. Now
it lists `pgrep -x systemd-inhibit` and confirms each pid via
/proc/<pid>/cmdline. Re-verified: orphan reaped, exactly one live inhibitor,
zero remaining after release.

**Consequence — _alarm_session.py.** The real gap was that nothing on disk
ever said "ringing, not yet dismissed": wake_state.json is written only on
dismissal, so a hard power-off left no trace and the catch-up window closed
while the machine was down. A signed record is now written at fire time, and
_trigger re-fires on one still marked ringing, ignoring the window.

Deliberately no date field. _state.py keys by UTC and
screen_locker/_wake_state.py mirrors that helper to read the very same file
from another repo, so the UTC basis there is load-bearing. The plan's
_today_str() flip is therefore NOT done -- it would have made any dismissal
between 00:00-02:00 local read as yesterday's in screen-locker and silently
lose an earned workout skip. This record carries only an aware fired_at and
compares elapsed time, so the midnight question never arises.

Age-bounded at 5400 s: an alarm that dies before dismissal leaves a record
nothing ever clears, and unbounded this would restart the alarm every minute
forever.

Two bugs the unit tests could not see, both found by running it:

- A future-stamped record returned None, i.e. "not ringing". But a backward
  clock jump is routine on a machine that hibernates nightly (NTP correcting
  after resume), so that failed *open* on exactly the escape it closes: ring
  on a fast clock, clock corrects, power-off works again. Now clamped to zero
  within a 900 s tolerance and logged.
- _alarm.py derived the correlation id from the alarm's *start* instant. On a
  catch-up or re-fire the PC would write wake-...-0735 while the phone wrote
  wake-...-0700 and the two log streams stop joining. Now
  correlation_id_for_today() derives it from the resolved alarm time, which is
  what _correlation.py always specified.

Every trigger test patched should_refire, so _decide against a real record was
untested -- which is why only the manual run found the first one. There is now
an end-to-end test that writes a real session and asserts the decision.

Splits carried: test_trigger.py 294 -> 197 + test_trigger_main.py,
test_alarm_part2.py 266 -> 170 + test_alarm_timers_flash.py. The inhibitor
handle moved into _AlarmHardware, which also settles pylint's attribute count
and puts it beside the other thing on_close() gives back.

No new suppressions: the one inline pylint disable was redundant, since
consider-using-with is already disabled repo-wide in pyproject.toml.

452 tests pass, 100% branch coverage.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-27 20:26:37 +02:00

125 lines
5.1 KiB
Python

"""Shared fixtures keeping the wake_alarm suite off the real machine.
Since gatelock v0.2.0 the lock builds one real ``tk.Toplevel`` per live
output. Two consequences for tests, both of which bite silently:
* ``tk.Toplevel`` over a ``MagicMock`` master sends real tkinter into infinite
mock recursion -- the run **hangs** rather than failing, which is far harder
to diagnose than an error.
* An unpatched lock setup shells out to ``setxkbmap`` and really disables VT
switching on the machine running the tests, and reaches the real
``$XDG_RUNTIME_DIR``, where it could stand a *production* locker down.
Sink reactivation adds a fourth: ``WakeAlarm.__init__`` starts a background
thread that really shells out to ``pactl set-card-profile`` and would reshape
the *host's* audio routing mid-test.
The power-key inhibitor and the session record add a fifth and a sixth: an
unstubbed run really spawns ``systemd-inhibit`` (blocking the machine's power
button for as long as the test process lives) and really writes the
*production* ``alarm_session.json``, which the next real trigger tick would
then act on. All three are stubbed here and re-patched explicitly by the tests
that assert the wiring.
The escape hatch adds a third: ``WakeAlarm.__init__`` builds its tracker over
the real ``ESCAPE_HISTORY_FILE``, so an unpatched run both reads a *production*
budget -- making "the button appears" tests fail on any day the real budget is
spent -- and could write to it.
So this is autouse and deliberately broad.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
from gatelock import Output, OutputRect
import pytest
if TYPE_CHECKING:
from collections.abc import Generator
from pathlib import Path
FAKE_OUTPUTS = (
Output(
"VIRTUAL-1",
connected=True,
rect=OutputRect(0, 0, 1920, 1080),
primary=True,
),
)
"""One live output, so the Tk-screen fallback (which would call int() on a
MagicMock) is never reached."""
TWO_OUTPUTS = (
Output("DP-0", connected=True, rect=OutputRect(0, 0, 3840, 2160), primary=True),
Output("HDMI-0", connected=True, rect=OutputRect(3840, 0, 2560, 1440)),
)
"""The real desk. Opt into it with the ``dual_output`` fixture for anything
asserting that work fans out: against ``FAKE_OUTPUTS`` a loop that only ever
touched the first surface would pass every assertion."""
def make_toplevel(_parent: object = None, **_kwargs: object) -> MagicMock:
"""A Toplevel stand-in that remembers the geometry it was given."""
window = 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))
window.geometry.side_effect = geometry
window.deiconify.side_effect = lambda: state.update(mapped=True)
window.withdraw.side_effect = lambda: state.update(mapped=False)
window.winfo_ismapped.side_effect = lambda: state["mapped"]
window.winfo_rootx.side_effect = lambda: state["x"]
window.winfo_rooty.side_effect = lambda: state["y"]
window.winfo_width.side_effect = lambda: state["w"]
window.winfo_height.side_effect = lambda: state["h"]
return window
@pytest.fixture(autouse=True)
def _hermetic(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Generator[None]:
"""Block every path from the lock to the real display or machine."""
monkeypatch.setenv("GATELOCK_RUNTIME_DIR", str(tmp_path / "gatelock-runtime"))
key_file = tmp_path / "hmac.key"
key_file.write_bytes(b"0" * 32)
with (
# The real key is root-owned but world-readable, so an unpatched run
# signs test entries with the *production* key on this machine and
# with none at all anywhere else. Pin it so the suite is portable.
patch("gatelock.log_integrity.DEFAULT_HMAC_KEY_FILE", key_file),
patch(
"wake_alarm._escape_flow.ESCAPE_HISTORY_FILE",
tmp_path / "escape_history.json",
),
patch("wake_alarm._alarm.start_alarm_reactivation"),
patch("wake_alarm._alarm.take_power_key_inhibitor", return_value=None),
patch("wake_alarm._alarm.release_power_key_inhibitor"),
patch("wake_alarm._alarm.start_session"),
patch("wake_alarm._alarm.finish_session"),
patch("gatelock._surfaces.tk.Toplevel", side_effect=make_toplevel),
patch("gatelock._outputs.RandrBackend.create", return_value=None),
patch("gatelock._outputs.scan_xrandr", return_value=FAKE_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 dual_output(_hermetic: None) -> Generator[None]:
"""Re-scan as a two-monitor desk, layered over the single-output default.
Depends on ``_hermetic`` so pytest is obliged to apply it second; the
``scan_xrandr`` patch here has to be the one that wins.
"""
with patch("gatelock._outputs.scan_xrandr", return_value=TWO_OUTPUTS):
yield