screen-locker/screen_locker/tests/_status_view_helpers.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

176 lines
4.8 KiB
Python

"""Shared StatusSnapshot-building test helpers for test_status_view*.py.
Not a test module itself (no test_/\u200b*_test naming) — pytest's collector
(``python_files`` in pyproject.toml) never picks this up as a test file.
"""
from __future__ import annotations
import dataclasses
from unittest.mock import MagicMock
from screen_locker._compliance_state import (
AutoUpgradeOpportunity,
LockExplanation,
PredicateResult,
)
from screen_locker._status_data import (
DayStatus,
ManualWorkoutBudgetStatus,
ShutdownProjection,
ShutdownProjectionDay,
SickBudgetStatus,
StatusSnapshot,
WeeklySummary,
)
from screen_locker._temperature import TemperatureCheck
from screen_locker.status_view import StatusWindow
_WEEKDAY_LABELS = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
def _day(
*,
date: str = "2024-01-05",
label: str = "Fri Jan 05",
entry_types: tuple[str, ...] = (),
source: str = "",
counted: bool = False,
day_count: int = 0,
is_sick_day: bool = False,
) -> DayStatus:
return DayStatus(
date=date,
label=label,
entry_types=entry_types,
source=source,
counted=counted,
day_count=day_count,
is_sick_day=is_sick_day,
)
def _week(
*,
days: tuple[DayStatus, ...] | None = None,
counted_count: int = 0,
minimum: int = 4,
remaining: int = 4,
extra: int = 0,
) -> WeeklySummary:
return WeeklySummary(
days=days or (_day(),),
counted_count=counted_count,
minimum=minimum,
remaining=remaining,
extra=extra,
)
def _lock_explanation(
*,
fired: bool = False,
stage: str = "already_logged",
reason: str = "Workout already logged today — lock skipped.",
auto_upgrade: AutoUpgradeOpportunity | None = None,
heat_skip_evaluated: bool = False,
) -> LockExplanation:
return LockExplanation(
fired=fired,
stage=stage,
reason=reason,
trace=(PredicateResult("already_logged", not fired, reason),),
auto_upgrade=auto_upgrade
or AutoUpgradeOpportunity(would_attempt=False, via="none", reason="none"),
heat_skip_evaluated=heat_skip_evaluated,
)
def _sick_budget(*, used_7d: int = 0, exhausted: bool = False) -> SickBudgetStatus:
return SickBudgetStatus(
used_7d=used_7d,
budget_7d=1,
used_30d=0,
budget_30d=3,
used_90d=0,
budget_90d=10,
debt=0,
exhausted=exhausted,
)
def _manual_workout_budget(
*, used_7d: int = 0, exhausted: bool = False
) -> ManualWorkoutBudgetStatus:
return ManualWorkoutBudgetStatus(
used_7d=used_7d,
budget_7d=2,
used_30d=0,
budget_30d=5,
exhausted=exhausted,
)
def _shutdown(
*, tonight: tuple[int, int, int] | None = (21, 21, 5)
) -> ShutdownProjection:
rest = tuple(
ShutdownProjectionDay(label=lbl, hour=21, speculative=False)
for lbl in _WEEKDAY_LABELS
)
preview = tuple(
ShutdownProjectionDay(label=lbl, hour=21, speculative=True)
for lbl in _WEEKDAY_LABELS
)
return ShutdownProjection(
tonight=tonight,
rest_of_week=rest,
next_week_preview=preview,
explanation="two separate systems",
)
def _snapshot(**overrides: object) -> StatusSnapshot:
default = StatusSnapshot(
today=_day(),
week=_week(),
bonus_hours_this_week=0,
streak=0,
early_bird_extended=False,
shutdown=_shutdown(),
lock_explanation=_lock_explanation(),
sick_budget=_sick_budget(),
manual_workout_budget=_manual_workout_budget(),
generated_at="2024-01-05T12:00:00+00:00",
)
return dataclasses.replace(default, **overrides)
def _texts(mock_tk: MagicMock) -> list[str]:
"""All text/label strings passed to any tk.Label call, in call order."""
return [c.kwargs.get("text", "") for c in mock_tk.Label.call_args_list]
def _button_texts(mock_tk: MagicMock) -> set[str]:
return {c.kwargs.get("text") for c in mock_tk.Button.call_args_list}
def _temp_check(
*, temp_celsius: float | None = 20.0, timed_out: bool = False
) -> TemperatureCheck:
return TemperatureCheck(temp_celsius=temp_celsius, timed_out=timed_out)
def _make_window(
mock_tk: MagicMock, snapshot: StatusSnapshot, **kwargs: object
) -> StatusWindow:
"""Build a StatusWindow with an instant, non-hot, non-network temperature
fetcher by default, so unrelated tests never trigger real network I/O —
tests exercising temperature behavior pass their own ``temperature_fetcher``.
"""
root = MagicMock()
kwargs.setdefault("temperature_fetcher", lambda _city: _temp_check())
return StatusWindow(
root, snapshot, on_refresh=kwargs.pop("on_refresh", MagicMock()), **kwargs
)