mirror of
https://github.com/kuhyx/screen-locker.git
synced 2026-11-20 02:14:28 +01:00
Drop gaming from credit toast and poke
Pin earned-time-v0.22.0. The toast and the poke reply show only the shutdown gain; gaming_budget_minutes leaves the reply and the phone app's result line (an older PC's field is ignored). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WzxdWViGJJaqBKGr1Hbppr
This commit is contained in:
parent
8e52688138
commit
ad849aff02
@ -143,7 +143,7 @@ repos:
|
||||
# than merely an old one.
|
||||
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.12.0#subdirectory=gatelock
|
||||
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync
|
||||
- earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.21.0#subdirectory=earned_time
|
||||
- earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.22.0#subdirectory=earned_time
|
||||
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.3#subdirectory=freedays
|
||||
- sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.4#subdirectory=sickdays
|
||||
# Same pin as workout_app/tools/render_finish_chime.sh installs.
|
||||
@ -166,7 +166,7 @@ repos:
|
||||
# than merely an old one.
|
||||
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.12.0#subdirectory=gatelock
|
||||
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync
|
||||
- earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.21.0#subdirectory=earned_time
|
||||
- earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.22.0#subdirectory=earned_time
|
||||
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.3#subdirectory=freedays
|
||||
- sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.4#subdirectory=sickdays
|
||||
- mcp>=2,<3
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
# Workout poke: phone -> PC wire contract (v1)
|
||||
|
||||
The phone sends a finished StrongLifts session straight to the PC over the
|
||||
home LAN, so the credit (shutdown time, gaming budget, notification) lands in
|
||||
home LAN, so the credit (shutdown time, notification) lands in
|
||||
under a second instead of waiting for the GitHub/Firebase round trip. The
|
||||
normal sync push still runs in parallel; the PC dedups by record id, so a
|
||||
session that arrives both ways is credited once.
|
||||
@ -45,11 +45,13 @@ session that arrives both ways is credited once.
|
||||
|
||||
```json
|
||||
{"ok":<bool>,"credited":<bool>,"duplicate":<bool>,"sandbox":<bool>,
|
||||
"shutdown":"HH:MM"|null,"gaming_budget_minutes":<int|null>,"pc_ms":<int>,
|
||||
"shutdown":"HH:MM"|null,"pc_ms":<int>,
|
||||
"reason":"<sentence a human can act on>"}
|
||||
```
|
||||
|
||||
The phone must treat `shutdown` and `gaming_budget_minutes` as nullable.
|
||||
The phone must treat `shutdown` as nullable. `gaming_budget_minutes` was dropped
|
||||
when the gaming budget was removed (2026-11-16); a phone ignores it if an older
|
||||
PC still sends it.
|
||||
|
||||
Outcomes of a verified (200) request:
|
||||
|
||||
@ -64,8 +66,8 @@ Outcomes of a verified (200) request:
|
||||
Refusals are never 200. Besides the four checks above, the PC may answer
|
||||
`404` (wrong path), `405` (not POST), `411` (no Content-Length), `413` (body
|
||||
over 64 KiB) and `500` (internal error; the regular sync still credits). All
|
||||
of them carry the same JSON shape with `ok:false` and `shutdown` and
|
||||
`gaming_budget_minutes` both `null`. The PC answers a `413` without reading
|
||||
of them carry the same JSON shape with `ok:false` and `shutdown`
|
||||
`null`. The PC answers a `413` without reading
|
||||
the body, so the phone may see a connection reset instead of the reply.
|
||||
|
||||
## Shared fixture
|
||||
|
||||
@ -10,7 +10,7 @@ dependencies = [
|
||||
"gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.14.0#subdirectory=gatelock",
|
||||
"crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync",
|
||||
"freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.3#subdirectory=freedays",
|
||||
"earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.21.0#subdirectory=earned_time",
|
||||
"earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.22.0#subdirectory=earned_time",
|
||||
"holds @ git+https://github.com/kuhyx/utils@holds-v0.1.0#subdirectory=holds",
|
||||
"sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.4#subdirectory=sickdays",
|
||||
]
|
||||
|
||||
@ -4,7 +4,7 @@ bandit==1.9.4
|
||||
codespell==2.4.3
|
||||
coverage==7.17.3
|
||||
crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync
|
||||
earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.21.0#subdirectory=earned_time
|
||||
earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.22.0#subdirectory=earned_time
|
||||
freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.3#subdirectory=freedays
|
||||
gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.14.0#subdirectory=gatelock
|
||||
holds @ git+https://github.com/kuhyx/utils@holds-v0.1.0#subdirectory=holds
|
||||
|
||||
@ -6,11 +6,8 @@ that credits a workout ends in
|
||||
:meth:`~screen_locker._workout_credit.WorkoutCreditMixin._apply_credit_for_written_entry`,
|
||||
which calls :func:`notify_workout_credit` once per newly earned credit slot.
|
||||
|
||||
The gaming figure is ``earned_time.resolve`` over screen-locker's own answers
|
||||
(:func:`screen_locker._shutdown_target.gather` -- the same sum the daily reset
|
||||
writes), so no budget math lives here. steam-backlog-enforcer resolves the
|
||||
same registry with its own transports and holds a day's high-water mark, so
|
||||
its figure can sit above this one, never below on a normal day.
|
||||
The body shows the shutdown only: the gaming budget is gone (earned_time
|
||||
0.22.0), so there is no second figure to feel.
|
||||
|
||||
A notification is a courtesy, never part of crediting: any failure (no DBus,
|
||||
no notify-send, a hang) is logged at warning and swallowed.
|
||||
@ -22,52 +19,27 @@ from datetime import date
|
||||
import logging
|
||||
import shutil
|
||||
import subprocess
|
||||
from typing import TYPE_CHECKING, Final
|
||||
from typing import Final
|
||||
|
||||
from screen_locker._day import today_str
|
||||
from screen_locker._earned import hhmm, span
|
||||
from screen_locker._grace_floor import tonight_minutes
|
||||
from screen_locker._shutdown_target import gather
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
_logger: Final = logging.getLogger(__name__)
|
||||
|
||||
# textgate: glyphs + numbers (colour emoji are safe in the notification
|
||||
# daemon, unlike Tk). Was "Workout credited 💪" / "Shutdown 23:00 (+2h) ·
|
||||
# gaming 7.0h" / "Credit applied (details unavailable)".
|
||||
# daemon, unlike Tk). Was "Workout credited 💪" / "Shutdown 23:00 (+2h)" /
|
||||
# "Credit applied (details unavailable)".
|
||||
TITLE: Final = "\N{FLEXED BICEPS} \N{CHECK MARK}"
|
||||
_SHUTDOWN: Final = "\N{POWER SYMBOL}"
|
||||
_GAMING: Final = "\N{VIDEO GAME}"
|
||||
_NOTIFY_TIMEOUT_SECONDS: Final = 5
|
||||
_MINUTES_PER_HOUR: Final = 60.0
|
||||
|
||||
|
||||
def gaming_minutes_today(log_file: Path | None) -> int | None:
|
||||
"""Today's gaming budget per the earned_time registry, or ``None``.
|
||||
|
||||
``None`` (logged) when the inputs cannot be read; the notification then
|
||||
shows the shutdown time alone.
|
||||
"""
|
||||
try:
|
||||
target = gather(date.fromisoformat(today_str()), log_file)
|
||||
except (OSError, ValueError, KeyError) as exc:
|
||||
_logger.warning(
|
||||
"Could not compute today's gaming budget for the credit "
|
||||
"notification (%s) — showing the shutdown time only",
|
||||
exc,
|
||||
)
|
||||
return None
|
||||
return int(target.resolution.gaming_minutes)
|
||||
|
||||
|
||||
def credit_body(
|
||||
before: tuple[int, int, int] | None,
|
||||
after: tuple[int, int, int] | None,
|
||||
gaming_minutes: int | None,
|
||||
) -> str:
|
||||
"""``⏻ 23:00 (+2h) · 🎮 7.0h`` -- whichever parts are known.
|
||||
"""``⏻ 23:00 (+2h)`` -- whichever parts are known.
|
||||
|
||||
``before``/``after`` are the shutdown config around the credit; the delta
|
||||
is tonight's actual move, so a capped or rest-day credit shows ``+0h``.
|
||||
@ -86,8 +58,6 @@ def credit_body(
|
||||
moved = max(0, tonight - tonight_minutes(before, day))
|
||||
text += f" (+{span(moved)})"
|
||||
parts.append(text)
|
||||
if gaming_minutes is not None:
|
||||
parts.append(f"{_GAMING} {gaming_minutes / _MINUTES_PER_HOUR:.1f}h")
|
||||
return " \N{MIDDLE DOT} ".join(parts) or "\N{CHECK MARK}"
|
||||
|
||||
|
||||
@ -123,8 +93,7 @@ def send_notification(title: str, body: str) -> bool:
|
||||
def notify_workout_credit(
|
||||
before: tuple[int, int, int] | None,
|
||||
after: tuple[int, int, int] | None,
|
||||
log_file: Path | None,
|
||||
) -> bool:
|
||||
"""Notify a newly earned workout credit. Never raises."""
|
||||
body = credit_body(before, after, gaming_minutes_today(log_file))
|
||||
body = credit_body(before, after)
|
||||
return send_notification(TITLE, body)
|
||||
|
||||
@ -25,7 +25,6 @@ from screen_locker._constants import (
|
||||
SHUTDOWN_BASE_FILE,
|
||||
SHUTDOWN_CONFIG_FILE,
|
||||
)
|
||||
from screen_locker._credit_notify import gaming_minutes_today
|
||||
from screen_locker._day import today_str
|
||||
from screen_locker._earned import hhmm
|
||||
from screen_locker._extra_benefits import process_week_transition
|
||||
@ -38,7 +37,6 @@ from screen_locker.screen_lock import ScreenLocker
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterable, Mapping
|
||||
from pathlib import Path
|
||||
|
||||
from screen_locker._workout_credit import WorkoutCreditResult
|
||||
|
||||
@ -49,7 +47,6 @@ __all__ = [
|
||||
"credit_manual_workouts",
|
||||
"credit_session",
|
||||
"credit_sessions",
|
||||
"current_gaming_minutes",
|
||||
"current_shutdown",
|
||||
]
|
||||
|
||||
@ -120,11 +117,6 @@ def current_shutdown() -> str | None:
|
||||
return hhmm(tonight_minutes(config, date.fromisoformat(today_str())))
|
||||
|
||||
|
||||
def current_gaming_minutes(log_file: Path) -> int | None:
|
||||
"""Today's gaming budget (``None`` and a warning when it cannot be summed)."""
|
||||
return gaming_minutes_today(log_file)
|
||||
|
||||
|
||||
def _precheck(record_id: str, payload: Mapping[str, object]) -> str | None:
|
||||
"""Why the session can never count, or ``None`` if it can.
|
||||
|
||||
|
||||
@ -46,21 +46,19 @@ def _reply(
|
||||
outcome: _poke_credit.PokeOutcome,
|
||||
*,
|
||||
sandbox: bool = False,
|
||||
snapshot: tuple[str | None, int | None] = (None, None),
|
||||
shutdown: str | None = None,
|
||||
) -> dict[str, object]:
|
||||
"""The contract's response shape; ``pc_ms`` is filled in by the handler.
|
||||
|
||||
``snapshot`` is (tonight's shutdown ``HH:MM``, gaming minutes); refusals
|
||||
leave it null rather than tell an unverified caller anything.
|
||||
``shutdown`` is tonight's shutdown ``HH:MM``; refusals leave it null
|
||||
rather than tell an unverified caller anything.
|
||||
"""
|
||||
shutdown, gaming = snapshot
|
||||
return {
|
||||
"ok": outcome.ok,
|
||||
"credited": outcome.credited,
|
||||
"duplicate": outcome.duplicate,
|
||||
"sandbox": sandbox,
|
||||
"shutdown": shutdown,
|
||||
"gaming_budget_minutes": gaming,
|
||||
"pc_ms": 0,
|
||||
"reason": outcome.reason,
|
||||
}
|
||||
@ -77,7 +75,6 @@ def _refused(reason: str) -> dict[str, object]:
|
||||
|
||||
def _process(request: PokeRequest) -> dict[str, object]:
|
||||
"""Credit (or, for a sandbox request, only answer) one verified poke."""
|
||||
locker = _poke_credit.fresh_locker()
|
||||
if request.sandbox:
|
||||
outcome = _poke_credit.PokeOutcome(
|
||||
ok=True,
|
||||
@ -90,10 +87,7 @@ def _process(request: PokeRequest) -> dict[str, object]:
|
||||
return _reply(
|
||||
outcome,
|
||||
sandbox=request.sandbox,
|
||||
snapshot=(
|
||||
_poke_credit.current_shutdown(),
|
||||
_poke_credit.current_gaming_minutes(locker.log_file),
|
||||
),
|
||||
shutdown=_poke_credit.current_shutdown(),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@ -182,7 +182,7 @@ class WorkoutCreditMixin:
|
||||
batch uncredited, so every exception is logged and dropped here.
|
||||
"""
|
||||
try:
|
||||
_credit_notify.notify_workout_credit(before, after, self.log_file)
|
||||
_credit_notify.notify_workout_credit(before, after)
|
||||
except Exception: # pylint: disable=broad-exception-caught # notification must never fail the credit
|
||||
_logger.exception(
|
||||
"Workout credit notification failed — the credit itself is "
|
||||
|
||||
@ -87,10 +87,8 @@ def main(argv: list[str] | None = None) -> int:
|
||||
except (OSError, ValueError) as exc:
|
||||
_logger.critical("Refusing to start: bad poke key (%s); %s", exc, _KEYGEN_HINT)
|
||||
return 1
|
||||
# Warm the budget sum (registry, ledgers) and the conf read once, so the
|
||||
# first poke costs what every later one does.
|
||||
# Warm the conf read once, so the first poke costs what every later one does.
|
||||
_poke_credit.current_shutdown()
|
||||
_poke_credit.current_gaming_minutes(_poke_credit.fresh_locker().log_file)
|
||||
try:
|
||||
server = PokeServer((args.bind, args.port), key)
|
||||
except OSError as exc:
|
||||
|
||||
@ -9,7 +9,6 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import subprocess
|
||||
from types import SimpleNamespace
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
@ -20,7 +19,6 @@ from screen_locker.tests.conftest import create_locker
|
||||
|
||||
# The toast's glyphs (textgate): the module's own constants, not words.
|
||||
_SHUTDOWN = _credit_notify._SHUTDOWN
|
||||
_GAMING = _credit_notify._GAMING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
@ -44,54 +42,34 @@ def _warned(caplog: pytest.LogCaptureFixture, needle: str) -> bool:
|
||||
)
|
||||
|
||||
|
||||
class TestGamingMinutes:
|
||||
"""The budget figure, or None when its inputs cannot be read."""
|
||||
|
||||
def test_returns_the_registry_figure(self) -> None:
|
||||
"""gather's resolution is shown as whole minutes."""
|
||||
target = SimpleNamespace(resolution=SimpleNamespace(gaming_minutes=420.0))
|
||||
with patch(f"{_MOD}.gather", return_value=target):
|
||||
assert _credit_notify.gaming_minutes_today(None) == 420
|
||||
|
||||
def test_unreadable_inputs_warn_and_return_none(
|
||||
self, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
"""A broken ledger costs the figure, not the notification."""
|
||||
with patch(f"{_MOD}.gather", side_effect=OSError("ledger gone")):
|
||||
assert _credit_notify.gaming_minutes_today(None) is None
|
||||
assert _warned(caplog, "ledger gone")
|
||||
|
||||
|
||||
class TestCreditBody:
|
||||
"""Whichever parts are known end up in the body."""
|
||||
|
||||
def test_full_body(self) -> None:
|
||||
"""Shutdown time, tonight's move and the gaming budget."""
|
||||
body = _credit_notify.credit_body((0, 1200, 0), (0, 1320, 0), 420)
|
||||
assert body == f"{_SHUTDOWN} 22:00 (+2h) \N{MIDDLE DOT} {_GAMING} 7.0h"
|
||||
"""Shutdown time and tonight's move; no gaming figure any more."""
|
||||
body = _credit_notify.credit_body((0, 1200, 0), (0, 1320, 0))
|
||||
assert body == f"{_SHUTDOWN} 22:00 (+2h)"
|
||||
|
||||
def test_a_capped_credit_shows_plus_zero(self) -> None:
|
||||
"""No backwards move is ever shown: the delta floors at zero."""
|
||||
body = _credit_notify.credit_body((0, 1380, 0), (0, 1320, 0), None)
|
||||
body = _credit_notify.credit_body((0, 1380, 0), (0, 1320, 0))
|
||||
assert body == f"{_SHUTDOWN} 22:00 (+0h)"
|
||||
|
||||
def test_unknown_before_drops_the_delta(self) -> None:
|
||||
"""Without the old config there is no move to show."""
|
||||
assert (
|
||||
_credit_notify.credit_body(None, (0, 1320, 0), None) == f"{_SHUTDOWN} 22:00"
|
||||
)
|
||||
assert _credit_notify.credit_body(None, (0, 1320, 0)) == f"{_SHUTDOWN} 22:00"
|
||||
|
||||
def test_unreadable_after_warns_and_shows_gaming_only(
|
||||
def test_unreadable_after_warns_and_shows_the_check_mark(
|
||||
self, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
"""An unreadable config is said out loud, not silently omitted."""
|
||||
assert _credit_notify.credit_body(None, None, 90) == f"{_GAMING} 1.5h"
|
||||
assert _credit_notify.credit_body(None, None) == "\N{CHECK MARK}"
|
||||
assert _warned(caplog, "unreadable")
|
||||
|
||||
def test_nothing_known_still_says_something(self) -> None:
|
||||
"""An empty body would read as a glitch; say the credit happened."""
|
||||
body = _credit_notify.credit_body(None, None, None)
|
||||
assert body == "\N{CHECK MARK}"
|
||||
def test_the_gaming_figure_is_gone(self) -> None:
|
||||
"""No budget exists any more: the body never mentions gaming."""
|
||||
assert not hasattr(_credit_notify, "gaming_minutes_today")
|
||||
assert not hasattr(_credit_notify, "_GAMING")
|
||||
|
||||
|
||||
class TestSendNotification:
|
||||
@ -152,13 +130,10 @@ class TestSendNotification:
|
||||
def test_notify_workout_credit_sends_the_composed_body() -> None:
|
||||
"""The real entry point composes the body and sends it once."""
|
||||
with (
|
||||
patch(f"{_MOD}.gaming_minutes_today", return_value=60),
|
||||
patch(f"{_MOD}.send_notification", return_value=True) as send,
|
||||
):
|
||||
assert _real_notify((0, 1200, 0), (0, 1260, 0), None)
|
||||
send.assert_called_once_with(
|
||||
_credit_notify.TITLE, f"{_SHUTDOWN} 21:00 (+1h) \N{MIDDLE DOT} {_GAMING} 1.0h"
|
||||
)
|
||||
assert _real_notify((0, 1200, 0), (0, 1260, 0))
|
||||
send.assert_called_once_with(_credit_notify.TITLE, f"{_SHUTDOWN} 21:00 (+1h)")
|
||||
|
||||
|
||||
class TestCreditSideOfTheNotifier:
|
||||
|
||||
@ -129,7 +129,7 @@ class TestSlotCreditMinutes:
|
||||
result, notify = _credit(locker, [])
|
||||
assert result.shutdown_adjusted is True
|
||||
assert locker._read_shutdown_config() == (1320, 1320, 300)
|
||||
notify.assert_called_once_with(_START, (1320, 1320, 300), locker.log_file)
|
||||
notify.assert_called_once_with(_START, (1320, 1320, 300))
|
||||
|
||||
def test_distinct_slot_earns_one_hour(
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
|
||||
@ -84,7 +84,7 @@ class TestStartTheDay:
|
||||
|
||||
|
||||
class TestSnapshots:
|
||||
"""Groups the shutdown and gaming-minutes values snapshotted into poke replies."""
|
||||
"""Groups the shutdown value snapshotted into poke replies."""
|
||||
|
||||
def test_current_shutdown_renders_tonights_time(
|
||||
self, monkeypatch: pytest.MonkeyPatch
|
||||
@ -102,18 +102,3 @@ class TestSnapshots:
|
||||
with caplog.at_level(logging.WARNING):
|
||||
assert _poke_credit.current_shutdown() is None
|
||||
assert "shutdown=null" in caplog.text
|
||||
|
||||
def test_current_gaming_minutes_delegates(
|
||||
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""current_gaming_minutes returns what gaming_minutes_today reports for the log."""
|
||||
seen: list[Path] = []
|
||||
|
||||
def minutes(log: Path) -> int:
|
||||
"""Record the log path asked about and return 90 minutes."""
|
||||
seen.append(log)
|
||||
return 90
|
||||
|
||||
monkeypatch.setattr(_poke_credit, "gaming_minutes_today", minutes)
|
||||
assert _poke_credit.current_gaming_minutes(tmp_path / "log.json") == 90
|
||||
assert seen == [tmp_path / "log.json"]
|
||||
|
||||
@ -54,7 +54,6 @@ def _daemon_stubs(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
||||
locker.log_file = tmp_path / "log.json"
|
||||
monkeypatch.setattr(_poke_credit, "fresh_locker", lambda: locker)
|
||||
monkeypatch.setattr(_poke_credit, "current_shutdown", MagicMock())
|
||||
monkeypatch.setattr(_poke_credit, "current_gaming_minutes", MagicMock())
|
||||
monkeypatch.setattr(poke_server, "PokeServer", FakeServer)
|
||||
|
||||
|
||||
|
||||
@ -49,7 +49,6 @@ def pc_fixture(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> dict[str, Mag
|
||||
monkeypatch.setattr(_poke_credit, "ingest_session_records", spies["ingest"])
|
||||
monkeypatch.setattr(_poke_credit, "credit_session", spies["credit"])
|
||||
monkeypatch.setattr(_poke_credit, "current_shutdown", lambda: "20:30")
|
||||
monkeypatch.setattr(_poke_credit, "current_gaming_minutes", lambda _p: 75)
|
||||
return spies
|
||||
|
||||
|
||||
@ -63,7 +62,7 @@ def test_sandbox_replies_ok_with_the_snapshot_and_nothing_credited(
|
||||
assert reply["credited"] is False
|
||||
assert reply["duplicate"] is False
|
||||
assert reply["shutdown"] == "20:30"
|
||||
assert reply["gaming_budget_minutes"] == 75
|
||||
assert "gaming_budget_minutes" not in reply
|
||||
assert "nothing written or credited" in str(reply["reason"])
|
||||
|
||||
|
||||
|
||||
@ -70,7 +70,6 @@ def credit_fixture(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> MagicMock
|
||||
locker.log_file = tmp_path / "log.json"
|
||||
monkeypatch.setattr(_poke_credit, "fresh_locker", lambda: locker)
|
||||
monkeypatch.setattr(_poke_credit, "current_shutdown", lambda: "20:30")
|
||||
monkeypatch.setattr(_poke_credit, "current_gaming_minutes", lambda _p: 75)
|
||||
spy = MagicMock(
|
||||
return_value=_poke_credit.PokeOutcome(
|
||||
ok=True, credited=True, duplicate=False, reason="workout credited"
|
||||
@ -130,7 +129,7 @@ class TestCredit:
|
||||
assert reply["duplicate"] is False
|
||||
assert reply["sandbox"] is False
|
||||
assert reply["shutdown"] == "20:30"
|
||||
assert reply["gaming_budget_minutes"] == 75
|
||||
assert "gaming_budget_minutes" not in reply
|
||||
assert isinstance(reply["pc_ms"], int)
|
||||
credit.assert_called_once_with(
|
||||
"rec-1", {"date": "2026-10-09", "note": "zażółć"}
|
||||
|
||||
@ -78,8 +78,9 @@ class TestRouting:
|
||||
|
||||
|
||||
def test_reply_for_a_refusal_leaves_the_snapshot_null() -> None:
|
||||
"""A refusal reply carries no shutdown or gaming-budget snapshot."""
|
||||
"""A refusal reply carries no shutdown snapshot."""
|
||||
reply = _poke_server._refused("nope")
|
||||
assert reply["ok"] is False
|
||||
assert (reply["shutdown"], reply["gaming_budget_minutes"]) == (None, None)
|
||||
assert reply["shutdown"] is None
|
||||
assert "gaming_budget_minutes" not in reply
|
||||
assert reply["reason"] == "nope"
|
||||
|
||||
@ -37,15 +37,13 @@ class PokeResult {
|
||||
required this.outcome,
|
||||
required this.reason,
|
||||
this.shutdown,
|
||||
this.gamingBudgetMinutes,
|
||||
this.roundTripMs,
|
||||
});
|
||||
|
||||
/// A failure that never got a usable reply.
|
||||
const PokeResult.failed(this.reason, {this.roundTripMs})
|
||||
: outcome = PokeOutcome.failed,
|
||||
shutdown = null,
|
||||
gamingBudgetMinutes = null;
|
||||
shutdown = null;
|
||||
|
||||
/// Parses the PC's JSON reply. Any shape the contract does not allow is a
|
||||
/// [PokeOutcome.failed] naming what was wrong, not an exception.
|
||||
@ -81,8 +79,8 @@ class PokeResult {
|
||||
roundTripMs: roundTripMs,
|
||||
);
|
||||
}
|
||||
// shutdown / gaming_budget_minutes may be null (refusals): never assumed.
|
||||
final budget = decoded['gaming_budget_minutes'];
|
||||
// shutdown may be null (refusals): never assumed. An older PC also sends
|
||||
// gaming_budget_minutes; the budget is gone, so the field is ignored.
|
||||
final shutdown = decoded['shutdown'];
|
||||
final PokeOutcome outcome;
|
||||
if (decoded['ok'] != true) {
|
||||
@ -100,7 +98,6 @@ class PokeResult {
|
||||
outcome: outcome,
|
||||
reason: reason,
|
||||
shutdown: shutdown is String ? shutdown : null,
|
||||
gamingBudgetMinutes: budget is int ? budget : null,
|
||||
roundTripMs: roundTripMs,
|
||||
);
|
||||
}
|
||||
@ -114,9 +111,6 @@ class PokeResult {
|
||||
/// The PC's shutdown time after this poke, `HH:MM`.
|
||||
final String? shutdown;
|
||||
|
||||
/// Today's gaming budget after this poke, in minutes.
|
||||
final int? gamingBudgetMinutes;
|
||||
|
||||
/// Measured phone-side round trip, when a request was actually sent.
|
||||
final int? roundTripMs;
|
||||
|
||||
@ -126,11 +120,7 @@ class PokeResult {
|
||||
case PokeOutcome.credited:
|
||||
final parts = <String>['PC ✓'];
|
||||
if (shutdown != null) parts.add('shutdown $shutdown');
|
||||
final minutes = gamingBudgetMinutes;
|
||||
final gaming = minutes == null
|
||||
? ''
|
||||
: ' · gaming ${(minutes / 60).toStringAsFixed(1)}h';
|
||||
return '${parts.join(' ')}$gaming';
|
||||
return parts.join(' ');
|
||||
case PokeOutcome.duplicate:
|
||||
return 'PC: already credited';
|
||||
case PokeOutcome.sandbox:
|
||||
|
||||
@ -63,7 +63,6 @@ class PcPokeLine extends StatelessWidget {
|
||||
PokeOutcome.failed => Icons.schedule,
|
||||
};
|
||||
final style = TextStyle(color: color, fontSize: AppTextSize.caption);
|
||||
final minutes = result.gamingBudgetMinutes;
|
||||
return Semantics(
|
||||
label: result.label,
|
||||
excludeSemantics: true,
|
||||
@ -80,11 +79,6 @@ class PcPokeLine extends StatelessWidget {
|
||||
Icon(Icons.power_settings_new, size: 14, color: color),
|
||||
Text(' ${result.shutdown}', style: style),
|
||||
],
|
||||
if (minutes != null) ...[
|
||||
const SizedBox(width: AppSpacing.sm),
|
||||
Icon(Icons.sports_esports, size: 14, color: color),
|
||||
Text(' ${(minutes / 60).toStringAsFixed(1)}h', style: style),
|
||||
],
|
||||
],
|
||||
// Sandbox: the round trip in milliseconds behind a timer glyph.
|
||||
if (result.outcome == PokeOutcome.sandbox) ...[
|
||||
|
||||
@ -24,10 +24,11 @@ String _reply({
|
||||
});
|
||||
|
||||
void main() {
|
||||
test('credited shows shutdown and gaming hours', () {
|
||||
// A PC older than 2026-11-16 still sends gaming_budget_minutes: ignored.
|
||||
test('credited shows the shutdown only', () {
|
||||
final r = PokeResult.fromReply(200, _reply(credited: true), 40);
|
||||
expect(r.outcome, PokeOutcome.credited);
|
||||
expect(r.label, 'PC ✓ shutdown 21:00 · gaming 1.5h');
|
||||
expect(r.label, 'PC ✓ shutdown 21:00');
|
||||
});
|
||||
|
||||
test('credited with null shutdown/budget still renders', () {
|
||||
|
||||
@ -92,7 +92,7 @@ void main() {
|
||||
final result = await _service(client, sandbox: false).poke(_session());
|
||||
|
||||
expect(result.outcome, PokeOutcome.credited);
|
||||
expect(result.label, 'PC ✓ shutdown 22:00 · gaming 2.0h');
|
||||
expect(result.label, 'PC ✓ shutdown 22:00');
|
||||
expect(result.roundTripMs, isNotNull);
|
||||
expect(seen.url.toString(), 'http://10.0.0.7:$kPcPokePort$kPcPokePath');
|
||||
expect(
|
||||
@ -119,13 +119,12 @@ void main() {
|
||||
expect(result.label, startsWith('PC ✓ (sandbox, not credited) · '));
|
||||
});
|
||||
|
||||
test('null shutdown and budget are carried as null, not guessed', () async {
|
||||
test('null shutdown is carried as null, not guessed', () async {
|
||||
final client = MockClient(
|
||||
(_) async => http.Response(_reply(credited: true), 200),
|
||||
);
|
||||
final result = await _service(client).poke(_session());
|
||||
expect(result.shutdown, isNull);
|
||||
expect(result.gamingBudgetMinutes, isNull);
|
||||
expect(result.label, 'PC ✓');
|
||||
});
|
||||
|
||||
|
||||
@ -51,7 +51,6 @@ void main() {
|
||||
outcome: PokeOutcome.credited,
|
||||
reason: 'credited',
|
||||
shutdown: '22:00',
|
||||
gamingBudgetMinutes: 90,
|
||||
),
|
||||
PokeResult(outcome: PokeOutcome.duplicate, reason: 'dup'),
|
||||
PokeResult(outcome: PokeOutcome.sandbox, reason: 'sb', roundTripMs: 40),
|
||||
|
||||
@ -88,7 +88,7 @@ void main() {
|
||||
expect(colorOf(tester), status.warning);
|
||||
});
|
||||
|
||||
testWidgets('a credit shows the new shutdown and gaming hours', (
|
||||
testWidgets('a credit shows the new shutdown and no gaming figure', (
|
||||
tester,
|
||||
) async {
|
||||
await show(
|
||||
@ -98,12 +98,11 @@ void main() {
|
||||
outcome: PokeOutcome.credited,
|
||||
reason: 'credited',
|
||||
shutdown: '22:00',
|
||||
gamingBudgetMinutes: 90,
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(find.text(' 22:00'), findsOneWidget);
|
||||
expect(find.text(' 1.5h'), findsOneWidget);
|
||||
expect(find.byIcon(Icons.sports_esports), findsNothing);
|
||||
expect(find.byIcon(Icons.power_settings_new), findsOneWidget);
|
||||
expect(colorOf(tester), status.success);
|
||||
});
|
||||
|
||||
Loading…
Reference in New Issue
Block a user