screen-locker/screen_locker/tests/test_verify_workout.py
Krzysztof Rudnicki 3e77f4e232 Make every lock screen keyboard-operable, and add the missing installer
The locker was not running at all. workout-locker.service crash-looped ~1977
times in a single boot with ModuleNotFoundError while remaining `enabled`, and
has no successful start in the retained journal. A locker that cannot start is
a locker that does not lock.

Root cause: commit 9b420a9 removed the unit's WorkingDirectory and
PYTHONPATH=/opt/screen-locker on the (correct in principle) grounds that
"screen_locker is now pip-installed" -- but nothing guaranteed that install.
There was no installer, /opt/screen-locker no longer exists, and the package
was absent from every Python version's user site-packages. The unit lost its
fallback and gained a hard dependency on a manual step nobody re-ran.

install.sh fixes that as a script rather than a reminder, and *gates*: it fails
if the production interpreter cannot import screen_locker, because an installer
that reports success while the service still cannot start is precisely the
failure above. It also re-asserts an editable gatelock from ~/utils AFTER the
package install and verifies it resolves there -- pyproject pins gatelock to a
git tag, so a plain install silently replaces a local editable gatelock with a
frozen wheel, which was observed removing ScrollableSurface and taking
diet_guard down with it.

The keyboard work, all of it Tk defaults rather than local mistakes:

- Focus was invisible. Tk ships highlightcolor="#000000" -- a black ring on
  #211D1B -- and relief="flat" removes the depth cue too, so a keyboard user
  had no indication of where they were. Now set in the _ui_widgets factory, so
  a new call site cannot omit it.
- Enter did nothing. X11 Tk binds <space> on Button and never <Return>.
- tk.Text trapped Tab (inserts a literal tab, refocuses itself) and no-opped
  Shift-Tab; the only exits are the undocumented Ctrl+Tab / Ctrl+Shift+Tab.
- The lock and retry screens started with NOTHING focused. on_focus_ready was
  a documented no-op arguing "buttons only, nothing to focus" -- exactly
  backwards: buttons are what needs focusing when there is no other window on
  screen and a global grab is held.
- The heat-skip modal grabbed input fullscreen with no focus, no ring, no
  Return and no Escape. It now focuses the *declining* option, so a blind
  Return keeps the workout rather than silently skipping it.

The manual-workout form's scroll viewport was pointer-only in three ways at
once: tk.Canvas has no class key bindings, so ::tk::FocusOK rejected it as a
focus stop; nothing bound wheel, PageUp/PageDown or arrows, leaving only a
draggable thumb; and canvas clipping does not unmap children, so below-the-fold
fields stayed in the tab ring while Tk never scrolled to follow focus -- Tab led
to fields the user could neither see nor reveal. Its height was also a magic
0.7*toplevel above ~230-290px of fixed chrome, i.e. satisfied at 1080p and
violated at 768p, where SUBMIT/BACK were pushed off the bottom.

All of that is gone by deletion: the surface container is now a
gatelock.ScrollableSurface, so the inner viewport is redundant. build_surface
and _ensure_container both use it, which fixes the same symmetric-clipping
problem for EVERY screen rather than one at a time; center_when_fits keeps
short screens looking exactly as they did.

Re-arming after a repaint hooks into clear_container(), which all ~19 repaint
sites already call. "Remember to call settle after painting" is a rule that
would eventually be missed, and on a lock a missed re-arm means unreachable
content.

The aux windows hardcoded geometry("600x400") and ("700x450") while displaying
more than that -- the relaxed-day prompt's own button row requests 862px inside
a 700px window, sheared at both edges. That pre-dates this work by a wide
margin (Tk's default focus ring accounts for 4px of the 162px overflow). They
now size to content, floored at the old values and clamped to the display.

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

352 lines
10 KiB
Python

"""Tests for post-sick-day workout verification (--verify-workout)."""
from __future__ import annotations
from datetime import datetime, timezone
import json
from typing import TYPE_CHECKING
from unittest.mock import MagicMock
import pytest
from screen_locker.tests.conftest import create_locker
if TYPE_CHECKING:
from pathlib import Path
class TestIsSickDayToday:
"""Tests for _is_sick_day_today method.
sick_day is tracked in sick_history.json (via _sick_tracker.py) as the
sole source of truth -- not in workout_log.json. The autouse
_isolate_sick_history fixture redirects SICK_HISTORY_FILE to
tmp_path/sick_history.json for every test.
"""
def test_no_history_file(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Return False when sick_history.json does not exist."""
locker = create_locker(mock_tk, tmp_path)
assert locker._is_sick_day_today() is False
def test_today_not_sick_day(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Return False when today is not in sick_history's sick_days list."""
locker = create_locker(mock_tk, tmp_path)
history_file = tmp_path / "sick_history.json"
history_file.write_text(json.dumps({"sick_days": ["2020-01-01"]}))
assert locker._is_sick_day_today() is False
def test_today_is_sick_day(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Return True when today is in sick_history's sick_days list."""
locker = create_locker(mock_tk, tmp_path)
today = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
history_file = tmp_path / "sick_history.json"
history_file.write_text(json.dumps({"sick_days": [today]}))
assert locker._is_sick_day_today() is True
class TestVerifyOnlyInit:
"""Tests for ScreenLocker initialization with verify_only=True."""
def test_verify_only_exits_when_no_sick_day(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Exit when verify_only but no sick day logged today."""
mock_sys_exit.side_effect = SystemExit(0)
with pytest.raises(SystemExit):
create_locker(
mock_tk,
tmp_path,
verify_only=True,
is_sick_day_log=False,
)
mock_sys_exit.assert_called_once_with(0)
def test_verify_only_starts_when_sick_day(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Start verification window when sick day is logged."""
locker = create_locker(
mock_tk,
tmp_path,
verify_only=True,
is_sick_day_log=True,
)
assert locker.verify_only is True
mock_sys_exit.assert_not_called()
def test_verify_only_sets_title(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Verify window title includes [VERIFY]."""
locker = create_locker(
mock_tk,
tmp_path,
verify_only=True,
is_sick_day_log=True,
)
locker.root.title.assert_called_with("Workout Locker [VERIFY]")
def test_close_and_run_use_root_directly(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""No LockWindow is built for verify_only; close()/run() use root."""
locker = create_locker(
mock_tk,
tmp_path,
verify_only=True,
is_sick_day_log=True,
)
assert locker._lock is None
locker.run()
locker.root.mainloop.assert_called_once()
locker.close()
locker.root.destroy.assert_called_once()
class TestSetupVerifyWindow:
"""Tests for _setup_verify_window."""
def test_sizes_itself_to_content_with_a_floor(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Verify window fits its content, with 600x400 as a floor not a cap.
This asserted ``geometry("600x400")``, which pinned the window to a size
smaller than what it displays -- the same defect that left the
relaxed-day prompt's 862px button row sheared inside a 700px window.
``geometry("")`` hands sizing to the geometry manager, ``minsize`` keeps
the old dimensions as a floor, and ``maxsize`` stops a wide screen's
content pushing the window off-display.
"""
locker = create_locker(
mock_tk,
tmp_path,
verify_only=True,
is_sick_day_log=True,
)
locker.root.geometry.assert_called_with("")
locker.root.minsize.assert_called_once()
locker.root.maxsize.assert_called_once()
locker.root.configure.assert_called_with(
bg=locker._colors.bg,
cursor="arrow",
)
locker.root.protocol.assert_called_with(
"WM_DELETE_WINDOW",
locker.close,
)
class TestStartVerifyWorkoutCheck:
"""Tests for _start_verify_workout_check."""
def test_starts_phone_check_and_polls(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Start phone verification and begin polling."""
locker = create_locker(mock_tk, tmp_path)
object.__setattr__(
locker,
"_verify_phone_workout",
MagicMock(return_value=("verified", "ok")),
)
object.__setattr__(
locker,
"_poll_verify_workout_check",
MagicMock(),
)
locker._start_verify_workout_check()
assert locker._phone_future is not None
locker._poll_verify_workout_check.assert_called_once()
class TestPollVerifyWorkoutCheck:
"""Tests for _poll_verify_workout_check."""
def test_schedules_retry_when_not_done(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Re-schedule polling when future is not done."""
locker = create_locker(mock_tk, tmp_path)
mock_future = MagicMock()
mock_future.done.return_value = False
locker._phone_future = mock_future
locker._poll_verify_workout_check()
locker.root.after.assert_called_with(
500,
locker._poll_verify_workout_check,
)
def test_handles_result_when_done(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Route to result handler when future is done."""
locker = create_locker(mock_tk, tmp_path)
mock_future = MagicMock()
mock_future.done.return_value = True
mock_future.result.return_value = ("verified", "Found workout")
locker._phone_future = mock_future
object.__setattr__(
locker,
"_handle_verify_workout_result",
MagicMock(),
)
locker._poll_verify_workout_check()
locker._handle_verify_workout_result.assert_called_once_with(
"verified",
"Found workout",
)
class TestHandleVerifyWorkoutResult:
"""Tests for _handle_verify_workout_result."""
def test_verified_adjusts_shutdown_and_saves(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""On verified: adjust shutdown, save log, show success."""
locker = create_locker(mock_tk, tmp_path)
locker.log_file = tmp_path / "workout_log.json"
object.__setattr__(
locker,
"_adjust_shutdown_time_later",
MagicMock(return_value=True),
)
locker._handle_verify_workout_result("verified", "1 session found")
assert locker.workout_data["type"] == "phone_verified"
assert locker.workout_data["after_sick_day"] == "true"
locker._adjust_shutdown_time_later.assert_called_once()
locker.root.after.assert_called()
def test_verified_without_adjustment(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""On verified but adjustment fails: still saves and shows success."""
locker = create_locker(mock_tk, tmp_path)
locker.log_file = tmp_path / "workout_log.json"
object.__setattr__(
locker,
"_adjust_shutdown_time_later",
MagicMock(return_value=False),
)
locker._handle_verify_workout_result("verified", "1 session found")
assert locker.workout_data["type"] == "phone_verified"
locker.root.after.assert_called()
def test_not_verified_shows_retry(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""On not_verified: show retry screen."""
locker = create_locker(mock_tk, tmp_path)
object.__setattr__(
locker,
"_show_verify_retry",
MagicMock(),
)
locker._handle_verify_workout_result(
"not_verified",
"No workout today",
)
locker._show_verify_retry.assert_called_once_with(
"No workout today",
)
def test_error_shows_retry(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""On error: show retry screen."""
locker = create_locker(mock_tk, tmp_path)
object.__setattr__(
locker,
"_show_verify_retry",
MagicMock(),
)
locker._handle_verify_workout_result("error", "ADB failed")
locker._show_verify_retry.assert_called_once_with("ADB failed")
class TestShowVerifyRetry:
"""Tests for _show_verify_retry."""
def test_shows_retry_and_close_buttons(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Show TRY AGAIN and Close buttons."""
locker = create_locker(mock_tk, tmp_path)
locker._show_verify_retry("No workout found")
# Verify container was cleared and buttons were packed
locker.container.first.winfo_children.return_value = []