screen-locker/screen_locker/tests/test_web_payload_part2.py
Krzysztof kuhy Rudnicki 8f911585c1 Serve the lock decision, its history and its health at 127.0.0.1:8770
The only status surface was a GTK tray icon, commented out of ~/.config/i3
on 2026-08-21. So when the weekly count went wrong, nothing on the machine
said so for two weeks -- the same silence that let a deleted timer job stop
enforcement for thirteen days in August.

Three read-only endpoints, and a React 19 UI over them:

  /api/status     the decision, the week, and whether today has a workout
  /api/decisions  the recorded trail, newest first
  /api/health     timers armed, disarm marker, log and trail freshness

The Why view is the one that matters: it renders the run of
"weekly_minimum_met 5/5" ticks that hid this week's bug, without anyone
having to reach for journalctl.

/api/status also carries gaming.workout_today, which is the fact
steam-backlog-enforcer will cut the daily budget on. Deliberately just the
fact -- the enforcer owns the hour values, so the two repos cannot come to
disagree about what a workout day is. It is derived from count_day_credits,
the same rule the locker enforces with.

_compliance_state_word moves from status_view (tkinter) into
_status_projection, and the systemd arming check moves from
scripts/check_enforcement_armed.py into screen_locker/_armed_state.py, so
the server can answer "is enforcement armed" without a second copy of the
logic that would be free to disagree with the gate.

web/ mirrors steam-backlog-enforcer/web but tightens it: that config has no
"strict" in any tsconfig, extends only tseslint recommended (no type-aware
rules at all), and gates neither lint nor typecheck in pre-commit. Here all
three run, on strictTypeChecked + stylisticTypeChecked, with
noUncheckedIndexedAccess and exactOptionalPropertyTypes. 44 tests, 100% of
statements, branches, functions and lines.

typescript stays pinned at 6.0.3: 7.0.2 is out, but every published
typescript-eslint -- stable, canary and rc-v8 -- declares
typescript ">=4.8.4 <6.1.0". The fleet allowlist already carries that entry.

The 250-line cap now covers ts/tsx. It was python/shell/dart only, which
would have made web/ exempt from the gate the rest of the repo lives under
-- the same omission that exempted the whole Flutter app until 2026-08-15.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Fcwu78wk17FWMHbbfbyicc
2026-08-29 22:50:19 +02:00

139 lines
5.6 KiB
Python

"""Tests for _web_payload.build_health_payload.
Split out of test_web_payload.py for the 250-line cap.
Every field asserted here exists because its absence once went unnoticed: a
timer systemd deleted to break an ordering cycle, a disarm marker nobody
removed, a log that quietly stopped being written. The rule the tests enforce
is that "could not check" is its own state and never reads as a pass.
"""
from __future__ import annotations
from datetime import UTC, datetime
from typing import TYPE_CHECKING
from unittest.mock import patch
from screen_locker._armed_state import TimerState
from screen_locker._web_payload import build_health_payload
if TYPE_CHECKING:
from pathlib import Path
_PKG = "screen_locker._web_payload"
_SATURDAY = datetime(2026, 8, 29, 21, 0, 0, tzinfo=UTC)
class TestHealthPayload:
"""Health turns every silent absence into a rendered value."""
def _states(self, *, armed: bool) -> list[TimerState]:
"""Build timer states for the fake.
Args:
armed: Whether the timers should read as armed.
Returns:
One state per required timer.
"""
return [
TimerState("workout-locker.timer", armed, "enabled", armed),
]
def test_armed_when_everything_checks_out(self, tmp_path: Path) -> None:
"""Timers armed, no marker, systemctl present."""
with (
patch(f"{_PKG}.systemctl_available", return_value=True),
patch(f"{_PKG}.collect_states", return_value=self._states(armed=True)),
patch(f"{_PKG}.DISARM_MARKER", tmp_path / "absent"),
):
payload = build_health_payload(now=_SATURDAY)
assert payload["armed"] is True
assert payload["timers"][0]["armed"] is True
def test_unchecked_is_never_armed(self, tmp_path: Path) -> None:
"""Without systemctl the answer is unknown, which is not a pass."""
with (
patch(f"{_PKG}.systemctl_available", return_value=False),
patch(f"{_PKG}.DISARM_MARKER", tmp_path / "absent"),
):
payload = build_health_payload(now=_SATURDAY)
assert payload["timers_checked"] is False
assert payload["armed"] is False
assert payload["timers"] == []
def test_disarm_marker_overrides_armed_timers(self, tmp_path: Path) -> None:
"""The marker is the deliberate off switch; it must win."""
marker = tmp_path / "DISARMED"
marker.write_text("off for a reason", encoding="utf-8")
with (
patch(f"{_PKG}.systemctl_available", return_value=True),
patch(f"{_PKG}.collect_states", return_value=self._states(armed=True)),
patch(f"{_PKG}.DISARM_MARKER", marker),
):
payload = build_health_payload(now=_SATURDAY)
assert payload["disarmed"] is True
assert payload["armed"] is False
def test_missing_log_reports_unknown_age(self, tmp_path: Path) -> None:
"""A log that is not there reads as unknown, not as fresh."""
with (
patch(f"{_PKG}.systemctl_available", return_value=False),
patch(f"{_PKG}.DISARM_MARKER", tmp_path / "absent"),
patch(f"{_PKG}.LOG_FILE", tmp_path / "missing.json"),
patch(f"{_PKG}.read_decisions", return_value=[]),
):
payload = build_health_payload(now=_SATURDAY)
assert payload["log_age_seconds"] is None
assert payload["last_decision_age_seconds"] is None
def test_decision_age_is_measured_from_the_newest_entry(
self,
tmp_path: Path,
) -> None:
"""A quiet locker shows up as an old last decision."""
trail = [{"timestamp": "2026-08-29T20:00:00+00:00"}]
with (
patch(f"{_PKG}.systemctl_available", return_value=False),
patch(f"{_PKG}.DISARM_MARKER", tmp_path / "absent"),
patch(f"{_PKG}.read_decisions", return_value=trail),
):
payload = build_health_payload(now=_SATURDAY)
assert payload["last_decision_age_seconds"] == 3600
def test_a_corrupt_timestamp_reads_as_unknown(self, tmp_path: Path) -> None:
"""An unparsable stamp must not crash the Health view."""
with (
patch(f"{_PKG}.systemctl_available", return_value=False),
patch(f"{_PKG}.DISARM_MARKER", tmp_path / "absent"),
patch(f"{_PKG}.read_decisions", return_value=[{"timestamp": "nonsense"}]),
):
payload = build_health_payload(now=_SATURDAY)
assert payload["last_decision_age_seconds"] is None
def test_a_missing_timestamp_reads_as_unknown(self, tmp_path: Path) -> None:
"""A decision line without a timestamp is handled, not assumed."""
with (
patch(f"{_PKG}.systemctl_available", return_value=False),
patch(f"{_PKG}.DISARM_MARKER", tmp_path / "absent"),
patch(f"{_PKG}.read_decisions", return_value=[{"reason": "enforced"}]),
):
payload = build_health_payload(now=_SATURDAY)
assert payload["last_decision_age_seconds"] is None
def test_log_age_is_measured_from_mtime(self, tmp_path: Path) -> None:
"""A written log reports a real, non-negative age."""
log = tmp_path / "log.json"
log.write_text("{}", encoding="utf-8")
with (
patch(f"{_PKG}.systemctl_available", return_value=False),
patch(f"{_PKG}.DISARM_MARKER", tmp_path / "absent"),
patch(f"{_PKG}.LOG_FILE", log),
patch(f"{_PKG}.read_decisions", return_value=[]),
):
payload = build_health_payload()
age = payload["log_age_seconds"]
assert isinstance(age, float)
assert age >= 0