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

225 lines
8.6 KiB
Python

"""Tests for the power-key inhibitor held while the alarm rings."""
from __future__ import annotations
import subprocess
from typing import TYPE_CHECKING
from unittest.mock import MagicMock
import pytest
from wake_alarm import _inhibit
from wake_alarm._constants import INHIBIT_WHO
if TYPE_CHECKING:
from pathlib import Path
@pytest.fixture
def _no_stale_scan(monkeypatch: pytest.MonkeyPatch) -> None:
"""Stub the stale scan, so taking an inhibitor never scans the real host.
Not autouse: TestStaleCleanup exercises the real function, and an autouse
stub would silently make every one of those tests assert nothing.
"""
monkeypatch.setattr(_inhibit, "kill_stale_inhibitors", lambda: 0)
def test_resolves_systemd_inhibit_from_path(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""The binary is looked up on PATH, never hardcoded."""
monkeypatch.setattr(_inhibit.shutil, "which", lambda name: f"/usr/bin/{name}")
assert _inhibit._systemd_inhibit_path() == "/usr/bin/systemd-inhibit"
@pytest.mark.usefixtures("_no_stale_scan")
class TestTakeInhibitor:
"""Taking the inhibitor that blocks the power button."""
def test_spawns_a_blocking_inhibitor(self, monkeypatch: pytest.MonkeyPatch) -> None:
"""The child blocks handle-power-key and self-terminates."""
monkeypatch.setattr(
_inhibit, "_systemd_inhibit_path", lambda: "/usr/bin/systemd-inhibit"
)
captured: list[list[str]] = []
def fake_popen(cmd: list[str], **_kwargs: object) -> MagicMock:
captured.append(cmd)
return MagicMock(pid=4242)
monkeypatch.setattr(_inhibit.subprocess, "Popen", fake_popen)
assert _inhibit.take_power_key_inhibitor() is not None
cmd = captured[0]
assert "--mode=block" in cmd
assert "--what=handle-power-key:shutdown:idle" in cmd
# Never `sleep infinity`: an orphaned blocker would hold the power
# button down until the next reboot.
assert cmd[-2] == "sleep"
assert int(cmd[-1]) > 0
def test_missing_binary_never_stops_the_alarm(
self, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
"""No systemd-inhibit means an unprotected alarm, not no alarm."""
monkeypatch.setattr(_inhibit, "_systemd_inhibit_path", lambda: None)
with caplog.at_level("WARNING"):
assert _inhibit.take_power_key_inhibitor() is None
assert "systemd-inhibit not on PATH" in caplog.text
def test_spawn_failure_is_survivable(
self, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
"""A failed spawn is logged and the alarm rings on."""
monkeypatch.setattr(
_inhibit, "_systemd_inhibit_path", lambda: "/usr/bin/systemd-inhibit"
)
def boom(_cmd: list[str], **_kwargs: object) -> MagicMock:
msg = "no fork for you"
raise OSError(msg)
monkeypatch.setattr(_inhibit.subprocess, "Popen", boom)
with caplog.at_level("WARNING"):
assert _inhibit.take_power_key_inhibitor() is None
assert "rings unprotected" in caplog.text
def test_clears_a_stale_inhibitor_first(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A blocker from a crashed alarm is cleared before a new one is taken."""
monkeypatch.setattr(
_inhibit, "_systemd_inhibit_path", lambda: "/usr/bin/systemd-inhibit"
)
monkeypatch.setattr(_inhibit.subprocess, "Popen", lambda *a, **k: MagicMock())
cleared: list[str] = []
def fake_clear() -> int:
cleared.append("cleared")
return 0
monkeypatch.setattr(_inhibit, "kill_stale_inhibitors", fake_clear)
_inhibit.take_power_key_inhibitor()
assert cleared == ["cleared"]
class TestReleaseInhibitor:
"""Releasing the inhibitor when the alarm ends."""
def test_none_is_a_no_op(self) -> None:
"""on_close() runs on every path, including ones that took nothing."""
_inhibit.release_power_key_inhibitor(None)
def test_already_exited_is_a_no_op(self) -> None:
"""A child that self-terminated is not signalled again."""
process = MagicMock()
process.poll.return_value = 0
_inhibit.release_power_key_inhibitor(process)
process.terminate.assert_not_called()
def test_terminates_a_live_inhibitor(self) -> None:
"""The ordinary path: SIGTERM, then reap."""
process = MagicMock()
process.poll.return_value = None
_inhibit.release_power_key_inhibitor(process)
process.terminate.assert_called_once_with()
process.wait.assert_called_once_with(timeout=5)
process.kill.assert_not_called()
def test_kills_an_inhibitor_that_ignores_sigterm(
self, caplog: pytest.LogCaptureFixture
) -> None:
"""A stuck child must not outlive the alarm holding the power key."""
process = MagicMock()
process.poll.return_value = None
process.wait.side_effect = subprocess.TimeoutExpired("systemd-inhibit", 5)
with caplog.at_level("WARNING"):
_inhibit.release_power_key_inhibitor(process)
process.kill.assert_called_once_with()
assert "ignored SIGTERM" in caplog.text
class TestStaleCleanup:
"""Clearing an inhibitor orphaned by a crashed alarm."""
def test_identifies_our_own_child(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""A pid is judged by its argv, never by a command-line pattern.
The earlier ``pkill -f`` version matched the shell that had just typed
the pattern and killed *it* -- substring matching is self-matching.
"""
proc = tmp_path / "77"
proc.mkdir()
(proc / "cmdline").write_bytes(
b"systemd-inhibit\x00--who=" + INHIBIT_WHO.encode() + b"\x00"
)
monkeypatch.setattr(
_inhibit.pathlib, "Path", lambda *p: tmp_path / p[-2] / p[-1]
)
assert _inhibit._is_our_inhibitor("77") is True
def test_ignores_a_pid_that_vanished(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""A process that exited between listing and reading is not stale."""
monkeypatch.setattr(
_inhibit.pathlib, "Path", lambda *p: tmp_path / "definitely-absent"
)
assert _inhibit._is_our_inhibitor("99") is False
def test_kills_only_matching_pids(self, monkeypatch: pytest.MonkeyPatch) -> None:
"""Someone else's systemd-inhibit is left strictly alone."""
monkeypatch.setattr(_inhibit.shutil, "which", lambda _name: "/usr/bin/pgrep")
monkeypatch.setattr(
_inhibit.subprocess,
"run",
lambda *a, **k: MagicMock(stdout=b"11\n22\n"),
)
monkeypatch.setattr(_inhibit, "_is_our_inhibitor", lambda pid: pid == "22")
signalled: list[int] = []
monkeypatch.setattr(
_inhibit.os, "kill", lambda pid, _sig: signalled.append(pid)
)
assert _inhibit.kill_stale_inhibitors() == 1
assert signalled == [22]
def test_survives_a_pid_that_exits_mid_kill(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A race between listing and killing is not an error."""
monkeypatch.setattr(_inhibit.shutil, "which", lambda _name: "/usr/bin/pgrep")
monkeypatch.setattr(
_inhibit.subprocess, "run", lambda *a, **k: MagicMock(stdout=b"11\n")
)
monkeypatch.setattr(_inhibit, "_is_our_inhibitor", lambda _pid: True)
def gone(_pid: int, _sig: int) -> None:
raise ProcessLookupError
monkeypatch.setattr(_inhibit.os, "kill", gone)
assert _inhibit.kill_stale_inhibitors() == 0
def test_no_pgrep_means_no_scan(self, monkeypatch: pytest.MonkeyPatch) -> None:
"""Without pgrep the cleanup is skipped rather than guessed at."""
monkeypatch.setattr(_inhibit.shutil, "which", lambda _name: None)
assert _inhibit.kill_stale_inhibitors() == 0
def test_pgrep_failure_is_survivable(
self, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
"""A failed scan must not stop the alarm from starting."""
monkeypatch.setattr(_inhibit.shutil, "which", lambda _name: "/usr/bin/pgrep")
def boom(*_a: object, **_k: object) -> None:
msg = "nope"
raise OSError(msg)
monkeypatch.setattr(_inhibit.subprocess, "run", boom)
with caplog.at_level("WARNING"):
assert _inhibit.kill_stale_inhibitors() == 0
assert "Could not check for a stale" in caplog.text