mirror of
https://github.com/kuhyx/screen-locker.git
synced 2026-11-28 18:49:06 +01:00
Compare commits
No commits in common. "c7a7593a5588a1a5029e13759d79140977207b14" and "e7bf74c3aa8ed6901dab31ed036946c324659395" have entirely different histories.
c7a7593a55
...
e7bf74c3aa
@ -1,105 +0,0 @@
|
||||
"""``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)
|
||||
|
||||
|
||||
# 2026-11-24 is the day the review is paid by its progress row (earned_time
|
||||
# 0.24); a finished simulated review must still add its 20 minutes there.
|
||||
@pytest.mark.parametrize("day", [_REVIEW_DAY, "2026-11-24"])
|
||||
def test_preview_review_sequence_adds_flat_review_minutes(
|
||||
day: str, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
"""C1/C4: a review adds its minutes, live == derived."""
|
||||
_run(monkeypatch, "--day", 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
|
||||
@ -15,7 +15,7 @@ import earned_time
|
||||
import sickdays
|
||||
|
||||
from screen_locker._ceiling import HARD_CEILING_MINUTES as HELPER_CEILING
|
||||
from screen_locker._earned import first_minutes, registry
|
||||
from screen_locker._earned import first_minutes
|
||||
from screen_locker._runnerup_verification import RunnerUpVerificationMixin
|
||||
from screen_locker._shutdown import ShutdownMixin
|
||||
from screen_locker._sick import is_sick
|
||||
@ -101,9 +101,7 @@ class SimShutdown(ShutdownMixin):
|
||||
elif name == earned_time.WORKOUT.name:
|
||||
self._adjust_shutdown_time_later()
|
||||
else:
|
||||
# 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)
|
||||
minutes = first_minutes(earned_time.earner(name), day)
|
||||
self._adjust_shutdown_time_by(minutes)
|
||||
self._apply_sick_floor()
|
||||
|
||||
|
||||
@ -99,7 +99,7 @@ def _simulate(args: argparse.Namespace, tmp: Path) -> None:
|
||||
eve = datetime.combine(day - timedelta(days=1), time(12)).astimezone()
|
||||
_say(f" declare: {declare(day, now=eve, path=rest_file).reason}")
|
||||
done = {n for n in (args.done or "").split(",") if n}
|
||||
flat = {e.name: e.name in done for e in _earned.flat_earners(day)}
|
||||
flat = {e.name: e.name in done for e in _earned.flat_earners()}
|
||||
first = stamp(day, args.first_done) if args.first_done else None
|
||||
logged = _grace_floor.workout_done_at(log, day)
|
||||
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)["GRACE_STATE_FILE"] = tmp / "grace_floor.json"
|
||||
use_temp_pool(tmp)
|
||||
done = {e.name: False for e in _earned.flat_earners(day)}
|
||||
done = {e.name: False for e in _earned.flat_earners()}
|
||||
sim = SimShutdown(derive(DayInputs(day, done)).minutes)
|
||||
_say(f"[sequence] {day} start {hhmm(sim.config[0])} (nothing done, not sick)")
|
||||
workouts, first = 0, None
|
||||
@ -150,15 +150,8 @@ 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:
|
||||
"""Print the requested preview. Returns 0; exits 2 on an unknown step."""
|
||||
"""Print the requested preview. Returns 0."""
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
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")
|
||||
@ -185,9 +178,6 @@ def main() -> int:
|
||||
_report(f"today {label}", derive(replace(inputs, sick_day=sick)))
|
||||
return 0
|
||||
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)}")
|
||||
with tempfile.TemporaryDirectory(prefix="preview_shutdown_") as raw:
|
||||
if args.sequence:
|
||||
|
||||
Loading…
Reference in New Issue
Block a user