Preview a review credit by the day's registry

preview_shutdown --sequence review@HH:MM raised KeyError: the review
(ReviewEarner) joins the registry only through earners_for(day) from
REVIEW_FROM, while the sim looked names up in the static EARNERS tuple.
The sim now looks earners up in the simulated day's registry, the done
maps come from that day's flat earners, and a step that is no earner on
that day is an argparse usage error (exit 2), not a traceback.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Krzysztof Rudnicki 2026-11-23 13:43:07 +01:00
parent e7bf74c3aa
commit acf69becc7
3 changed files with 119 additions and 5 deletions

View File

@ -0,0 +1,102 @@
"""``preview_shutdown --sequence`` simulates a review credit (earned_time 0.23).
The review is a top-up that joins the registry only from ``REVIEW_FROM``
(``earners_for(day)``), so a lookup in the static ``EARNERS`` tuple raised
``KeyError: 'review'``. The preview must look earners up in the simulated
day's registry, and reject a name not in force that day with a usage error.
"""
from __future__ import annotations
from datetime import timedelta
import sys
import earned_time
import pytest
from screen_locker import _earned, _grace_floor, _shutdown, _sick_floor
from screen_locker._earned import hhmm
from scripts import preview_shutdown
_REVIEW_DAY = earned_time.REVIEW_FROM.isoformat()
# The last day before the review joined the registry.
_EVE = (earned_time.REVIEW_FROM - timedelta(days=1)).isoformat()
# conftest stubs ``sys.exit`` process-wide; argparse's usage error needs the
# real one, captured at import (before the autouse stub).
_real_exit = sys.exit
@pytest.fixture(autouse=True)
def _restore_patched_globals(monkeypatch: pytest.MonkeyPatch) -> None:
"""The script rebinds module globals with ``vars()``; undo them afterwards."""
for module in (_grace_floor, _shutdown, _sick_floor):
for name in ("today_str", "GRACE_STATE_FILE", "sick_target"):
if name in vars(module):
monkeypatch.setattr(module, name, vars(module)[name])
for name, module in tuple(sys.modules.items()):
if name.startswith("sickdays.") and "resolve_paths" in vars(module):
monkeypatch.setattr(module, "resolve_paths", vars(module)["resolve_paths"])
monkeypatch.setattr(_earned, "LEDGER_HOME", _earned.LEDGER_HOME)
monkeypatch.setattr(sys, "exit", _real_exit)
def _run(monkeypatch: pytest.MonkeyPatch, *argv: str) -> int:
monkeypatch.setattr(sys, "argv", ["preview_shutdown", *argv])
return preview_shutdown.main()
def _lines(text: str) -> dict[str, str]:
"""``step -> rest`` for each `` name@HH:MM: ...`` sequence line."""
out = {}
for line in text.splitlines():
step, sep, rest = line.strip().partition(": config ")
if sep:
out[step] = rest
return out
def _start(text: str) -> int:
line = next(x for x in text.splitlines() if x.startswith("[sequence]"))
hours, minutes = line.split(" start ")[1].split()[0].split(":")
return int(hours) * 60 + int(minutes)
def test_preview_review_sequence_adds_flat_review_minutes(
monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
"""C1: a review on its first day adds its flat minutes, live == derived."""
_run(monkeypatch, "--day", _REVIEW_DAY, "--sequence", "review@21:00")
out = capsys.readouterr().out
want = hhmm(_start(out) + earned_time.REVIEW_SHUTDOWN_MINUTES)
assert _lines(out) == {"review@21:00": f"{want} (derived {want})"}
def test_preview_review_sequence_stacks_with_leetcode(
monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
"""C2: review then LeetCode stack, and every step matches the derivation."""
steps = "review@21:00,leetcode@21:30"
_run(monkeypatch, "--day", _REVIEW_DAY, "--sequence", steps)
out = capsys.readouterr().out
after_review = _start(out) + earned_time.REVIEW_SHUTDOWN_MINUTES
after_leetcode = after_review + earned_time.earner("leetcode").shutdown_minutes
first, second = hhmm(after_review), hhmm(after_leetcode)
assert _lines(out) == {
"review@21:00": f"{first} (derived {first})",
"leetcode@21:30": f"{second} (derived {second})",
}
assert "MISMATCH" not in out
def test_preview_review_sequence_before_review_from_is_a_usage_error(
monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
"""C3: the day before the review existed exits 2 with a one-line reason."""
with pytest.raises(SystemExit) as raised:
_run(monkeypatch, "--day", _EVE, "--sequence", "review@21:00")
assert raised.value.code == 2
err = capsys.readouterr().err
assert "review" in err
assert _EVE in err
assert "Traceback" not in err
assert "KeyError" not in err

View File

@ -15,7 +15,7 @@ import earned_time
import sickdays import sickdays
from screen_locker._ceiling import HARD_CEILING_MINUTES as HELPER_CEILING from screen_locker._ceiling import HARD_CEILING_MINUTES as HELPER_CEILING
from screen_locker._earned import first_minutes from screen_locker._earned import first_minutes, registry
from screen_locker._runnerup_verification import RunnerUpVerificationMixin from screen_locker._runnerup_verification import RunnerUpVerificationMixin
from screen_locker._shutdown import ShutdownMixin from screen_locker._shutdown import ShutdownMixin
from screen_locker._sick import is_sick from screen_locker._sick import is_sick
@ -101,7 +101,9 @@ class SimShutdown(ShutdownMixin):
elif name == earned_time.WORKOUT.name: elif name == earned_time.WORKOUT.name:
self._adjust_shutdown_time_later() self._adjust_shutdown_time_later()
else: else:
minutes = first_minutes(earned_time.earner(name), day) # The registry in force on ``day``: the review joins it only from
# ``REVIEW_FROM``, so the static ``EARNERS`` tuple misses it.
minutes = first_minutes(earned_time.earner(name, registry(day)), day)
self._adjust_shutdown_time_by(minutes) self._adjust_shutdown_time_by(minutes)
self._apply_sick_floor() self._apply_sick_floor()

View File

@ -99,7 +99,7 @@ def _simulate(args: argparse.Namespace, tmp: Path) -> None:
eve = datetime.combine(day - timedelta(days=1), time(12)).astimezone() eve = datetime.combine(day - timedelta(days=1), time(12)).astimezone()
_say(f" declare: {declare(day, now=eve, path=rest_file).reason}") _say(f" declare: {declare(day, now=eve, path=rest_file).reason}")
done = {n for n in (args.done or "").split(",") if n} done = {n for n in (args.done or "").split(",") if n}
flat = {e.name: e.name in done for e in _earned.flat_earners()} flat = {e.name: e.name in done for e in _earned.flat_earners(day)}
first = stamp(day, args.first_done) if args.first_done else None first = stamp(day, args.first_done) if args.first_done else None
logged = _grace_floor.workout_done_at(log, day) logged = _grace_floor.workout_done_at(log, day)
times = [t for t in (first, logged) if t is not None] times = [t for t in (first, logged) if t is not None]
@ -122,7 +122,7 @@ def _sequence(args: argparse.Namespace, tmp: Path) -> None:
vars(module)["today_str"] = lambda: args.day vars(module)["today_str"] = lambda: args.day
vars(module)["GRACE_STATE_FILE"] = tmp / "grace_floor.json" vars(module)["GRACE_STATE_FILE"] = tmp / "grace_floor.json"
use_temp_pool(tmp) use_temp_pool(tmp)
done = {e.name: False for e in _earned.flat_earners()} done = {e.name: False for e in _earned.flat_earners(day)}
sim = SimShutdown(derive(DayInputs(day, done)).minutes) sim = SimShutdown(derive(DayInputs(day, done)).minutes)
_say(f"[sequence] {day} start {hhmm(sim.config[0])} (nothing done, not sick)") _say(f"[sequence] {day} start {hhmm(sim.config[0])} (nothing done, not sick)")
workouts, first = 0, None workouts, first = 0, None
@ -150,8 +150,15 @@ def _sequence(args: argparse.Namespace, tmp: Path) -> None:
) )
def unknown_step(sequence: str, day: date) -> str | None:
"""The first ``--sequence`` name that is not an earner in force on ``day``."""
known = {e.name for e in _earned.registry(day)} | {SICK_STEP}
names = (step.partition("@")[0] for step in sequence.split(","))
return next((name for name in names if name not in known), None)
def main() -> int: def main() -> int:
"""Print the requested preview. Returns 0.""" """Print the requested preview. Returns 0; exits 2 on an unknown step."""
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--day", default=None, help="simulate this day (YYYY-MM-DD)") parser.add_argument("--day", default=None, help="simulate this day (YYYY-MM-DD)")
parser.add_argument("--walk", help="moving minutes per walk leg, e.g. 25,20") parser.add_argument("--walk", help="moving minutes per walk leg, e.g. 25,20")
@ -178,6 +185,9 @@ def main() -> int:
_report(f"today {label}", derive(replace(inputs, sick_day=sick))) _report(f"today {label}", derive(replace(inputs, sick_day=sick)))
return 0 return 0
day = date.fromisoformat(args.day) day = date.fromisoformat(args.day)
unknown = unknown_step(args.sequence, day) if args.sequence else None
if unknown is not None:
parser.error(f"{unknown!r} is not an earner on {day}")
_say(f" ladder in force on {day}: {earned_time.on_ladder(day)}") _say(f" ladder in force on {day}: {earned_time.on_ladder(day)}")
with tempfile.TemporaryDirectory(prefix="preview_shutdown_") as raw: with tempfile.TemporaryDirectory(prefix="preview_shutdown_") as raw:
if args.sequence: if args.sequence: