screen-locker/screen_locker/tests/test_early_bird_part2.py
Krzysztof kuhy Rudnicki 79879263ba Support multiple workouts per day; fix the dead sync; ban silent failures
The workout log stored ONE workout per calendar day, so a second same-day
workout was silently dropped and could never earn credit.

Multiple workouts per day:
- workout_log.json: {date: entry} -> {date: [entry, ...]}. Legacy entries are
  wrapped on read (_log_io.load_workout_log) so their HMACs stay valid — no
  re-signing; every write normalizes the file, migrating it progressively.
- New write chokepoint (_log_mixin.write_signed_entry) APPENDS and dedups by a
  stable workout_id, returning RecordResult so callers can tell a new workout
  from a duplicate. Re-verifying the same workout is a no-op.
- count_weekly_workouts is anti-gaming: each VERIFIED workout counts
  individually; self-reported manual entries count at most once per day. Four
  real workouts in one day satisfy the week; four manual entries count as one.
- Reward: the day's first counted workout gets the base +2h; an additional
  same-day VERIFIED workout gets +1h; an additional manual gets nothing. The
  old "+1h when weekly_count > 4" gate is replaced — weekly volume is the
  banked bonus's job and shouldn't be paid twice.
- Fixed: the unlock screen labelled the +1h "#{weekly_count - 4}", which can
  render negative under the new rule. Removed the dead runnerup_manual type.
- Flutter: the manual budget counts distinct DAYS, matching the PC.

PC->phone sync (it had never worked once):
- push_pc_manuals pushed from a side-store written at log-time, so anything
  logged before that feature existed could never publish. _manual_push now
  derives the crdt log directly from workout_log.json — the single source of
  truth — covering manual AND verified runs. The record id is the workout's own
  workout_id (derived for legacy entries to match the phone's format) and the
  HLC comes from the entry's own timestamp, so a re-push is byte-identical and
  the repo never churns.
- The phone reads every kind (readMergedWorkoutPayloads) and lists the PC's
  workouts under "SYNCED FROM PC". The manual budget still sees manual-only, so
  a verified run can't consume a self-report slot.
- Settings claimed "Connected." whenever a token STRING existed. It now
  verifies against the API on open, so a revoked token reports 401 instead of
  showing a green lie.

Never fail silently:
- 30 swallowed exceptions across 19 files now log WARNING with the concrete
  cause AND consequence — plus the token guards in _workout_sync that returned
  [] in total silence, the exact bug that hid the dead sync for weeks.
- New pre-commit hook (scripts/check_silent_failures.py) fails any except that
  neither re-raises nor logs loudly. ruff's S110 only catches `except: pass`;
  the real pattern here was `except: log.info(); return []`. Documented in
  CLAUDE.md.

Verified on real data: the Jul 13 run (pulled from its actual TCX over ADB) now
counts alongside that day's manual squash, and all three workouts are published
to kuhyx/syncs.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Fv8ULVt3Q67GwCFbM7doHB
2026-07-17 09:22:31 +02:00

190 lines
6.7 KiB
Python

"""Tests for early bird auto-upgrade, has_logged_today, and init flow."""
from __future__ import annotations
from datetime import datetime, timezone
import json
from pathlib import Path
from typing import Any
from unittest.mock import MagicMock, patch
import pytest
from screen_locker.screen_lock import ScreenLocker
from screen_locker.tests.conftest import (
create_locker,
create_locker_early_bird,
)
class TestTryAutoUpgradeEarlyBird:
"""Tests for _try_auto_upgrade_early_bird method."""
def test_upgrade_succeeds_when_verified(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Returns True, saves phone_verified entry, adjusts shutdown."""
log_file = tmp_path / "workout_log.json"
locker = create_locker(mock_tk, tmp_path)
locker.log_file = log_file
object.__setattr__(
locker,
"_verify_phone_workout",
MagicMock(return_value=("verified", "Workout verified! (67 min)")),
)
object.__setattr__(
locker,
"_adjust_shutdown_time_later",
MagicMock(return_value=True),
)
with patch(
"screen_locker._log_mixin.compute_entry_hmac",
return_value=None,
):
result = locker._try_auto_upgrade_early_bird()
assert result is True
with log_file.open() as f:
data: dict[str, Any] = json.load(f)
today = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
assert data[today][0]["workout_data"]["type"] == "phone_verified"
assert data[today][0]["workout_data"]["after_early_bird"] == "true"
def test_upgrade_fails_when_not_verified(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Returns False when phone shows no workout."""
locker = create_locker(mock_tk, tmp_path)
object.__setattr__(
locker,
"_verify_phone_workout",
MagicMock(return_value=("no_phone", "No phone connected")),
)
assert locker._try_auto_upgrade_early_bird() is False
def test_upgrade_fails_on_os_error(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Returns False when _verify_phone_workout raises OSError."""
locker = create_locker(mock_tk, tmp_path)
object.__setattr__(
locker,
"_verify_phone_workout",
MagicMock(side_effect=OSError("adb fail")),
)
assert locker._try_auto_upgrade_early_bird() is False
def test_upgrade_fails_on_runtime_error(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Returns False when _verify_phone_workout raises RuntimeError."""
locker = create_locker(mock_tk, tmp_path)
object.__setattr__(
locker,
"_verify_phone_workout",
MagicMock(side_effect=RuntimeError("unexpected")),
)
assert locker._try_auto_upgrade_early_bird() is False
class TestInitEarlyBirdFlow:
"""Integration tests for early bird branches in __init__."""
def test_init_saves_log_and_exits_during_early_bird_window(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""First login during 5-8:30 window: save early_bird log, exit."""
mock_sys_exit.side_effect = SystemExit(0)
with (
patch.object(Path, "resolve", return_value=tmp_path),
patch.object(ScreenLocker, "has_logged_today", return_value=False),
patch.object(ScreenLocker, "_is_sick_day_today", return_value=False),
patch.object(ScreenLocker, "_is_early_bird_pending", return_value=False),
patch.object(ScreenLocker, "_is_early_bird_time", return_value=True),
patch.object(
ScreenLocker,
"_try_auto_upgrade_early_bird",
return_value=False,
),
patch.object(ScreenLocker, "_save_early_bird_pending") as mock_save,
patch.object(ScreenLocker, "_start_phone_check"),
patch.object(ScreenLocker, "_start_verify_workout_check"),
patch(
"screen_locker._auto_upgrade.has_workout_skip_today",
return_value=False,
),
pytest.raises(SystemExit),
):
ScreenLocker(demo_mode=True)
mock_save.assert_called_once()
mock_sys_exit.assert_called_with(0)
def test_init_exits_when_early_bird_log_still_in_window(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Early bird log exists and window still active: skip lock, exit."""
mock_sys_exit.side_effect = SystemExit(0)
with pytest.raises(SystemExit):
create_locker_early_bird(mock_tk, tmp_path, state="log_active")
mock_sys_exit.assert_called_with(0)
def test_init_exits_when_early_bird_log_upgrades_successfully(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Early bird log + past 8:30 + workout done: upgrade, exit."""
mock_sys_exit.side_effect = SystemExit(0)
with (
patch.object(Path, "resolve", return_value=tmp_path),
patch.object(ScreenLocker, "has_logged_today", return_value=False),
patch.object(ScreenLocker, "_is_sick_day_today", return_value=False),
patch.object(ScreenLocker, "_is_early_bird_pending", return_value=True),
patch.object(ScreenLocker, "_is_early_bird_time", return_value=False),
patch.object(
ScreenLocker, "_try_auto_upgrade_early_bird", return_value=True
),
patch.object(ScreenLocker, "_start_phone_check"),
patch.object(ScreenLocker, "_start_verify_workout_check"),
pytest.raises(SystemExit),
):
ScreenLocker(demo_mode=True)
mock_sys_exit.assert_called_with(0)
def test_init_shows_lock_when_early_bird_log_no_workout(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Early bird log + past 8:30 + no workout: show lock, no early exit."""
locker = create_locker_early_bird(mock_tk, tmp_path, state="log_expired")
# _try_auto_upgrade_early_bird returns False (default in create_locker)
# so __init__ falls through to show the lock without calling sys.exit
mock_sys_exit.assert_not_called()
assert locker.demo_mode is True