wake-alarm/wake_alarm/tests/test_alarm_part4.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

244 lines
8.3 KiB
Python

"""Tests for WakeAlarm's gatelock hooks: on_focus_ready, on_callback_error, on_close."""
from __future__ import annotations
import tkinter as tk
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
import pytest
if TYPE_CHECKING:
from collections.abc import Generator
from wake_alarm._alarm import WakeAlarm
from wake_alarm._alarm_view import _EntryProxy
from wake_alarm._sinks import _AudioState
# ---------------------------------------------------------------------------
# Helpers (duplicated from part 1 so this file is self-contained)
# ---------------------------------------------------------------------------
def _make_mock_tk() -> MagicMock:
"""Build a MagicMock that stands in for the tkinter module."""
mock = MagicMock()
mock_root = MagicMock()
mock_root.winfo_screenwidth.return_value = 1920
mock_root.winfo_screenheight.return_value = 1080
mock.Tk.return_value = mock_root
# Distinct frames and buttons per call: a shared return_value would make
# "every monitor got one" indistinguishable from "one monitor got two".
mock.Frame.side_effect = lambda *_args, **_kwargs: MagicMock()
mock.Button.side_effect = lambda *_args, **_kwargs: MagicMock()
mock.Label.return_value = MagicMock()
mock.Entry.return_value = MagicMock()
mock.TclError = tk.TclError
mock.END = tk.END
return mock
@pytest.fixture(autouse=True)
def _block_real_tk() -> Generator[MagicMock]:
"""Prevent any real Tk windows in tests."""
mock = _make_mock_tk()
with (
patch("wake_alarm._alarm.tk", mock),
patch("wake_alarm._dismiss_view.tk", mock),
patch("wake_alarm._alarm_view.tk", mock),
patch(
"wake_alarm._alarm.GateRoot",
return_value=mock.Tk.return_value,
),
):
yield mock
@pytest.fixture(autouse=True)
def _block_extra_devices() -> Generator[MagicMock]:
"""Prevent real subprocess.Popen calls for extra ALSA devices."""
with (
patch("wake_alarm._beep_loop._play_on_all_sinks") as mock,
patch("wake_alarm._startup._set_max_brightness"),
patch("wake_alarm._startup._wake_display"),
patch("wake_alarm._alarm._restore_display"),
patch("wake_alarm._startup._warn_if_no_real_sink"),
patch("wake_alarm._alarm._activate_all_outputs", return_value=None),
patch("wake_alarm._alarm._restore_audio_state"),
patch("wake_alarm._startup.turn_on_plug"),
patch("wake_alarm._alarm.turn_off_plug"),
):
yield mock
@pytest.fixture
def mock_tk_module() -> Generator[MagicMock]:
"""Provide explicit access to the mocked tk module."""
mock = _make_mock_tk()
with (
patch("wake_alarm._alarm.tk", mock),
patch("wake_alarm._dismiss_view.tk", mock),
patch("wake_alarm._alarm_view.tk", mock),
patch(
"wake_alarm._alarm.GateRoot",
return_value=mock.Tk.return_value,
),
):
yield mock
class TestGatelockHooks:
"""Tests for the LockWindowHooks callbacks (on_focus_ready/on_callback_error)."""
def test_on_focus_ready_focuses_entry(
self,
mock_tk_module: MagicMock,
) -> None:
"""on_focus_ready forces focus onto the dismiss-code entry."""
del mock_tk_module
alarm = WakeAlarm(demo_mode=True)
alarm._view._views[0].entry.focus_force.reset_mock()
alarm.on_focus_ready(alarm._view._views[0])
alarm._view._views[0].entry.focus_force.assert_called_once()
alarm._stop_beep.set()
def test_on_callback_error_surfaces_and_refocuses(
self,
mock_tk_module: MagicMock,
) -> None:
"""on_callback_error shows a message and refocuses the entry."""
del mock_tk_module
alarm = WakeAlarm(demo_mode=True)
alarm._view._views[0].entry.focus_force.reset_mock()
alarm.on_callback_error()
alarm._view._views[0].labels.status.configure.assert_called_with(
text="Something went wrong — try again.",
)
alarm._view._views[0].entry.focus_force.assert_called_once()
alarm._stop_beep.set()
class TestClose:
"""Tests for the alarm's gatelock close path (LockWindow.close/on_close)."""
def test_lock_close_stops_beep_and_destroys(
self,
mock_tk_module: MagicMock,
) -> None:
"""LockWindow.close() runs on_close (stop event) and destroys root."""
del mock_tk_module
alarm = WakeAlarm(demo_mode=True)
alarm._lock.close()
assert alarm._stop_beep.is_set()
alarm.root.destroy.assert_called()
def test_on_close_restores_audio(
self,
mock_tk_module: MagicMock,
) -> None:
"""on_close restores the audio state captured at activation."""
del mock_tk_module
alarm = WakeAlarm(demo_mode=True)
state = _AudioState(
default_sink="jbl_sink",
card_profiles={},
sink_volumes={},
sink_mutes={},
)
alarm._hardware.audio_restore = state
with patch(
"wake_alarm._alarm._restore_audio_state",
) as mock_restore:
alarm.on_close()
mock_restore.assert_called_once_with(state)
alarm._stop_beep.set()
def test_on_close_releases_the_inhibitor_and_closes_the_session(
self,
mock_tk_module: MagicMock,
) -> None:
"""Both are released here, not in _dismiss_alarm.
on_close() is the one path that runs on *every* exit -- dismissal, the
escape hatch and SIGTERM alike -- so an alarm killed by systemd still
gives the power button back and still marks its session finished.
"""
del mock_tk_module
alarm = WakeAlarm(demo_mode=True)
sentinel = object()
alarm._hardware.inhibitor = sentinel
with (
patch("wake_alarm._alarm.release_power_key_inhibitor") as release,
patch("wake_alarm._alarm.finish_session") as finish,
):
alarm.on_close()
release.assert_called_once_with(sentinel)
finish.assert_called_once_with()
alarm._stop_beep.set()
class TestMultiMonitorSurfaces:
"""Per-output behaviour added in the gatelock v0.2.0 migration."""
def test_on_focus_ready_with_no_live_output(
self, mock_tk_module: MagicMock
) -> None:
"""A dark machine arms the alarm with nothing to focus."""
del mock_tk_module
alarm = WakeAlarm(demo_mode=True)
alarm._view._views[0].entry.focus_force.reset_mock()
alarm.on_focus_ready(None)
alarm._view._views[0].entry.focus_force.assert_not_called()
alarm._stop_beep.set()
def test_focus_force_skips_destroyed_entries(
self, mock_tk_module: MagicMock
) -> None:
"""A surface whose window already died is stepped over."""
del mock_tk_module
alarm = WakeAlarm(demo_mode=True)
dead, alive = MagicMock(), MagicMock()
dead.focus_force.side_effect = tk.TclError("gone")
proxy = _EntryProxy([dead, alive], MagicMock())
proxy.focus_force()
alive.focus_force.assert_called_once_with()
alarm._stop_beep.set()
def test_title_label_fans_out(self, mock_tk_module: MagicMock) -> None:
"""Every named label proxy reaches its per-monitor copies."""
del mock_tk_module
alarm = WakeAlarm(demo_mode=True)
alarm._view.title_label.configure(text="hi")
alarm._view._views[0].labels.title.configure.assert_called_with(text="hi")
alarm._stop_beep.set()
def test_teardown_forgets_a_dark_output(self, mock_tk_module: MagicMock) -> None:
"""An output going dark drops just its own view."""
del mock_tk_module
alarm = WakeAlarm(demo_mode=True)
surface = alarm._view._views[0]
alarm.teardown_surface(surface)
assert alarm._view._views == []
alarm._stop_beep.set()
def test_focus_force_when_every_entry_is_gone(
self, mock_tk_module: MagicMock
) -> None:
"""All surfaces destroyed: nothing to focus, and no exception."""
del mock_tk_module
alarm = WakeAlarm(demo_mode=True)
dead = MagicMock()
dead.focus_force.side_effect = tk.TclError("gone")
_EntryProxy([dead], MagicMock()).focus_force() # must not raise
alarm._stop_beep.set()