mirror of
https://github.com/kuhyx/screen-locker.git
synced 2026-11-13 22:30:53 +01:00
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
301 lines
10 KiB
Python
301 lines
10 KiB
Python
"""Tests targeting remaining screen_lock.py coverage gaps."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import datetime, timezone
|
|
import json
|
|
from typing import TYPE_CHECKING
|
|
from unittest.mock import MagicMock, patch
|
|
|
|
from screen_locker.tests.conftest import create_locker
|
|
|
|
if TYPE_CHECKING:
|
|
from pathlib import Path
|
|
|
|
|
|
class TestUnlockScreenExtras:
|
|
"""Tests for unlock_screen extra-workout bonus and streak display (360-389)."""
|
|
|
|
def _setup_unlock(
|
|
self,
|
|
mock_tk: MagicMock,
|
|
tmp_path: Path,
|
|
weekly_count: int = 5,
|
|
streak: int = 0,
|
|
adjust_ok: bool = True,
|
|
seed_today_type: str | None = None,
|
|
):
|
|
"""Create a locker ready to call unlock_screen.
|
|
|
|
``seed_today_type`` pre-logs a counted workout for today under a
|
|
different ``workout_id``, so the unlock's own verified workout is an
|
|
ADDITIONAL same-day one — the case that now earns the +1h bonus.
|
|
"""
|
|
log_file = tmp_path / "workout_log.json"
|
|
if seed_today_type is None:
|
|
log_file.write_text("{}")
|
|
else:
|
|
today = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
|
|
log_file.write_text(
|
|
json.dumps(
|
|
{
|
|
today: [
|
|
{
|
|
"timestamp": f"{today}T06:00:00+00:00",
|
|
"workout_data": {"type": seed_today_type},
|
|
"workout_id": f"{seed_today_type}:{today}",
|
|
}
|
|
]
|
|
}
|
|
)
|
|
)
|
|
locker = create_locker(mock_tk, tmp_path)
|
|
locker.log_file = log_file
|
|
locker.workout_data = {"type": "phone_verified"}
|
|
|
|
object.__setattr__(
|
|
locker, "_try_adjust_shutdown_for_workout", MagicMock(return_value=False)
|
|
)
|
|
object.__setattr__(
|
|
locker, "_clear_debt_on_verified_workout", MagicMock(return_value=None)
|
|
)
|
|
object.__setattr__(
|
|
locker,
|
|
"_adjust_shutdown_time_by",
|
|
MagicMock(return_value=adjust_ok),
|
|
)
|
|
object.__setattr__(
|
|
locker,
|
|
"_read_shutdown_config",
|
|
MagicMock(return_value=(22, 22, 5)),
|
|
)
|
|
return locker
|
|
|
|
def test_extra_workout_bonus_shown(
|
|
self,
|
|
mock_tk: MagicMock,
|
|
mock_sys_exit: MagicMock,
|
|
tmp_path: Path,
|
|
) -> None:
|
|
"""An additional same-day verified workout earns the +1h bonus."""
|
|
locker = self._setup_unlock(
|
|
mock_tk, tmp_path, weekly_count=5, seed_today_type="manual_workout"
|
|
)
|
|
|
|
with (
|
|
patch(
|
|
"screen_locker._workout_credit.count_weekly_workouts",
|
|
return_value=5,
|
|
),
|
|
patch(
|
|
"screen_locker.screen_lock.current_streak",
|
|
return_value=0,
|
|
),
|
|
patch("screen_locker._log_mixin.compute_entry_hmac", return_value=None),
|
|
):
|
|
locker.unlock_screen()
|
|
|
|
locker._adjust_shutdown_time_by.assert_called_once_with(1)
|
|
|
|
def test_extra_bonus_delta_displayed(
|
|
self,
|
|
mock_tk: MagicMock,
|
|
mock_sys_exit: MagicMock,
|
|
tmp_path: Path,
|
|
) -> None:
|
|
"""extra_bonus_delta > 0 → _text called with 'Extra workout'."""
|
|
locker = self._setup_unlock(mock_tk, tmp_path, seed_today_type="manual_workout")
|
|
|
|
# Simulate before=22, after=23 → delta=1
|
|
old_cfg = (22, 22, 5)
|
|
new_cfg = (23, 23, 5)
|
|
locker._read_shutdown_config.side_effect = [old_cfg, new_cfg]
|
|
|
|
text_calls: list[str] = []
|
|
|
|
def _capture_text(msg: str, **kw: object) -> None:
|
|
text_calls.append(msg)
|
|
|
|
object.__setattr__(locker, "_text", _capture_text)
|
|
|
|
with (
|
|
patch(
|
|
"screen_locker._workout_credit.count_weekly_workouts",
|
|
return_value=5,
|
|
),
|
|
patch(
|
|
"screen_locker.screen_lock.current_streak",
|
|
return_value=0,
|
|
),
|
|
patch("screen_locker._log_mixin.compute_entry_hmac", return_value=None),
|
|
):
|
|
locker.unlock_screen()
|
|
|
|
assert any("Extra workout" in c for c in text_calls)
|
|
|
|
def test_no_extra_bonus_when_adjust_fails(
|
|
self,
|
|
mock_tk: MagicMock,
|
|
mock_sys_exit: MagicMock,
|
|
tmp_path: Path,
|
|
) -> None:
|
|
"""Additional verified workout but the +1h adjust fails → delta stays 0."""
|
|
locker = self._setup_unlock(
|
|
mock_tk,
|
|
tmp_path,
|
|
seed_today_type="manual_workout",
|
|
adjust_ok=False,
|
|
)
|
|
|
|
text_calls: list[str] = []
|
|
object.__setattr__(locker, "_text", lambda msg, **kw: text_calls.append(msg))
|
|
|
|
with (
|
|
patch(
|
|
"screen_locker._workout_credit.count_weekly_workouts",
|
|
return_value=5,
|
|
),
|
|
patch("screen_locker.screen_lock.current_streak", return_value=0),
|
|
patch("screen_locker._log_mixin.compute_entry_hmac", return_value=None),
|
|
):
|
|
locker.unlock_screen()
|
|
|
|
assert not any("Extra workout" in c for c in text_calls)
|
|
|
|
def test_no_extra_bonus_when_new_config_unreadable(
|
|
self,
|
|
mock_tk: MagicMock,
|
|
mock_sys_exit: MagicMock,
|
|
tmp_path: Path,
|
|
) -> None:
|
|
"""Re-reading the shutdown config fails after the +1h → delta stays 0."""
|
|
locker = self._setup_unlock(mock_tk, tmp_path, seed_today_type="manual_workout")
|
|
# old_cfg readable, new_cfg unreadable → no delta can be computed.
|
|
locker._read_shutdown_config.side_effect = [(22, 22, 5), None]
|
|
|
|
text_calls: list[str] = []
|
|
object.__setattr__(locker, "_text", lambda msg, **kw: text_calls.append(msg))
|
|
|
|
with (
|
|
patch(
|
|
"screen_locker._workout_credit.count_weekly_workouts",
|
|
return_value=5,
|
|
),
|
|
patch("screen_locker.screen_lock.current_streak", return_value=0),
|
|
patch("screen_locker._log_mixin.compute_entry_hmac", return_value=None),
|
|
):
|
|
locker.unlock_screen()
|
|
|
|
assert not any("Extra workout" in c for c in text_calls)
|
|
|
|
def test_streak_displayed_when_nonzero(
|
|
self,
|
|
mock_tk: MagicMock,
|
|
mock_sys_exit: MagicMock,
|
|
tmp_path: Path,
|
|
) -> None:
|
|
"""streak >= 1 → _text shows streak line (line 389)."""
|
|
locker = self._setup_unlock(mock_tk, tmp_path, weekly_count=3, adjust_ok=False)
|
|
|
|
text_calls: list[str] = []
|
|
|
|
def _capture_text(msg: str, **kw: object) -> None:
|
|
text_calls.append(msg)
|
|
|
|
object.__setattr__(locker, "_text", _capture_text)
|
|
|
|
with (
|
|
patch(
|
|
"screen_locker._workout_credit.count_weekly_workouts",
|
|
return_value=3,
|
|
),
|
|
patch(
|
|
"screen_locker.screen_lock.current_streak",
|
|
return_value=3,
|
|
),
|
|
patch("screen_locker._log_mixin.compute_entry_hmac", return_value=None),
|
|
):
|
|
locker.unlock_screen()
|
|
|
|
assert any("streak" in c.lower() for c in text_calls)
|
|
|
|
def test_extra_bonus_skipped_when_old_cfg_none(
|
|
self,
|
|
mock_tk: MagicMock,
|
|
mock_sys_exit: MagicMock,
|
|
tmp_path: Path,
|
|
) -> None:
|
|
"""old_cfg is None → branch 361->366: bonus block skipped, delta stays 0."""
|
|
locker = self._setup_unlock(mock_tk, tmp_path)
|
|
# _read_shutdown_config returns None → condition at 361 is False
|
|
locker._read_shutdown_config.return_value = None
|
|
|
|
with (
|
|
patch(
|
|
"screen_locker._workout_credit.count_weekly_workouts",
|
|
return_value=5,
|
|
),
|
|
patch("screen_locker.screen_lock.current_streak", return_value=0),
|
|
patch("screen_locker._log_mixin.compute_entry_hmac", return_value=None),
|
|
):
|
|
locker.unlock_screen()
|
|
# No assertion beyond "no crash" — we just needed the branch executed.
|
|
|
|
def test_extra_bonus_skipped_when_new_cfg_none(
|
|
self,
|
|
mock_tk: MagicMock,
|
|
mock_sys_exit: MagicMock,
|
|
tmp_path: Path,
|
|
) -> None:
|
|
"""new_cfg is None → branch 363->366: delta stays 0 even after adjust."""
|
|
locker = self._setup_unlock(mock_tk, tmp_path)
|
|
# First call (old_cfg): valid; second call (new_cfg after adjust): None
|
|
locker._read_shutdown_config.side_effect = [(22, 22, 5), None]
|
|
|
|
with (
|
|
patch(
|
|
"screen_locker._workout_credit.count_weekly_workouts",
|
|
return_value=5,
|
|
),
|
|
patch("screen_locker.screen_lock.current_streak", return_value=0),
|
|
patch("screen_locker._log_mixin.compute_entry_hmac", return_value=None),
|
|
):
|
|
locker.unlock_screen()
|
|
|
|
|
|
class TestIngestSyncedManualWorkouts:
|
|
"""Tests for _ingest_synced_manual_workouts (manual-sync wiring)."""
|
|
|
|
def test_logs_each_ingested_record(
|
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
|
) -> None:
|
|
locker = create_locker(mock_tk, tmp_path)
|
|
with (
|
|
patch(
|
|
"screen_locker.screen_lock.pull_all_manual_records",
|
|
return_value=[("manual:x", {})],
|
|
),
|
|
patch(
|
|
"screen_locker.screen_lock.ingest_manual_records",
|
|
return_value=["manual:x"],
|
|
) as ingest,
|
|
):
|
|
locker._ingest_synced_manual_workouts()
|
|
ingest.assert_called_once()
|
|
|
|
def test_no_records_ingests_nothing(
|
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
|
) -> None:
|
|
locker = create_locker(mock_tk, tmp_path)
|
|
with (
|
|
patch(
|
|
"screen_locker.screen_lock.pull_all_manual_records",
|
|
return_value=[],
|
|
),
|
|
patch(
|
|
"screen_locker.screen_lock.ingest_manual_records",
|
|
return_value=[],
|
|
),
|
|
):
|
|
locker._ingest_synced_manual_workouts()
|