mirror of
https://github.com/kuhyx/diet-guard.git
synced 2026-11-21 18:22:17 +01:00
Auto-log due catering before the lock
kuhy's 2026-11-17 override of "delivered is not eaten": before the lock opens, the PC logs the due slots' dishes by id uuid5(kuchnia📅key), shared with the phone (fixture-pinned). Failure paths: - fetch error, no credentials, > 5 s: fail-closed, nothing is logged, the lock opens as before, reason emitted and logged. - log write error (OSError/ValueError): fail-closed, same. - gate --check: never logs (a decision, not a write). - an undone (tombstoned) entry counts as logged: fail-closed against resurrecting a meal kuhy removed. - publish outage after a clearing auto-log: fail-open by design, the local entry stays and the reason is emitted. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
This commit is contained in:
parent
b0c556b745
commit
03b6a455cb
@ -35,6 +35,8 @@ _LAZY_ATTRS = {
|
||||
# ``_sync_refresh`` reaches ``crdt_sync`` -> ``requests``; the not-due
|
||||
# tick never pulls, so it must not pay that import either.
|
||||
"pull_peer_logs": ("diet_guard._sync_refresh", "pull_peer_logs"),
|
||||
# The catering auto-log reaches the panel client; same reasoning.
|
||||
"autolog_due_delivery": ("diet_guard._kuchnia_autolog", "autolog_due_delivery"),
|
||||
}
|
||||
|
||||
|
||||
@ -48,7 +50,7 @@ def __getattr__(name: str) -> object:
|
||||
return getattr(import_module(module_name), attr)
|
||||
|
||||
|
||||
def _should_lock(emit: Callable[[str], None]) -> bool:
|
||||
def _should_lock(emit: Callable[[str], None], *, autolog: bool = True) -> bool:
|
||||
"""Decide whether to lock, pulling from sync first if a lock looks due.
|
||||
|
||||
This wraps the pure, local :func:`~diet_guard._gate.gate_is_due` predicate
|
||||
@ -64,15 +66,29 @@ def _should_lock(emit: Callable[[str], None]) -> bool:
|
||||
in :func:`cmd_gate` once the window has closed. Only the peer logs can
|
||||
answer "has a peer already logged this slot?", which is the sole question
|
||||
this predicate asks.
|
||||
|
||||
After the pull, ``autolog`` (every real mode except ``--check``) logs
|
||||
today's catering for the due slots (:mod:`diet_guard._kuchnia_autolog`,
|
||||
kuhy's 2026-11-17 override of "delivered is not eaten"). It is capped at
|
||||
5 s and fail-closed: any failure leaves the lock decision untouched. When
|
||||
it clears the lock no window opens, so it publishes here -- ``cmd_gate``'s
|
||||
own publish only follows a window -- or the phone would keep nagging.
|
||||
"""
|
||||
if not gate_is_due():
|
||||
return False
|
||||
# Through the module object so the lazy hook above resolves it, and so a
|
||||
# test's ``patch.object`` still wins.
|
||||
reason = sys.modules[__name__].pull_peer_logs()
|
||||
module = sys.modules[__name__]
|
||||
reason = module.pull_peer_logs()
|
||||
if reason is not None:
|
||||
emit(f"{reason}; using local log.")
|
||||
return gate_is_due()
|
||||
written = module.autolog_due_delivery(emit) if autolog else 0
|
||||
due = gate_is_due()
|
||||
if written and not due:
|
||||
reason = module.publish_after_log()
|
||||
if reason is not None:
|
||||
emit(f"auto-logged locally, not yet published ({reason}).")
|
||||
return due
|
||||
|
||||
|
||||
def cmd_gate(emit: Callable[[str], None], *, check: bool, demo: bool) -> int:
|
||||
@ -97,7 +113,7 @@ def cmd_gate(emit: Callable[[str], None], *, check: bool, demo: bool) -> int:
|
||||
For ``--check``: 0 if not due, 1 if a lock is due. Otherwise 0.
|
||||
"""
|
||||
if check:
|
||||
due = _should_lock(emit)
|
||||
due = _should_lock(emit, autolog=False)
|
||||
emit("due (a lock is warranted)" if due else "ok (no lock needed)")
|
||||
return 1 if due else 0
|
||||
if not demo and not _should_lock(emit):
|
||||
|
||||
@ -9,9 +9,9 @@ link in the controller chain -- pylint caps that chain's depth and the gate is
|
||||
at the limit -- and a separate module so both stay under the 250-line cap.
|
||||
|
||||
**Neither logs anything by itself.** The catering fetch fills the form and
|
||||
stops; the user still clicks "Log & Continue". Auto-submitting would let the
|
||||
gate satisfy its own checkpoint from a delivery note, which is the one thing
|
||||
this feature is designed not to do.
|
||||
stops; the user still clicks "Log & Continue". The tap-free logging happens
|
||||
earlier and elsewhere (:mod:`diet_guard._kuchnia_autolog`, before the window
|
||||
opens), never from inside it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@ -2,8 +2,10 @@
|
||||
|
||||
Two clicks, never one. The first fetches the day's delivery off the Tk thread
|
||||
and shows exactly what would be written; the button relabels to "Confirm (N)".
|
||||
Only the second click writes. A delivered meal is not an eaten meal, so the
|
||||
user sees the dishes and the slots before anything lands -- and no modal
|
||||
Only the second click writes. This is the *manual* path; the pre-lock
|
||||
auto-log (:mod:`diet_guard._kuchnia_autolog`) logs due slots without a tap, but
|
||||
this button reaches every slot, so the user sees the dishes and the slots
|
||||
before anything lands -- and no modal
|
||||
dialog asks instead, because a pop-up over a fullscreen grab risks stealing the
|
||||
very keyboard grab the lock depends on.
|
||||
|
||||
|
||||
@ -22,7 +22,8 @@ exists to forbid, so the pattern is copied rather than bent:
|
||||
the window is gone -- the gate is a ``Type=oneshot`` unit and must exit.
|
||||
|
||||
Nothing here logs anything. The fetch only *offers* dishes; writing entries is
|
||||
a separate, explicitly confirmed step (:mod:`diet_guard._kuchnia_log`).
|
||||
a separate, explicitly confirmed step (:mod:`diet_guard._kuchnia_log`), or the
|
||||
tap-free pre-lock auto-log (:mod:`diet_guard._kuchnia_autolog`).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@ -129,8 +129,8 @@ def _build_actions(
|
||||
).pack(side="left", padx=(0, XS))
|
||||
|
||||
# Today's catering delivery, with its real macros. Loading only *offers*
|
||||
# the dishes -- each still has to be checked and submitted, because a
|
||||
# delivered meal is not an eaten meal.
|
||||
# the dishes -- each still has to be checked and submitted here (the
|
||||
# pre-lock auto-log, when it runs, has already logged the due slots).
|
||||
make_button(
|
||||
pulls,
|
||||
_COLORS,
|
||||
|
||||
137
diet_guard/_kuchnia_autolog.py
Normal file
137
diet_guard/_kuchnia_autolog.py
Normal file
@ -0,0 +1,137 @@
|
||||
"""Log the due slots' catering dishes on the PC before a lock window opens.
|
||||
|
||||
kuhy's decision of 2026-11-17 ("LOG EVEN WITHOUT TAP") overrides the old rule
|
||||
that a delivered meal is not an eaten meal: when the gate is due, today's
|
||||
delivery is fetched and the dishes that :mod:`diet_guard._kuchnia_spread`
|
||||
assigns to the *due* slots are logged by themselves. If that satisfies every
|
||||
due slot, no window opens. Later slots are left alone -- they are logged when
|
||||
they come due, so a tick at 09:00 never pre-logs the evening.
|
||||
|
||||
Each entry's id is :func:`diet_guard._kuchnia_ids.autolog_id`, the same on the
|
||||
phone, so a repeat run, a second tick and the phone's own copy all collapse to
|
||||
one entry. A tombstoned (undone) entry still counts as logged.
|
||||
|
||||
Every failure is **fail-closed**: nothing is written and the lock opens as it
|
||||
always did. The fetch sits in front of a fullscreen lock, so it is capped at
|
||||
:data:`FETCH_TIMEOUT_S` seconds (``docs/DOCS-sync-latency.md``); the worker is a
|
||||
daemon thread, so an abandoned request cannot keep the oneshot unit alive.
|
||||
|
||||
``requests`` is reached lazily (PEP 562 hook below): the gate's common not-due
|
||||
tick must not pay ~78ms for an HTTP stack it never uses, and ``patch.object``
|
||||
keeps working on the name.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from importlib import import_module
|
||||
import logging
|
||||
import queue
|
||||
import sys
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from diet_guard._gate import due_slots
|
||||
from diet_guard._gatelock_kuchnia import start_delivery_fetch
|
||||
from diet_guard._kuchnia_ids import autolog_id, dish_key
|
||||
from diet_guard._kuchnia_log import dish_nutrition
|
||||
from diet_guard._kuchnia_spread import assign_slots
|
||||
from diet_guard._meal_schedule_store import current_schedule
|
||||
from diet_guard._slots import day_slots
|
||||
from diet_guard._state import now_local
|
||||
from diet_guard._state_sync import find_entry, log_meal_as
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - typing only
|
||||
from collections.abc import Callable, Sequence
|
||||
from datetime import date
|
||||
|
||||
from diet_guard._gatelock_kuchnia import RefreshFn
|
||||
from diet_guard._kuchnia_parse import Dish
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
#: Upper bound on the whole catering walk (login + three requests), in seconds.
|
||||
FETCH_TIMEOUT_S = 5.0
|
||||
|
||||
|
||||
def __getattr__(name: str) -> object:
|
||||
"""Resolve the deferred catering import on first attribute access."""
|
||||
if name != "refresh_delivery":
|
||||
msg = f"module {__name__!r} has no attribute {name!r}"
|
||||
raise AttributeError(msg)
|
||||
return import_module("diet_guard._kuchnia_import").refresh_delivery
|
||||
|
||||
|
||||
def current_slots() -> tuple[int, ...]:
|
||||
"""The configured slot minutes of the day."""
|
||||
return day_slots(current_schedule())
|
||||
|
||||
|
||||
def fetch_bounded(
|
||||
day: date,
|
||||
*,
|
||||
refresh: RefreshFn | None = None,
|
||||
timeout: float = FETCH_TIMEOUT_S,
|
||||
) -> tuple[list[Dish], str | None]:
|
||||
"""Fetch ``day``'s dishes, giving up after ``timeout`` seconds.
|
||||
|
||||
Returns:
|
||||
``(dishes, None)``, or ``([], reason)`` on a failed or too-slow fetch.
|
||||
"""
|
||||
fetch = refresh or sys.modules[__name__].refresh_delivery
|
||||
result = start_delivery_fetch(fetch, day)
|
||||
try:
|
||||
outcome = result.get(timeout=timeout)
|
||||
except queue.Empty:
|
||||
return [], f"catering fetch timed out after {timeout:g}s"
|
||||
return list(outcome.dishes), outcome.reason
|
||||
|
||||
|
||||
def log_due_dishes(
|
||||
dishes: Sequence[Dish],
|
||||
due: Sequence[int],
|
||||
day: date,
|
||||
slots: Sequence[int],
|
||||
) -> list[str]:
|
||||
"""Log the dishes assigned to a due slot; skip ones already logged.
|
||||
|
||||
Returns:
|
||||
The descriptions written, in the provider's meal order.
|
||||
"""
|
||||
written: list[str] = []
|
||||
for item in assign_slots(dishes, slots):
|
||||
if item.slot not in due:
|
||||
continue
|
||||
key = item.dish.dish_key or dish_key(None, item.dish.name)
|
||||
entry_id = autolog_id(day, key)
|
||||
if find_entry(entry_id) is not None:
|
||||
continue
|
||||
log_meal_as(entry_id, item.dish.name, dish_nutrition(item.dish), item.slot)
|
||||
written.append(item.dish.name)
|
||||
return written
|
||||
|
||||
|
||||
def autolog_due_delivery(emit: Callable[[str], None]) -> int:
|
||||
"""Auto-log today's catering for the due slots; never raises.
|
||||
|
||||
Returns:
|
||||
How many entries were written (0 on any failure: the lock proceeds).
|
||||
"""
|
||||
due = due_slots()
|
||||
if not due:
|
||||
return 0
|
||||
day = now_local().date()
|
||||
dishes, reason = fetch_bounded(day)
|
||||
if reason is not None:
|
||||
# First line only: a missing-credentials reason carries setup steps.
|
||||
short = reason.splitlines()[0] if reason else "unknown"
|
||||
_logger.warning("catering auto-log skipped: %s", short)
|
||||
emit(f"catering auto-log skipped: {short}")
|
||||
return 0
|
||||
try:
|
||||
written = log_due_dishes(dishes, due, day, current_slots())
|
||||
except OSError, ValueError:
|
||||
_logger.exception("catering auto-log failed while writing")
|
||||
emit("catering auto-log skipped: could not write the log (disk error)")
|
||||
return 0
|
||||
if written:
|
||||
emit(f"catering auto-logged: {', '.join(written)}")
|
||||
return len(written)
|
||||
42
diet_guard/_kuchnia_ids.py
Normal file
42
diet_guard/_kuchnia_ids.py
Normal file
@ -0,0 +1,42 @@
|
||||
"""The id a catering dish gets when it is logged without a tap.
|
||||
|
||||
One formula on every device, so the PC's entry and the phone's entry for the
|
||||
same delivered dish are the same record and the sync merge keeps one::
|
||||
|
||||
uuid5(NAMESPACE_URL, f"kuchnia:{delivery date YYYY-MM-DD}:{dish key}")
|
||||
|
||||
The dish key is the panel's ``deliveryMealId`` (an ``int``, or a stripped
|
||||
``str``); anything else -- a ``bool``, a float, a blank or missing id --
|
||||
falls back to the lower-cased dish name. The phone's port and this module are
|
||||
pinned by one fixture, ``tests/fixtures/kuchnia_autolog_ids.json``
|
||||
(``scripts/build_kuchnia_autolog_fixture.py``), asserted by
|
||||
``test_kuchnia_ids.py`` and ``app/test/services/kuchnia_autolog_ids_test.dart``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
import uuid
|
||||
|
||||
|
||||
def dish_key(meal_id: object, name: str) -> str:
|
||||
"""The dish half of the id string.
|
||||
|
||||
``bool`` is tested before ``int`` because ``isinstance(True, int)`` is
|
||||
true in Python and not in Dart; ``.lower()`` (not ``casefold``) matches
|
||||
the Dart port on the fixture's ASCII fallback names.
|
||||
"""
|
||||
key = ""
|
||||
if isinstance(meal_id, bool):
|
||||
key = ""
|
||||
elif isinstance(meal_id, int):
|
||||
key = str(meal_id)
|
||||
elif isinstance(meal_id, str):
|
||||
key = meal_id.strip()
|
||||
return key or name.strip().lower()
|
||||
|
||||
|
||||
def autolog_id(day: date | str, key: str) -> str:
|
||||
"""The deterministic entry id for dish ``key`` delivered on ``day``."""
|
||||
stamp = day.isoformat() if isinstance(day, date) else day
|
||||
return str(uuid.uuid5(uuid.NAMESPACE_URL, f"kuchnia:{stamp}:{key}"))
|
||||
@ -1,10 +1,11 @@
|
||||
"""Turn confirmed catering dishes into log entries.
|
||||
|
||||
Nothing here runs without an explicit confirmation from the user -- that is the
|
||||
whole design of this feature. A delivered meal is not an eaten meal: if the
|
||||
importer wrote entries unattended, the gate would auto-satisfy the exact
|
||||
checkpoint it exists to enforce, and the log would record what the courier
|
||||
dropped off rather than what was eaten.
|
||||
Nothing in this module runs without an explicit confirmation: the CLI
|
||||
``--log``, the lock window's buttons and "Fill all" all ask first. The one
|
||||
unattended path is separate -- :mod:`diet_guard._kuchnia_autolog`, the PC's
|
||||
pre-lock auto-log, which kuhy chose on 2026-11-17 ("LOG EVEN WITHOUT TAP")
|
||||
knowing a delivered meal is not always an eaten one (skipped, shared or binned
|
||||
dishes are logged as eaten).
|
||||
|
||||
Duplicate suppression works off **today's log**, not a local "already
|
||||
imported" marker. ``log_meal`` mints a fresh uuid per entry, so a re-import
|
||||
|
||||
@ -34,6 +34,7 @@ from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from diet_guard._coerce import as_float
|
||||
from diet_guard._kuchnia_ids import dish_key
|
||||
|
||||
#: Atwater factors. Used only as a sanity check on the *units*, never to
|
||||
#: recompute a value the panel already states.
|
||||
@ -69,6 +70,8 @@ class Dish:
|
||||
grams: float
|
||||
priority: int
|
||||
slot_label: str
|
||||
#: The id half of the auto-log entry id (:mod:`diet_guard._kuchnia_ids`).
|
||||
dish_key: str = ""
|
||||
|
||||
|
||||
def _energy_is_consistent(
|
||||
@ -138,6 +141,7 @@ def _parse_meal(meal: object, fallback_priority: int) -> Dish | None:
|
||||
grams=grams,
|
||||
priority=priority,
|
||||
slot_label=str(meal.get("mealName") or "").strip(),
|
||||
dish_key=dish_key(meal.get("deliveryMealId"), name),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@ -169,6 +169,13 @@ def state_redirects(tmp_path: Path) -> list[_patch[object]]:
|
||||
"diet_guard._gatelock_delivery.refresh_delivery",
|
||||
return_value=([], None),
|
||||
),
|
||||
# The pre-lock catering auto-log: a fourth network entry point, and
|
||||
# unlike the others it WRITES log entries. Unpatched, any test that
|
||||
# reaches `_should_lock` would hit the live panel.
|
||||
patch(
|
||||
"diet_guard._kuchnia_autolog.refresh_delivery",
|
||||
return_value=([], None),
|
||||
),
|
||||
# The gate's "Fill all" button fetches through its own lazy helper.
|
||||
patch(
|
||||
"diet_guard._gatelock_fillall._refresh_delivery",
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
"""Tests for the lock screen's two-click "Fill all" catering flow.
|
||||
|
||||
The properties that matter, because the gate exists to stop unattended logging:
|
||||
The properties of this *manual* path (auto-log: ``test_kuchnia_autolog.py``):
|
||||
|
||||
* the first click **never writes** -- it only proposes, and relabels the button;
|
||||
* the second click writes only into slots that are **still empty right now**,
|
||||
|
||||
209
diet_guard/tests/test_kuchnia_autolog.py
Normal file
209
diet_guard/tests/test_kuchnia_autolog.py
Normal file
@ -0,0 +1,209 @@
|
||||
"""Catering auto-log: the PC logs the due slots' dishes before a lock opens.
|
||||
|
||||
kuhy overrode "delivered is not eaten" on 2026-11-17 ("LOG EVEN WITHOUT TAP").
|
||||
Failure paths are fail-closed: nothing is logged and the lock opens as before.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
import time
|
||||
from unittest.mock import MagicMock, patch
|
||||
import uuid
|
||||
|
||||
from crdt_sync import merge_logs
|
||||
|
||||
from diet_guard import _cli_gate, _kuchnia_autolog
|
||||
from diet_guard._kuchnia_autolog import (
|
||||
FETCH_TIMEOUT_S,
|
||||
autolog_due_delivery,
|
||||
fetch_bounded,
|
||||
log_due_dishes,
|
||||
)
|
||||
from diet_guard._kuchnia_parse import Dish
|
||||
from diet_guard._slot_wire import entry_slot_minute
|
||||
from diet_guard._state_sync import find_entry, read_raw_log
|
||||
from diet_guard.sync_merge import daylog_to_log, log_to_daylog
|
||||
|
||||
DAY = date(2026, 11, 17)
|
||||
SLOTS = (480, 720, 960, 1200)
|
||||
|
||||
|
||||
def _dish(name: str, priority: int, key: str) -> Dish:
|
||||
return Dish(name, 400.0, 25.0, 45.0, 12.0, 300.0, priority, "x", dish_key=key)
|
||||
|
||||
|
||||
DISHES = [_dish("A", 1, "1001"), _dish("B", 2, "1002"), _dish("C", 3, "1003")]
|
||||
|
||||
|
||||
def _id(key: str) -> str:
|
||||
return str(uuid.uuid5(uuid.NAMESPACE_URL, f"kuchnia:2026-11-17:{key}"))
|
||||
|
||||
|
||||
def _entries() -> list[dict[str, object]]:
|
||||
return [e for day in read_raw_log().values() for e in day]
|
||||
|
||||
|
||||
def _run(due: tuple[int, ...]) -> list[str]:
|
||||
return log_due_dishes(DISHES, due, DAY, SLOTS)
|
||||
|
||||
|
||||
class TestLogDueDishes:
|
||||
"""Which dishes land, under which id."""
|
||||
|
||||
def test_only_due_slots_are_logged(self) -> None:
|
||||
"""Dishes of slots that are not due stay unlogged."""
|
||||
# 3 dishes on 4 slots: A -> 480, B -> 720, C -> 960 (i*S//N: 0,1,2).
|
||||
assert _run((720,)) == ["B"]
|
||||
(entry,) = _entries()
|
||||
assert entry["id"] == _id("1002")
|
||||
assert entry_slot_minute(entry) == 720
|
||||
assert entry["source"] == "kuchnia wikinga"
|
||||
|
||||
def test_run_twice_logs_one_entry(self) -> None:
|
||||
"""The deterministic id makes a repeat a no-op."""
|
||||
assert _run((480, 720)) == ["A", "B"]
|
||||
assert _run((480, 720)) == []
|
||||
assert [e["id"] for e in _entries()] == [_id("1001"), _id("1002")]
|
||||
|
||||
def test_an_undone_dish_is_not_resurrected(self) -> None:
|
||||
"""A tombstoned entry still counts as logged."""
|
||||
_run((480,))
|
||||
entry = find_entry(_id("1001"))
|
||||
assert entry is not None
|
||||
entry["deleted"] = True
|
||||
assert _run((480,)) == []
|
||||
|
||||
def test_peer_copy_merges_to_one_entry(self) -> None:
|
||||
"""The phone's copy of the same dish collapses with ours by id."""
|
||||
_run((480,))
|
||||
local = read_raw_log()
|
||||
(day,) = local
|
||||
peer_entry = {**local[day][0], "time": f"{day}T08:05:00+01:00"}
|
||||
peer_entry.pop("hmac", None)
|
||||
merged = merge_logs(daylog_to_log(local), daylog_to_log({day: [peer_entry]}))
|
||||
entries = [e for es in log_to_daylog(merged).values() for e in es]
|
||||
assert [e["id"] for e in entries] == [_id("1001")]
|
||||
|
||||
|
||||
class TestFetchBounded:
|
||||
"""The fetch sits in front of a fullscreen lock: it must be capped."""
|
||||
|
||||
def test_returns_the_fetch_result(self) -> None:
|
||||
"""A prompt fetch is passed through."""
|
||||
refresh = MagicMock(return_value=(DISHES, None))
|
||||
assert fetch_bounded(DAY, refresh=refresh) == (DISHES, None)
|
||||
|
||||
def test_slow_fetch_times_out(self) -> None:
|
||||
"""A hung panel yields a reason after the cap, not a hang."""
|
||||
|
||||
def slow(_day: date) -> tuple[list[Dish], str | None]:
|
||||
time.sleep(2)
|
||||
return DISHES, None
|
||||
|
||||
started = time.monotonic()
|
||||
dishes, reason = fetch_bounded(DAY, refresh=slow, timeout=0.05)
|
||||
assert (dishes, reason is not None) == ([], True)
|
||||
assert time.monotonic() - started < 1
|
||||
|
||||
def test_cap_is_five_seconds(self) -> None:
|
||||
"""The spec's bound."""
|
||||
assert FETCH_TIMEOUT_S <= 5.0
|
||||
|
||||
def test_unexpected_error_is_a_reason(self) -> None:
|
||||
"""A bug in the fetch cannot escape the worker."""
|
||||
dishes, reason = fetch_bounded(DAY, refresh=MagicMock(side_effect=OSError("x")))
|
||||
assert dishes == []
|
||||
assert reason is not None
|
||||
|
||||
|
||||
class TestAutologBeforeLock:
|
||||
"""The orchestration: fetch, log, report; never raise."""
|
||||
|
||||
written = 0
|
||||
|
||||
def _go(self, fetched: object, due: tuple[int, ...] = (480,)) -> list[str]:
|
||||
lines: list[str] = []
|
||||
with (
|
||||
patch.object(_kuchnia_autolog, "due_slots", return_value=due),
|
||||
patch.object(_kuchnia_autolog, "current_slots", return_value=SLOTS),
|
||||
patch.object(_kuchnia_autolog, "refresh_delivery", return_value=fetched),
|
||||
):
|
||||
self.written = autolog_due_delivery(lines.append)
|
||||
return lines
|
||||
|
||||
def test_logs_and_reports(self) -> None:
|
||||
"""A good fetch logs the due dish and says so."""
|
||||
lines = self._go((DISHES, None))
|
||||
assert self.written == 1
|
||||
assert [e["desc"] for e in _entries()] == ["A"]
|
||||
assert lines
|
||||
|
||||
def test_fetch_failure_logs_nothing_and_says_why(self) -> None:
|
||||
"""Fail closed: no entry, a reason line, the lock proceeds."""
|
||||
lines = self._go(([], "panel down"))
|
||||
assert self.written == 0
|
||||
assert _entries() == []
|
||||
assert "panel down" in lines[0]
|
||||
|
||||
def test_nothing_due_skips_the_network(self) -> None:
|
||||
"""No due slot, no fetch."""
|
||||
fetch = MagicMock(return_value=(DISHES, None))
|
||||
with (
|
||||
patch.object(_kuchnia_autolog, "due_slots", return_value=()),
|
||||
patch.object(_kuchnia_autolog, "fetch_bounded", fetch),
|
||||
):
|
||||
assert autolog_due_delivery([].append) == 0
|
||||
fetch.assert_not_called()
|
||||
|
||||
def test_logging_error_is_swallowed(self) -> None:
|
||||
"""Even a disk error falls back to the lock instead of crashing the gate."""
|
||||
lines: list[str] = []
|
||||
with (
|
||||
patch.object(_kuchnia_autolog, "due_slots", return_value=(480,)),
|
||||
patch.object(
|
||||
_kuchnia_autolog, "fetch_bounded", return_value=(DISHES, None)
|
||||
),
|
||||
patch.object(
|
||||
_kuchnia_autolog, "log_due_dishes", side_effect=OSError("disk")
|
||||
),
|
||||
):
|
||||
assert autolog_due_delivery(lines.append) == 0
|
||||
assert "disk" in lines[0]
|
||||
|
||||
|
||||
class TestShouldLockAutologs:
|
||||
"""``_should_lock`` runs the auto-log after the pull, before deciding."""
|
||||
|
||||
def test_autolog_that_clears_the_lock_publishes(self) -> None:
|
||||
"""No window, but the phone must still hear about the logged meal."""
|
||||
publish = MagicMock(return_value=None)
|
||||
with (
|
||||
patch.object(_cli_gate, "gate_is_due", side_effect=[True, False]),
|
||||
patch.object(_cli_gate, "autolog_due_delivery", return_value=1),
|
||||
patch.object(_cli_gate, "publish_after_log", publish),
|
||||
):
|
||||
assert _cli_gate._should_lock([].append) is False
|
||||
publish.assert_called_once()
|
||||
|
||||
def test_failed_autolog_still_locks(self) -> None:
|
||||
"""Nothing written, still due: the lock opens, no publish."""
|
||||
publish = MagicMock(return_value=None)
|
||||
with (
|
||||
patch.object(_cli_gate, "gate_is_due", side_effect=[True, True]),
|
||||
patch.object(_cli_gate, "autolog_due_delivery", return_value=0),
|
||||
patch.object(_cli_gate, "publish_after_log", publish),
|
||||
):
|
||||
assert _cli_gate._should_lock([].append) is True
|
||||
publish.assert_not_called()
|
||||
|
||||
def test_check_mode_never_logs(self) -> None:
|
||||
"""``gate --check`` is a decision, not a log write."""
|
||||
autolog = MagicMock(return_value=1)
|
||||
with (
|
||||
patch.object(_cli_gate, "gate_is_due", return_value=True),
|
||||
patch.object(_cli_gate, "pull_peer_logs", return_value=None),
|
||||
patch.object(_cli_gate, "autolog_due_delivery", autolog),
|
||||
):
|
||||
assert _cli_gate.cmd_gate([].append, check=True, demo=False) == 1
|
||||
autolog.assert_not_called()
|
||||
45
diet_guard/tests/test_kuchnia_ids.py
Normal file
45
diet_guard/tests/test_kuchnia_ids.py
Normal file
@ -0,0 +1,45 @@
|
||||
"""The auto-log entry id: one formula, pinned by the phone's shared fixture."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from diet_guard._kuchnia_ids import autolog_id, dish_key
|
||||
from diet_guard._kuchnia_parse import parse_menu
|
||||
|
||||
FIXTURE = (
|
||||
Path(__file__).resolve().parents[2] / "tests/fixtures/kuchnia_autolog_ids.json"
|
||||
)
|
||||
_CASES = json.loads(FIXTURE.read_text(encoding="utf-8"))["cases"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("case", _CASES, ids=lambda c: c["name_string"])
|
||||
def test_ids_match_the_shared_fixture(case: dict[str, object]) -> None:
|
||||
"""Key and id equal what the Dart port derives from the same input."""
|
||||
key = dish_key(case["delivery_meal_id"], str(case["name"]))
|
||||
assert key == case["dish_key"]
|
||||
assert autolog_id(str(case["delivery_date"]), key) == case["expected_id"]
|
||||
|
||||
|
||||
def test_parser_carries_the_panel_meal_id() -> None:
|
||||
"""``Dish.dish_key`` comes from ``deliveryMealId``, else the name."""
|
||||
meal = {
|
||||
"menuMealName": "Zupa",
|
||||
"mealPriority": 1,
|
||||
"nutrition": {
|
||||
"calories": 200.0,
|
||||
"protein": 10.0,
|
||||
"carbohydrate": 25.0,
|
||||
"fat": 6.0,
|
||||
"weight": 300.0,
|
||||
},
|
||||
}
|
||||
with_id, without = (
|
||||
parse_menu({"deliveryMenuMeal": [{**meal, **extra}]})[0]
|
||||
for extra in ({"deliveryMealId": 42}, {})
|
||||
)
|
||||
assert with_id.dish_key == "42"
|
||||
assert without.dish_key == "zupa"
|
||||
Loading…
Reference in New Issue
Block a user