mirror of
https://github.com/kuhyx/screen-locker.git
synced 2026-11-22 19:32:17 +01:00
Write a progress row for a short run day
Some checks are pending
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (flutter, flutter-analyze, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint,flutter-analyze,dependency-freshness) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Some checks are pending
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (flutter, flutter-analyze, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint,flutter-analyze,dependency-freshness) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
When a verified RunnerUp day is real but too short to qualify, the ledger now gets one signed "progress" row saying how far it got: metres over the distance bar or seconds over the time bar, whichever fraction is larger, from the verified TCX only. Several short runs in a day are summed; a longer second run writes a new row with a larger done. The row is inert: no reader uses it yet, and no bonus, shutdown time, stamp or web payload changes. Qualifying days write only their normal credit. Manual and StrongLifts days and the rooted-DB path write nothing. Failure modes: if the row cannot be signed or written, the workout verdict and everything else proceed exactly as before and the failure is logged at warning or above. An unreadable TCX is "could not check" and writes nothing. The bars appear only inside the signed row, never in a log line or message. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WzxdWVfmEXxPymCs5bo3Zs
This commit is contained in:
parent
c852379719
commit
4ed64b463c
@ -67,6 +67,9 @@ class ActivityDay:
|
|||||||
day never got there (or the activity recorded no end).
|
day never got there (or the activity recorded no end).
|
||||||
all_walks: Whether every activity was a walk (label only).
|
all_walks: Whether every activity was a walk (label only).
|
||||||
sport: The sport code when the day is a single non-walk activity.
|
sport: The sport code when the day is a single non-walk activity.
|
||||||
|
metres: The summed distance in metres, unrounded (feeds the signed
|
||||||
|
progress row; ``distance_km`` is the same figure over 1000).
|
||||||
|
moving_seconds: The summed moving seconds, likewise.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
legs: int
|
legs: int
|
||||||
@ -75,6 +78,8 @@ class ActivityDay:
|
|||||||
completed_at: float | None
|
completed_at: float | None
|
||||||
all_walks: bool = False
|
all_walks: bool = False
|
||||||
sport: int = -1
|
sport: int = -1
|
||||||
|
metres: float = 0.0
|
||||||
|
moving_seconds: float = 0.0
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def qualifies(self) -> bool:
|
def qualifies(self) -> bool:
|
||||||
@ -130,4 +135,6 @@ def activity_day(activities: Iterable[dict[str, Any]]) -> ActivityDay:
|
|||||||
completed_at=completed_at,
|
completed_at=completed_at,
|
||||||
all_walks=bool(ordered) and all(a.get("walking") for a in ordered),
|
all_walks=bool(ordered) and all(a.get("walking") for a in ordered),
|
||||||
sport=int(ordered[0].get("sport", -1)) if ordered else -1,
|
sport=int(ordered[0].get("sport", -1)) if ordered else -1,
|
||||||
|
metres=metres,
|
||||||
|
moving_seconds=moving,
|
||||||
)
|
)
|
||||||
|
|||||||
89
screen_locker/_progress_row.py
Normal file
89
screen_locker/_progress_row.py
Normal file
@ -0,0 +1,89 @@
|
|||||||
|
"""The workout's signed "progress" row: how far a too-short verified day got.
|
||||||
|
|
||||||
|
Writer only. The row is inert today -- no reader in ``earned_time`` looks at
|
||||||
|
``kind: "progress"`` yet -- and it never touches a bonus, a shutdown time, a
|
||||||
|
stamp or the web payload. It records ``done`` of ``target`` for one day, in
|
||||||
|
integers, from the verified RunnerUp TCX only::
|
||||||
|
|
||||||
|
{"kind": "progress", "entry_id": "progress:<day>:<done>:<target>",
|
||||||
|
"day": <day>, "amount": 0,
|
||||||
|
"detail": {"source": "workout", "for_day": <day>,
|
||||||
|
"done": "<digits>", "target": "<digits>"}}
|
||||||
|
|
||||||
|
The larger of the two fractions (distance / distance bar, moving time / time
|
||||||
|
bar) is the one recorded, so ``done``/``target`` is metres over metres or
|
||||||
|
seconds over seconds. The bars come from ``_constants`` and appear only inside
|
||||||
|
the signed row: they are never logged or shown (the constants file keeps a
|
||||||
|
deliberate leeway hidden). The ADVERTISED bars are the targets, not the
|
||||||
|
looser accept bars, so a row never reveals the leeway.
|
||||||
|
|
||||||
|
Signing, locking and idempotence on ``entry_id`` are the credit rows' own
|
||||||
|
(:func:`screen_locker._workout_ledger.append_rows`); a second short run the
|
||||||
|
same day has a larger ``done`` and so a new id.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from screen_locker._constants import MIN_RUN_DISTANCE_KM, MIN_WORKOUT_DURATION_MINUTES
|
||||||
|
from screen_locker._workout_ledger import append_rows
|
||||||
|
|
||||||
|
_logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
SOURCE = "workout"
|
||||||
|
|
||||||
|
|
||||||
|
def progress_pair(metres: float, moving_seconds: float) -> tuple[int, int] | None:
|
||||||
|
"""``(done, target)`` of the leading fraction, or ``None`` with nothing done.
|
||||||
|
|
||||||
|
Both fractions are compared exactly, by cross-multiplying integers; a tie
|
||||||
|
goes to distance. ``done`` is floored and capped at its ``target``.
|
||||||
|
"""
|
||||||
|
distance_target = round(MIN_RUN_DISTANCE_KM * 1000)
|
||||||
|
time_target = MIN_WORKOUT_DURATION_MINUTES * 60
|
||||||
|
distance_done = min(int(max(metres, 0.0)), distance_target)
|
||||||
|
time_done = min(int(max(moving_seconds, 0.0)), time_target)
|
||||||
|
if distance_done * time_target >= time_done * distance_target:
|
||||||
|
done, target = distance_done, distance_target
|
||||||
|
else:
|
||||||
|
done, target = time_done, time_target
|
||||||
|
return (done, target) if done > 0 else None
|
||||||
|
|
||||||
|
|
||||||
|
def progress_row(for_day: str, done: int, target: int) -> dict[str, Any] | None:
|
||||||
|
"""The unsigned progress row; ``None`` when nothing was done."""
|
||||||
|
if done <= 0:
|
||||||
|
return None
|
||||||
|
return {
|
||||||
|
"kind": "progress",
|
||||||
|
"entry_id": f"progress:{for_day}:{done}:{target}",
|
||||||
|
"day": for_day,
|
||||||
|
"amount": 0,
|
||||||
|
"detail": {
|
||||||
|
"source": SOURCE,
|
||||||
|
"for_day": for_day,
|
||||||
|
"done": str(done),
|
||||||
|
"target": str(target),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def record_progress(for_day: str, metres: float, moving_seconds: float) -> None:
|
||||||
|
"""Append the day's progress row; never raises, never changes a verdict.
|
||||||
|
|
||||||
|
Call only for a day verified from RunnerUp TCX data and judged too short.
|
||||||
|
A row that cannot be signed or written is logged at warning or above by
|
||||||
|
``append_rows``; any other failure is logged here.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
pair = progress_pair(metres, moving_seconds)
|
||||||
|
row = progress_row(for_day, *pair) if pair is not None else None
|
||||||
|
if row is not None:
|
||||||
|
append_rows([row])
|
||||||
|
except Exception: # pylint: disable=broad-exception-caught # a progress row must never change the verdict
|
||||||
|
_logger.exception(
|
||||||
|
"Could not write the progress row for %s; the workout verdict is unchanged",
|
||||||
|
for_day,
|
||||||
|
)
|
||||||
@ -15,6 +15,7 @@ import logging
|
|||||||
from typing import TYPE_CHECKING, Any
|
from typing import TYPE_CHECKING, Any
|
||||||
|
|
||||||
from screen_locker._log_mixin import write_signed_entry
|
from screen_locker._log_mixin import write_signed_entry
|
||||||
|
from screen_locker._progress_row import record_progress
|
||||||
from screen_locker._walk_tcx import activity_day, activity_shortfall
|
from screen_locker._walk_tcx import activity_day, activity_shortfall
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
@ -103,6 +104,7 @@ class RunnerUpBackfillMixin:
|
|||||||
date_str,
|
date_str,
|
||||||
activity_shortfall(day),
|
activity_shortfall(day),
|
||||||
)
|
)
|
||||||
|
record_progress(date_str, day.metres, day.moving_seconds)
|
||||||
return False
|
return False
|
||||||
workout_data: dict[str, Any] = {
|
workout_data: dict[str, Any] = {
|
||||||
"type": "runnerup_verified",
|
"type": "runnerup_verified",
|
||||||
|
|||||||
@ -17,6 +17,7 @@ from screen_locker._constants import (
|
|||||||
RUNNERUP_WEBDAV_DIRS,
|
RUNNERUP_WEBDAV_DIRS,
|
||||||
)
|
)
|
||||||
from screen_locker._day import today_str
|
from screen_locker._day import today_str
|
||||||
|
from screen_locker._progress_row import record_progress
|
||||||
from screen_locker._runnerup_backfill import RunnerUpBackfillMixin
|
from screen_locker._runnerup_backfill import RunnerUpBackfillMixin
|
||||||
from screen_locker._runnerup_db import RunnerUpDbMixin
|
from screen_locker._runnerup_db import RunnerUpDbMixin
|
||||||
from screen_locker._runnerup_tcx import RunnerUpTcxMixin
|
from screen_locker._runnerup_tcx import RunnerUpTcxMixin
|
||||||
@ -132,6 +133,8 @@ class RunnerUpVerificationMixin(
|
|||||||
day = activity_day(activities)
|
day = activity_day(activities)
|
||||||
if day.qualifies:
|
if day.qualifies:
|
||||||
return "verified", day.message()
|
return "verified", day.message()
|
||||||
|
# Verified TCX data, real but short: say how far it got (inert row).
|
||||||
|
record_progress(today, day.metres, day.moving_seconds)
|
||||||
return "too_short", activity_shortfall(day)
|
return "too_short", activity_shortfall(day)
|
||||||
|
|
||||||
def _validate_runnerup_data(self, data: dict[str, Any]) -> tuple[str, str]:
|
def _validate_runnerup_data(self, data: dict[str, Any]) -> tuple[str, str]:
|
||||||
|
|||||||
83
screen_locker/tests/test_progress_pair.py
Normal file
83
screen_locker/tests/test_progress_pair.py
Normal file
@ -0,0 +1,83 @@
|
|||||||
|
"""The pure part: which fraction leads, in integers, capped, never a float."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from fractions import Fraction
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from screen_locker._constants import MIN_RUN_DISTANCE_KM, MIN_WORKOUT_DURATION_MINUTES
|
||||||
|
from screen_locker._progress_row import progress_pair, progress_row
|
||||||
|
|
||||||
|
_METRES = round(MIN_RUN_DISTANCE_KM * 1000)
|
||||||
|
_SECONDS = MIN_WORKOUT_DURATION_MINUTES * 60
|
||||||
|
|
||||||
|
|
||||||
|
class TestPair:
|
||||||
|
"""progress_pair picks the larger fraction and expresses it in integers."""
|
||||||
|
|
||||||
|
def test_distance_leads(self) -> None:
|
||||||
|
"""1750 m (1/2) beats 300 s (1/6): metres over the metre bar."""
|
||||||
|
assert progress_pair(1750.0, 300.0) == (1750, _METRES)
|
||||||
|
|
||||||
|
def test_time_leads(self) -> None:
|
||||||
|
"""1200 s (2/3) beats 1500 m: seconds over the second bar."""
|
||||||
|
assert progress_pair(1500.0, 1200.0) == (1200, _SECONDS)
|
||||||
|
|
||||||
|
def test_a_tie_goes_to_distance(self) -> None:
|
||||||
|
"""Equal fractions are one answer, and it is the distance form."""
|
||||||
|
assert progress_pair(_METRES / 2, _SECONDS / 2) == (_METRES // 2, _METRES)
|
||||||
|
|
||||||
|
def test_done_is_floored(self) -> None:
|
||||||
|
"""Fractions of a metre or second never round up."""
|
||||||
|
assert progress_pair(1750.9, 0.0) == (1750, _METRES)
|
||||||
|
assert progress_pair(0.0, 599.99) == (599, _SECONDS)
|
||||||
|
|
||||||
|
def test_done_is_capped_at_the_bar(self) -> None:
|
||||||
|
"""Past the bar is the bar, never beyond."""
|
||||||
|
assert progress_pair(9000.0, 10.0) == (_METRES, _METRES)
|
||||||
|
assert progress_pair(1.0, 9000.0) == (_SECONDS, _SECONDS)
|
||||||
|
|
||||||
|
def test_nothing_done_is_no_pair(self) -> None:
|
||||||
|
"""Zero (or less than a whole unit) is no progress."""
|
||||||
|
assert progress_pair(0.0, 0.0) is None
|
||||||
|
assert progress_pair(0.4, 0.9) is None
|
||||||
|
|
||||||
|
def test_the_pair_is_the_larger_capped_fraction(self) -> None:
|
||||||
|
"""Over a grid: done<=target and done/target is the max of the two fractions."""
|
||||||
|
steps = (0, 1, 499, 1750, 3499, 3500, 9000)
|
||||||
|
for metres in steps:
|
||||||
|
for seconds in (*steps, 1799, 1800):
|
||||||
|
pair = progress_pair(float(metres), float(seconds))
|
||||||
|
by_distance = Fraction(min(metres, _METRES), _METRES)
|
||||||
|
by_time = Fraction(min(seconds, _SECONDS), _SECONDS)
|
||||||
|
if pair is None:
|
||||||
|
assert not max(by_distance, by_time)
|
||||||
|
continue
|
||||||
|
done, target = pair
|
||||||
|
assert 0 < done <= target
|
||||||
|
assert Fraction(done, target) == max(by_distance, by_time)
|
||||||
|
|
||||||
|
|
||||||
|
class TestRow:
|
||||||
|
"""progress_row is exactly the agreed contract."""
|
||||||
|
|
||||||
|
def test_the_contract(self) -> None:
|
||||||
|
"""Every key and every string, nothing else."""
|
||||||
|
assert progress_row("2026-11-22", 1750, 3500) == {
|
||||||
|
"kind": "progress",
|
||||||
|
"entry_id": "progress:2026-11-22:1750:3500",
|
||||||
|
"day": "2026-11-22",
|
||||||
|
"amount": 0,
|
||||||
|
"detail": {
|
||||||
|
"source": "workout",
|
||||||
|
"for_day": "2026-11-22",
|
||||||
|
"done": "1750",
|
||||||
|
"target": "3500",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("bad", [(0, 3500), (-1, 3500)])
|
||||||
|
def test_nonpositive_done_is_refused(self, bad: tuple[int, int]) -> None:
|
||||||
|
"""No row for zero done."""
|
||||||
|
assert progress_row("2026-11-22", *bad) is None
|
||||||
238
screen_locker/tests/test_progress_row_flow.py
Normal file
238
screen_locker/tests/test_progress_row_flow.py
Normal file
@ -0,0 +1,238 @@
|
|||||||
|
"""A short verified RunnerUp day leaves a signed "progress" row in the ledger.
|
||||||
|
|
||||||
|
The row is inert today (its reader ships in a later ``earned_time``): these
|
||||||
|
tests pin that it is written, signed, and that nothing else moves.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
from typing import TYPE_CHECKING, Any
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import earned_time
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from screen_locker import _progress_row
|
||||||
|
from screen_locker._log_mixin import write_signed_entry
|
||||||
|
from screen_locker._workout_ledger import ledger_path
|
||||||
|
from screen_locker.tests._activity_helpers import DAY, Verifier, drop, tcx, verify
|
||||||
|
from screen_locker.tests._earned_fixtures import KEY, signing_key
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Iterator
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
_PROGRESS_KEYS = {"kind", "entry_id", "day", "amount", "detail", "hmac"}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(name="verifier")
|
||||||
|
def verifier_fixture(tmp_path: Path) -> Verifier:
|
||||||
|
"""A Verifier reading a temporary drop directory."""
|
||||||
|
drop_dir = tmp_path / "drop"
|
||||||
|
drop_dir.mkdir()
|
||||||
|
return Verifier(drop_dir)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True, name="key")
|
||||||
|
def key_fixture(tmp_path: Path) -> Iterator[Path]:
|
||||||
|
"""A signing key, so the ledger writes (the suite default has none)."""
|
||||||
|
with signing_key(tmp_path) as path:
|
||||||
|
yield path
|
||||||
|
|
||||||
|
|
||||||
|
def rows() -> list[dict[str, Any]]:
|
||||||
|
"""The ledger's rows, or none when it was never written."""
|
||||||
|
if not ledger_path().exists():
|
||||||
|
return []
|
||||||
|
return json.loads(ledger_path().read_text())["entries"]
|
||||||
|
|
||||||
|
|
||||||
|
def run(verifier: Verifier, start: str, *, moving_min: float, metres: float) -> None:
|
||||||
|
"""Drop one export for the test day."""
|
||||||
|
drop(
|
||||||
|
verifier.folder,
|
||||||
|
start.replace(":", "-") + "-00",
|
||||||
|
"_Running",
|
||||||
|
tcx("Running", start, moving_min=moving_min, metres=metres),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class TestWritten:
|
||||||
|
"""What a too-short verified day writes."""
|
||||||
|
|
||||||
|
def test_1750_m_against_3500_m_writes_the_distance_form(
|
||||||
|
self, verifier: Verifier
|
||||||
|
) -> None:
|
||||||
|
"""Half the distance bar: ``progress:<day>:1750:3500``, signed and valid."""
|
||||||
|
run(verifier, "07:00", moving_min=5, metres=1750)
|
||||||
|
result = verify(verifier)
|
||||||
|
assert result is not None
|
||||||
|
assert result[0] == "too_short"
|
||||||
|
(row,) = rows()
|
||||||
|
assert set(row) == _PROGRESS_KEYS
|
||||||
|
assert row["kind"] == "progress"
|
||||||
|
assert row["entry_id"] == f"progress:{DAY}:1750:3500"
|
||||||
|
assert row["day"] == DAY
|
||||||
|
assert row["amount"] is not None
|
||||||
|
assert not row["amount"]
|
||||||
|
assert row["detail"] == {
|
||||||
|
"source": "workout",
|
||||||
|
"for_day": DAY,
|
||||||
|
"done": "1750",
|
||||||
|
"target": "3500",
|
||||||
|
}
|
||||||
|
assert earned_time.verified(row, KEY)
|
||||||
|
|
||||||
|
def test_20_min_moving_with_little_distance_writes_the_seconds_form(
|
||||||
|
self, verifier: Verifier
|
||||||
|
) -> None:
|
||||||
|
"""Time leads: done is the moving seconds, target the time bar in seconds."""
|
||||||
|
run(verifier, "07:00", moving_min=20, metres=1500)
|
||||||
|
result = verify(verifier)
|
||||||
|
assert result is not None
|
||||||
|
assert result[0] == "too_short"
|
||||||
|
(row,) = rows()
|
||||||
|
assert row["entry_id"] == f"progress:{DAY}:1200:1800"
|
||||||
|
assert row["detail"]["done"] == "1200"
|
||||||
|
assert row["detail"]["target"] == "1800"
|
||||||
|
assert earned_time.verified(row, KEY)
|
||||||
|
|
||||||
|
def test_two_short_runs_sum(self, verifier: Verifier) -> None:
|
||||||
|
"""900 m + 850 m in one day is one progress of 1750 m."""
|
||||||
|
run(verifier, "07:00", moving_min=3, metres=900)
|
||||||
|
run(verifier, "18:00", moving_min=3, metres=850)
|
||||||
|
result = verify(verifier)
|
||||||
|
assert result is not None
|
||||||
|
assert result[0] == "too_short"
|
||||||
|
(row,) = rows()
|
||||||
|
assert row["entry_id"] == f"progress:{DAY}:1750:3500"
|
||||||
|
|
||||||
|
def test_a_second_short_run_writes_a_new_row_and_never_the_same_id_twice(
|
||||||
|
self, verifier: Verifier
|
||||||
|
) -> None:
|
||||||
|
"""More done is a new id; the same done again writes nothing."""
|
||||||
|
run(verifier, "07:00", moving_min=3, metres=900)
|
||||||
|
verify(verifier)
|
||||||
|
verify(verifier)
|
||||||
|
assert [r["entry_id"] for r in rows()] == [f"progress:{DAY}:900:3500"]
|
||||||
|
run(verifier, "18:00", moving_min=3, metres=850)
|
||||||
|
verify(verifier)
|
||||||
|
verify(verifier)
|
||||||
|
assert [r["entry_id"] for r in rows()] == [
|
||||||
|
f"progress:{DAY}:900:3500",
|
||||||
|
f"progress:{DAY}:1750:3500",
|
||||||
|
]
|
||||||
|
|
||||||
|
def test_the_weekly_scan_writes_it_for_its_own_day(
|
||||||
|
self, verifier: Verifier, tmp_path: Path
|
||||||
|
) -> None:
|
||||||
|
"""The backfill path judges the same too-short day and files it under it."""
|
||||||
|
run(verifier, "07:00", moving_min=5, metres=1750)
|
||||||
|
assert verifier._try_fill_runnerup_for_date(DAY, tmp_path / "log.json") is False
|
||||||
|
(row,) = rows()
|
||||||
|
assert row["entry_id"] == f"progress:{DAY}:1750:3500"
|
||||||
|
|
||||||
|
|
||||||
|
class TestNotWritten:
|
||||||
|
"""The days that must leave no progress row."""
|
||||||
|
|
||||||
|
def test_a_qualifying_day_writes_the_credit_and_no_progress_row(
|
||||||
|
self, verifier: Verifier, tmp_path: Path
|
||||||
|
) -> None:
|
||||||
|
"""A day over the bar credits as before; the ledger holds the credit only."""
|
||||||
|
run(verifier, "07:00", moving_min=30, metres=4000)
|
||||||
|
result = verify(verifier)
|
||||||
|
assert result is not None
|
||||||
|
assert result[0] == "verified"
|
||||||
|
assert not rows()
|
||||||
|
log = tmp_path / "log.json"
|
||||||
|
assert verifier._try_fill_runnerup_for_date(DAY, log) is True
|
||||||
|
assert [r["kind"] for r in rows()] == ["credit"]
|
||||||
|
|
||||||
|
def test_manual_and_stronglifts_days_write_no_progress_row(
|
||||||
|
self, tmp_path: Path
|
||||||
|
) -> None:
|
||||||
|
"""Only verified RunnerUp data has a "too short"; the others are all-or-nothing."""
|
||||||
|
log = tmp_path / "log.json"
|
||||||
|
write_signed_entry(
|
||||||
|
log,
|
||||||
|
DAY,
|
||||||
|
{"type": "manual_workout", "start_time": "17:00", "end_time": "18:00"},
|
||||||
|
)
|
||||||
|
write_signed_entry(log, DAY, {"type": "phone_verified", "workout_id": "p:1"})
|
||||||
|
assert rows()
|
||||||
|
assert {r["kind"] for r in rows()} == {"credit"}
|
||||||
|
|
||||||
|
def test_an_unreadable_tcx_is_could_not_check_and_writes_nothing(
|
||||||
|
self, verifier: Verifier
|
||||||
|
) -> None:
|
||||||
|
"""Broken XML is "not_verified": no row, no guess."""
|
||||||
|
drop(verifier.folder, "07-00-00", "_Running", "<not-xml")
|
||||||
|
result = verify(verifier)
|
||||||
|
assert result is not None
|
||||||
|
assert result[0] == "not_verified"
|
||||||
|
assert not rows()
|
||||||
|
|
||||||
|
def test_the_root_db_path_is_not_verified_data_and_writes_nothing(
|
||||||
|
self, verifier: Verifier
|
||||||
|
) -> None:
|
||||||
|
"""The rooted-DB fallback judges a dict, never a TCX: no row."""
|
||||||
|
row = {"sport": 0, "duration_seconds": 10 * 60, "distance_m": 2000.0}
|
||||||
|
assert verifier._validate_runnerup_data(row)[0] == "too_short"
|
||||||
|
assert not rows()
|
||||||
|
|
||||||
|
|
||||||
|
class TestFailureModes:
|
||||||
|
"""A row that cannot be written never changes the verdict."""
|
||||||
|
|
||||||
|
def test_no_signing_key_keeps_the_verdict_and_warns(
|
||||||
|
self,
|
||||||
|
verifier: Verifier,
|
||||||
|
key: Path,
|
||||||
|
caplog: pytest.LogCaptureFixture,
|
||||||
|
) -> None:
|
||||||
|
"""No key: the same too_short, one warning, no ledger."""
|
||||||
|
key.unlink()
|
||||||
|
run(verifier, "07:00", moving_min=5, metres=1750)
|
||||||
|
with caplog.at_level(logging.WARNING):
|
||||||
|
result = verify(verifier)
|
||||||
|
assert result is not None
|
||||||
|
assert result[0] == "too_short"
|
||||||
|
assert not rows()
|
||||||
|
assert any(r.levelno >= logging.WARNING for r in caplog.records)
|
||||||
|
|
||||||
|
def test_an_unexpected_writer_error_keeps_the_verdict_and_logs(
|
||||||
|
self, verifier: Verifier, caplog: pytest.LogCaptureFixture
|
||||||
|
) -> None:
|
||||||
|
"""Whatever the writer raises, the verdict is untouched and the error logged."""
|
||||||
|
run(verifier, "07:00", moving_min=5, metres=1750)
|
||||||
|
before = verify(verifier)
|
||||||
|
with (
|
||||||
|
patch.object(_progress_row, "append_rows", side_effect=RuntimeError("x")),
|
||||||
|
caplog.at_level(logging.WARNING),
|
||||||
|
):
|
||||||
|
after = verify(verifier)
|
||||||
|
assert after == before
|
||||||
|
assert "progress row" in caplog.text
|
||||||
|
|
||||||
|
|
||||||
|
class TestNothingShowsTheBars:
|
||||||
|
"""No message, log line or print carries a threshold."""
|
||||||
|
|
||||||
|
def test_no_threshold_in_logs_or_output(
|
||||||
|
self,
|
||||||
|
verifier: Verifier,
|
||||||
|
tmp_path: Path,
|
||||||
|
caplog: pytest.LogCaptureFixture,
|
||||||
|
capsys: pytest.CaptureFixture[str],
|
||||||
|
) -> None:
|
||||||
|
"""The bars live only inside the signed row."""
|
||||||
|
run(verifier, "07:00", moving_min=5, metres=1750)
|
||||||
|
with caplog.at_level(logging.DEBUG):
|
||||||
|
verify(verifier)
|
||||||
|
logged = "\n".join(r.getMessage() for r in caplog.records)
|
||||||
|
seen = logged.replace(str(tmp_path), "") + capsys.readouterr().out
|
||||||
|
for number in ("3500", "1800", "1500", "3325", "3.5", "25"):
|
||||||
|
assert number not in seen
|
||||||
136
screen_locker/tests/test_progress_row_readers.py
Normal file
136
screen_locker/tests/test_progress_row_readers.py
Normal file
@ -0,0 +1,136 @@
|
|||||||
|
"""Differential: progress rows in the workout ledger change no existing reader."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import date, datetime, time
|
||||||
|
import json
|
||||||
|
from typing import TYPE_CHECKING, Any
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
import earned_time
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from screen_locker import _earned, _progress_row
|
||||||
|
from screen_locker._shutdown_base import base_minutes
|
||||||
|
from screen_locker._shutdown_target import gather
|
||||||
|
from screen_locker._workout_ledger import append_rows, credit_row, ledger_path
|
||||||
|
from screen_locker.tests._earned_fixtures import KEY, signing_key
|
||||||
|
from screen_locker.tests.conftest import create_locker
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Iterator
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
_DAY = date(2026, 10, 10)
|
||||||
|
_ISO = _DAY.isoformat()
|
||||||
|
_FLAT = {"leetcode": False, "reading": False, "anki": False, "tutor": False}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True, name="key")
|
||||||
|
def key_fixture(tmp_path: Path) -> Iterator[Path]:
|
||||||
|
"""A signing key so the ledger can be written and read."""
|
||||||
|
with signing_key(tmp_path) as path:
|
||||||
|
yield path
|
||||||
|
|
||||||
|
|
||||||
|
def _noon() -> float:
|
||||||
|
return datetime.combine(_DAY, time(12, 0)).astimezone().timestamp()
|
||||||
|
|
||||||
|
|
||||||
|
def _log(tmp_path: Path) -> Path:
|
||||||
|
log = tmp_path / "log.json"
|
||||||
|
entry = {
|
||||||
|
"workout_data": {"type": "runnerup_verified", "completed_at": _noon()},
|
||||||
|
"timestamp": "2026-10-10T20:00:00+00:00",
|
||||||
|
}
|
||||||
|
log.write_text(json.dumps({_ISO: [entry]}))
|
||||||
|
return log
|
||||||
|
|
||||||
|
|
||||||
|
def _readers(tmp_path: Path, log: Path) -> dict[str, Any]:
|
||||||
|
"""Every existing reader of the workout ledger, side by side."""
|
||||||
|
workout = earned_time.WORKOUT
|
||||||
|
with patch("screen_locker._shutdown_target.gate_answers", return_value=_FLAT):
|
||||||
|
target = gather(_DAY, log)
|
||||||
|
return {
|
||||||
|
"units": earned_time.credit_units(
|
||||||
|
workout, ledger_path(), _earned.HMAC_KEY_FILE, _DAY
|
||||||
|
),
|
||||||
|
"first": earned_time.first_credit_at(
|
||||||
|
workout, ledger_path(), _earned.HMAC_KEY_FILE, _DAY
|
||||||
|
),
|
||||||
|
"first_credit_time": _earned.first_credit_time(workout, _DAY),
|
||||||
|
"target_minutes": target.minutes,
|
||||||
|
"first_done_at": target.first_done_at,
|
||||||
|
"workout_term": target.resolution.term("workout").answer,
|
||||||
|
"base": base_minutes(_DAY),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _credit_result(mock_tk: MagicMock, tmp_path: Path) -> tuple[Any, ...]:
|
||||||
|
"""The workout credit mixin's outcome over an in-memory shutdown config."""
|
||||||
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
|
locker.workout_data = {"type": "runnerup_verified"}
|
||||||
|
config = {"value": (1200, 1200, 300)}
|
||||||
|
|
||||||
|
def write(mw: int, ts: int, morning: int, *, restore: bool) -> bool:
|
||||||
|
assert restore
|
||||||
|
config["value"] = (mw, ts, morning)
|
||||||
|
return True
|
||||||
|
|
||||||
|
object.__setattr__(
|
||||||
|
locker, "_read_shutdown_config", MagicMock(side_effect=lambda: config["value"])
|
||||||
|
)
|
||||||
|
object.__setattr__(locker, "_write_shutdown_config", MagicMock(side_effect=write))
|
||||||
|
with (
|
||||||
|
patch("screen_locker._shutdown.plan_absorb", side_effect=lambda m: (m, 0)),
|
||||||
|
patch("screen_locker._shutdown.save_lift"),
|
||||||
|
patch("screen_locker._workout_credit.is_rest_day", return_value=False),
|
||||||
|
patch("screen_locker._workout_credit.count_weekly_workouts", return_value=3),
|
||||||
|
patch("screen_locker._workout_credit._credit_notify.notify_workout_credit"),
|
||||||
|
):
|
||||||
|
result = locker._apply_credit_for_written_entry([])
|
||||||
|
return (result, config["value"])
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.usefixtures("pre_ladder")
|
||||||
|
def test_progress_rows_change_no_existing_reader(
|
||||||
|
tmp_path: Path, mock_tk: MagicMock, mock_sys_exit: MagicMock
|
||||||
|
) -> None:
|
||||||
|
"""Credit units, first credit, shutdown target/base and the credit mixin agree."""
|
||||||
|
del mock_sys_exit
|
||||||
|
log = _log(tmp_path)
|
||||||
|
entries = json.loads(log.read_text())[_ISO]
|
||||||
|
credit = credit_row(_ISO, entries, 0)
|
||||||
|
assert credit is not None
|
||||||
|
assert append_rows([credit]) == 1
|
||||||
|
without = _readers(tmp_path, log)
|
||||||
|
credited_without = _credit_result(mock_tk, tmp_path)
|
||||||
|
assert without["units"] == 1
|
||||||
|
|
||||||
|
for done in (600.0, 1200.0):
|
||||||
|
_progress_row.record_progress(_ISO, done / 2 * 3.5, done)
|
||||||
|
stored = json.loads(ledger_path().read_text())["entries"]
|
||||||
|
assert [r["kind"] for r in stored] == ["credit", "progress", "progress"]
|
||||||
|
|
||||||
|
assert _readers(tmp_path, log) == without
|
||||||
|
assert _credit_result(mock_tk, tmp_path) == credited_without
|
||||||
|
|
||||||
|
|
||||||
|
def test_progress_rows_alone_earn_no_credit(tmp_path: Path) -> None:
|
||||||
|
"""A ledger holding only progress rows has zero credit units and no first credit."""
|
||||||
|
del tmp_path
|
||||||
|
_progress_row.record_progress(_ISO, 1750.0, 300.0)
|
||||||
|
assert earned_time.verified(
|
||||||
|
json.loads(ledger_path().read_text())["entries"][0], KEY
|
||||||
|
)
|
||||||
|
workout = earned_time.WORKOUT
|
||||||
|
units = earned_time.credit_units(
|
||||||
|
workout, ledger_path(), _earned.HMAC_KEY_FILE, _DAY
|
||||||
|
)
|
||||||
|
assert units is not None
|
||||||
|
assert not units
|
||||||
|
assert (
|
||||||
|
earned_time.first_credit_at(workout, ledger_path(), _earned.HMAC_KEY_FILE, _DAY)
|
||||||
|
is None
|
||||||
|
)
|
||||||
Loading…
Reference in New Issue
Block a user