mirror of
https://github.com/kuhyx/wake-alarm.git
synced 2026-11-22 15:02:17 +01:00
Ring the PC at 21:00 when notifications off
The fallback timer also ticks 21:00-21:59; those ticks go to _fallback_evening before any morning code. Rings while today's newest notifications event says off, 30 min cap on its own latch, never when tomorrow is free or sick. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
35d6d07d8e
commit
8c511c148c
@ -1,5 +1,5 @@
|
||||
[Unit]
|
||||
Description=Wake Alarm PC fallback alarm, once a minute through the morning
|
||||
Description=Wake Alarm PC fallback alarm, once a minute mornings and 21:00-21:59
|
||||
Documentation=https://github.com/kuhyx/wake-alarm
|
||||
|
||||
[Timer]
|
||||
@ -7,6 +7,8 @@ Documentation=https://github.com/kuhyx/wake-alarm
|
||||
# clamped to <= 08:00). Outside that window a tick reads only local files.
|
||||
# Through 11:59: a phone bypass rings the PC up to A + 4 h (A <= 08:00).
|
||||
OnCalendar=*-*-* 04..11:*:00
|
||||
# 21:00-21:59: the notifications check (DOCS-bypass.md); fetches only then.
|
||||
OnCalendar=*-*-* 21:*:00
|
||||
AccuracySec=1s
|
||||
# Catch up at once after the RTC resume or a boot.
|
||||
Persistent=true
|
||||
|
||||
@ -201,6 +201,8 @@ ESCAPE_REASON_MIN_CHARS: int = 40
|
||||
# Today's fallback-ring latch: {"date", "started_at", "stopped_at", "reason",
|
||||
# "stop_reason"}.
|
||||
FALLBACK_RING_FILE: Path = LOG_STATE_DIR / "fallback_ring.json"
|
||||
# The 21:00 notifications ring's own latch, same shape; never the morning's.
|
||||
EVENING_RING_FILE: Path = LOG_STATE_DIR / "evening_ring.json"
|
||||
|
||||
# {"mode": "hibernate" | "poweroff"}; how the PC goes down for the night.
|
||||
PC_WAKE_CONFIG: Path = Path.home() / ".config" / "wake_alarm" / "pc_wake.json"
|
||||
|
||||
100
wake_alarm/_evening_policy.py
Normal file
100
wake_alarm/_evening_policy.py
Normal file
@ -0,0 +1,100 @@
|
||||
"""The 21:00 notifications check's rule, as pure functions (``DOCS-bypass.md``).
|
||||
|
||||
Switching off "All WakeAlarm notifications" silences the ring and no device
|
||||
policy can lock that switch, so the phone reports the state as a
|
||||
``notifications`` phone event (at 21:00 and whenever the switch moves) and
|
||||
the PC rings in the evening, while there is still time to fix it:
|
||||
|
||||
============================================= ===================
|
||||
outside 21:00-21:59 start nothing
|
||||
tomorrow is a free or sick day never ring
|
||||
the evening ring used its 30 minutes never again tonight
|
||||
today's newest event says on, or none today quiet
|
||||
otherwise ring: notifications_off
|
||||
============================================= ===================
|
||||
|
||||
Tomorrow, not today: the point is tomorrow's alarm. The hour gates
|
||||
*starting* only; a ring in progress is judged by :func:`stop_reason`, so one
|
||||
started at 21:50 runs its full 30 minutes. The cap is measured from the
|
||||
evening latch's first start, never the morning's or a bypass's.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from wake_alarm._constants import FALLBACK_RING_CAP
|
||||
from wake_alarm._fallback_policy import CAP, Decision
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from datetime import datetime
|
||||
|
||||
from wake_alarm._fallback_latch import Latch
|
||||
|
||||
EVENING_HOUR: int = 21
|
||||
|
||||
# Reasons, as they appear in events.jsonl and evening_ring.json.
|
||||
NOTIFICATIONS_OFF = "notifications_off"
|
||||
NOTIFICATIONS_ON = "notifications_on"
|
||||
OUTSIDE_EVENING = "outside_evening"
|
||||
FREE_TOMORROW = "free_tomorrow"
|
||||
SICK_TOMORROW = "sick_tomorrow"
|
||||
UNREACHABLE = "firebase_unreachable"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EveningFacts:
|
||||
"""Everything one evening decision needs; the caller gathers it.
|
||||
|
||||
``off_since`` is today's newest ``notifications`` event when it says
|
||||
off; ``tomorrow_off`` is :data:`FREE_TOMORROW` / :data:`SICK_TOMORROW`.
|
||||
"""
|
||||
|
||||
now: datetime
|
||||
tomorrow_off: str | None = None
|
||||
off_since: datetime | None = None
|
||||
latch: Latch | None = None
|
||||
reachable: bool = True
|
||||
|
||||
|
||||
def in_evening(now: datetime) -> bool:
|
||||
"""Whether ``now`` is in the hour that may start an evening ring."""
|
||||
return now.hour == EVENING_HOUR
|
||||
|
||||
|
||||
def is_capped(facts: EveningFacts) -> bool:
|
||||
"""Whether tonight's ring has used its 30 minutes."""
|
||||
latch = facts.latch
|
||||
if latch is None:
|
||||
return False
|
||||
if latch.stop_reason == CAP:
|
||||
return True
|
||||
started = latch.started()
|
||||
return started is not None and facts.now >= started + FALLBACK_RING_CAP
|
||||
|
||||
|
||||
def needs_fetch(facts: EveningFacts) -> bool:
|
||||
"""Whether the phone's events can still change the answer."""
|
||||
return facts.tomorrow_off is None and not is_capped(facts)
|
||||
|
||||
|
||||
def stop_reason(facts: EveningFacts) -> str | None:
|
||||
"""Why an evening ring must stop (or not start), or None to ring."""
|
||||
if facts.tomorrow_off is not None:
|
||||
return facts.tomorrow_off
|
||||
if is_capped(facts):
|
||||
return CAP
|
||||
if facts.off_since is None:
|
||||
return NOTIFICATIONS_ON if facts.reachable else UNREACHABLE
|
||||
return None
|
||||
|
||||
|
||||
def decide(facts: EveningFacts) -> Decision:
|
||||
"""Ring or not at an evening tick; the table above, first match wins."""
|
||||
if not in_evening(facts.now):
|
||||
return Decision(ring=False, reason=OUTSIDE_EVENING)
|
||||
stop = stop_reason(facts)
|
||||
if stop is not None:
|
||||
return Decision(ring=False, reason=stop)
|
||||
return Decision(ring=True, reason=NOTIFICATIONS_OFF)
|
||||
@ -1,4 +1,7 @@
|
||||
"""The PC fallback alarm: one per-minute tick, 04:00-11:59.
|
||||
"""The PC fallback alarm: one per-minute tick, 04:00-11:59 and 21:00-21:59.
|
||||
|
||||
The 21:xx ticks are the notifications check (``_fallback_evening``),
|
||||
dispatched before any morning code runs.
|
||||
|
||||
``wake-alarm-fallback.timer`` runs ``--tick`` every minute. Outside
|
||||
``A - 5 min .. A + 45 min`` (or on a free or sick day) a tick decides from local
|
||||
@ -25,7 +28,9 @@ from typing import TYPE_CHECKING
|
||||
import freedays
|
||||
|
||||
from wake_alarm._cli_modes import mode_parser, parse_with_now
|
||||
from wake_alarm._evening_policy import in_evening
|
||||
from wake_alarm._events import emit, emit_on_change, last_value
|
||||
from wake_alarm._fallback_evening import evening_dry_run, evening_tick
|
||||
from wake_alarm._fallback_latch import Latch, mark_started, mark_stopped, read_latch
|
||||
from wake_alarm._fallback_observe import (
|
||||
Observation,
|
||||
@ -144,6 +149,8 @@ def ring_now(facts: Facts, reason: str) -> str:
|
||||
|
||||
def tick(now: datetime) -> Decision:
|
||||
"""One timer tick: observe, log a changed decision, ring if due."""
|
||||
if in_evening(now):
|
||||
return evening_tick(now)
|
||||
seen = observe(now, sync=True)
|
||||
record(seen)
|
||||
facts, day = seen.facts, now.date().isoformat()
|
||||
@ -211,6 +218,8 @@ def main(argv: list[str] | None = None) -> int:
|
||||
args, now = parse_with_now(parser, argv, _now)
|
||||
if args.show:
|
||||
sys.stdout.write(show(now))
|
||||
elif args.dry_run and in_evening(now):
|
||||
sys.stdout.write(evening_dry_run(now))
|
||||
elif args.dry_run:
|
||||
seen = observe(now, sync=False)
|
||||
sys.stdout.write(describe(seen, decide(seen.facts)))
|
||||
|
||||
166
wake_alarm/_fallback_evening.py
Normal file
166
wake_alarm/_fallback_evening.py
Normal file
@ -0,0 +1,166 @@
|
||||
"""The fallback timer's 21:00 hour: ring when the phone's notifications are off.
|
||||
|
||||
``_fallback.tick`` hands every 21:xx tick here before any morning code runs,
|
||||
so the morning rules (today free or sick, the window, the morning latch) never
|
||||
see the evening and the evening never sees them. The rule itself is
|
||||
``_evening_policy``; this module gathers its facts, rings and logs.
|
||||
|
||||
Events use their own names (``evening_tick``, ``evening_ring_start``,
|
||||
``evening_ring_stop``) so the morning audit never counts an evening ring as
|
||||
the morning's. An unreachable Firebase at a tick rings nothing (no event is
|
||||
known); one during a ring keeps ringing, bounded by the cap.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import replace
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import freedays
|
||||
|
||||
from wake_alarm._constants import EVENING_RING_FILE
|
||||
from wake_alarm._enforcement_payload import enforcement_view
|
||||
from wake_alarm._evening_policy import (
|
||||
FREE_TOMORROW,
|
||||
NOTIFICATIONS_OFF,
|
||||
SICK_TOMORROW,
|
||||
EveningFacts,
|
||||
decide,
|
||||
needs_fetch,
|
||||
stop_reason,
|
||||
)
|
||||
from wake_alarm._events import emit, emit_on_change
|
||||
from wake_alarm._fallback_latch import Latch, mark_started, mark_stopped, read_latch
|
||||
from wake_alarm._fallback_ring import ring
|
||||
from wake_alarm._ring_wav import SYSTEM_WAV_DIR, USER_WAV_DIR, ensure_pair
|
||||
from wake_alarm._sick import alarm_stands_down, alarm_stands_down_synced
|
||||
from wake_alarm._sync_transport import fetch_firebase_logs
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from wake_alarm._fallback_policy import Decision
|
||||
|
||||
TERMINATED = "terminated"
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
"""Aware local now; the seam tests patch."""
|
||||
return datetime.now(tz=UTC).astimezone()
|
||||
|
||||
|
||||
def _tomorrow_off(now: datetime, *, sync: bool) -> str | None:
|
||||
"""Why tomorrow rings nothing, or None; pulls the sick pool when acting."""
|
||||
tomorrow = now.date() + timedelta(days=1)
|
||||
if freedays.is_free_day(tomorrow):
|
||||
return FREE_TOMORROW
|
||||
sick = alarm_stands_down_synced if sync else alarm_stands_down
|
||||
return SICK_TOMORROW if sick(tomorrow) else None
|
||||
|
||||
|
||||
def observe_evening(now: datetime, *, sync: bool) -> EveningFacts:
|
||||
"""Gather the evening's facts; Firebase only when it can change them."""
|
||||
day = now.date().isoformat()
|
||||
facts = EveningFacts(
|
||||
now=now,
|
||||
tomorrow_off=_tomorrow_off(now, sync=sync),
|
||||
latch=read_latch(day, EVENING_RING_FILE),
|
||||
)
|
||||
if not needs_fetch(facts):
|
||||
return facts
|
||||
published = fetch_firebase_logs()
|
||||
if published is None:
|
||||
return replace(facts, reachable=False)
|
||||
return replace(
|
||||
facts, off_since=enforcement_view(published).notifications_off_since(day)
|
||||
)
|
||||
|
||||
|
||||
def _poll(off_since: datetime | None) -> str | None:
|
||||
"""Re-observe while ringing; the reason to stop, or None.
|
||||
|
||||
An unreachable Firebase keeps the off state the ring started with: fail
|
||||
toward ringing, never toward silence. The cap still ends it.
|
||||
"""
|
||||
facts = observe_evening(_now(), sync=True)
|
||||
if not facts.reachable:
|
||||
facts = replace(facts, off_since=off_since, reachable=True)
|
||||
return stop_reason(facts)
|
||||
|
||||
|
||||
def _close(latch: Latch, reason: str) -> None:
|
||||
"""Stop an open evening latch and log it."""
|
||||
stopped = mark_stopped(
|
||||
latch, now=_now(), stop_reason=reason, file=EVENING_RING_FILE
|
||||
)
|
||||
emit(
|
||||
"evening_ring_stop",
|
||||
reason,
|
||||
stop_reason=reason,
|
||||
started_at=stopped.started_at,
|
||||
stopped_at=stopped.stopped_at,
|
||||
)
|
||||
|
||||
|
||||
def ring_evening(facts: EveningFacts) -> str:
|
||||
"""Latch, ring until a stop condition, unlatch; returns the stop reason."""
|
||||
day = facts.now.date().isoformat()
|
||||
resumed = facts.latch is not None and facts.latch.started_at is not None
|
||||
latch = mark_started(
|
||||
facts.latch,
|
||||
day=day,
|
||||
now=facts.now,
|
||||
reason=NOTIFICATIONS_OFF,
|
||||
file=EVENING_RING_FILE,
|
||||
)
|
||||
off_since = facts.off_since
|
||||
emit(
|
||||
"evening_ring_start",
|
||||
NOTIFICATIONS_OFF,
|
||||
reason=NOTIFICATIONS_OFF,
|
||||
resumed=resumed,
|
||||
off_since=off_since.isoformat() if off_since else None,
|
||||
started_at=latch.started_at,
|
||||
)
|
||||
stopped = TERMINATED
|
||||
try:
|
||||
# Inside the try, as in the morning: a WAV that cannot be generated
|
||||
# must still close the latch.
|
||||
rise, loop = ensure_pair(SYSTEM_WAV_DIR, USER_WAV_DIR)
|
||||
stopped = ring(lambda: _poll(off_since), rise=rise, loop=loop)
|
||||
finally:
|
||||
_close(latch, stopped)
|
||||
return stopped
|
||||
|
||||
|
||||
def evening_tick(now: datetime) -> Decision:
|
||||
"""One 21:xx timer tick: observe, log a changed decision, ring if due."""
|
||||
facts, day = observe_evening(now, sync=True), now.date().isoformat()
|
||||
decision = decide(facts)
|
||||
emit_on_change(
|
||||
"evening_tick",
|
||||
f"{day}|{decision.ring}|{decision.reason}",
|
||||
f"{'ring' if decision.ring else 'quiet'}: {decision.reason}",
|
||||
ring=decision.ring,
|
||||
reason=decision.reason,
|
||||
reachable=facts.reachable,
|
||||
)
|
||||
latch = facts.latch
|
||||
if decision.ring:
|
||||
ring_evening(facts)
|
||||
elif latch is not None and latch.started_at and not latch.stopped_at:
|
||||
_close(latch, decision.reason)
|
||||
return decision
|
||||
|
||||
|
||||
def evening_dry_run(now: datetime) -> str:
|
||||
"""The ``--dry-run`` report for a 21:xx instant; writes nothing."""
|
||||
facts = observe_evening(now, sync=False)
|
||||
decision = decide(facts)
|
||||
verdict = "WOULD RING" if decision.ring else "quiet"
|
||||
return (
|
||||
f"{now:%Y-%m-%d %H:%M} — {verdict}: {decision.reason}\n"
|
||||
f" evening check: tomorrow_off={facts.tomorrow_off} "
|
||||
f"firebase={'ok' if facts.reachable else 'UNREACHABLE'}\n"
|
||||
f" off_since={facts.off_since}\n"
|
||||
f" latch={facts.latch}\n"
|
||||
)
|
||||
@ -201,6 +201,12 @@ def _hermetic(tmp_path: Path) -> Generator[None]:
|
||||
"wake_alarm._fallback_latch.FALLBACK_RING_FILE",
|
||||
tmp_path / "fallback_ring.json",
|
||||
),
|
||||
patch(
|
||||
"wake_alarm._fallback_evening.EVENING_RING_FILE",
|
||||
tmp_path / "evening_ring.json",
|
||||
),
|
||||
patch("wake_alarm._fallback_evening.SYSTEM_WAV_DIR", tmp_path / "wav-system"),
|
||||
patch("wake_alarm._fallback_evening.USER_WAV_DIR", tmp_path / "wav-user"),
|
||||
patch("wake_alarm._pc_wake_mode.PC_WAKE_CONFIG", tmp_path / "pc_wake.json"),
|
||||
patch("wake_alarm._audit.INCIDENTS_DIR", tmp_path / "incidents"),
|
||||
patch("wake_alarm._audit_sources.LOG_JSONL_FILE", tmp_path / "audit.jsonl"),
|
||||
|
||||
99
wake_alarm/tests/test_evening_policy.py
Normal file
99
wake_alarm/tests/test_evening_policy.py
Normal file
@ -0,0 +1,99 @@
|
||||
"""The 21:00 notifications check's rule, as pure functions (2026-11-22)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
from wake_alarm._evening_policy import (
|
||||
FREE_TOMORROW,
|
||||
NOTIFICATIONS_OFF,
|
||||
NOTIFICATIONS_ON,
|
||||
OUTSIDE_EVENING,
|
||||
SICK_TOMORROW,
|
||||
UNREACHABLE,
|
||||
EveningFacts,
|
||||
decide,
|
||||
in_evening,
|
||||
needs_fetch,
|
||||
stop_reason,
|
||||
)
|
||||
from wake_alarm._fallback_latch import Latch
|
||||
from wake_alarm._fallback_policy import CAP, Decision
|
||||
|
||||
DAY = "2026-11-22"
|
||||
NINE = datetime(2026, 11, 22, 21, 0).astimezone()
|
||||
|
||||
|
||||
def _at(minutes: float) -> datetime:
|
||||
return NINE + timedelta(minutes=minutes)
|
||||
|
||||
|
||||
def _latch(started: float, stop: str | None = None) -> Latch:
|
||||
return Latch(date=DAY, started_at=_at(started).isoformat(), stop_reason=stop)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("when", [_at(0), _at(59)])
|
||||
def test_the_21_oclock_hour_is_the_evening(when: datetime) -> None:
|
||||
assert in_evening(when)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("when", [_at(-1), _at(60)])
|
||||
def test_the_minutes_around_it_are_not(when: datetime) -> None:
|
||||
assert not in_evening(when)
|
||||
|
||||
|
||||
class TestDecide:
|
||||
def test_off_today_rings(self) -> None:
|
||||
facts = EveningFacts(now=_at(5), off_since=_at(0))
|
||||
assert decide(facts) == Decision(ring=True, reason=NOTIFICATIONS_OFF)
|
||||
|
||||
def test_no_off_event_is_quiet(self) -> None:
|
||||
facts = EveningFacts(now=_at(5))
|
||||
assert decide(facts) == Decision(ring=False, reason=NOTIFICATIONS_ON)
|
||||
|
||||
def test_outside_the_hour_nothing_starts(self) -> None:
|
||||
facts = EveningFacts(now=_at(70), off_since=_at(0))
|
||||
assert decide(facts) == Decision(ring=False, reason=OUTSIDE_EVENING)
|
||||
|
||||
@pytest.mark.parametrize("off", [FREE_TOMORROW, SICK_TOMORROW])
|
||||
def test_a_free_or_sick_tomorrow_never_rings(self, off: str) -> None:
|
||||
facts = EveningFacts(now=_at(5), off_since=_at(0), tomorrow_off=off)
|
||||
assert decide(facts) == Decision(ring=False, reason=off)
|
||||
|
||||
def test_unreachable_is_quiet_and_says_so(self) -> None:
|
||||
facts = EveningFacts(now=_at(5), reachable=False)
|
||||
assert decide(facts) == Decision(ring=False, reason=UNREACHABLE)
|
||||
|
||||
|
||||
class TestCap:
|
||||
def test_thirty_minutes_from_the_first_ring_ends_it(self) -> None:
|
||||
facts = EveningFacts(now=_at(40), off_since=_at(35), latch=_latch(10))
|
||||
assert stop_reason(facts) == CAP
|
||||
assert decide(facts) == Decision(ring=False, reason=CAP)
|
||||
|
||||
def test_a_resumed_ring_keeps_its_first_start(self) -> None:
|
||||
facts = EveningFacts(now=_at(39), off_since=_at(35), latch=_latch(10, "x"))
|
||||
assert stop_reason(facts) is None
|
||||
|
||||
def test_a_latched_cap_holds(self) -> None:
|
||||
facts = EveningFacts(now=_at(12), off_since=_at(0), latch=_latch(10, CAP))
|
||||
assert stop_reason(facts) == CAP
|
||||
|
||||
def test_a_latch_never_started_caps_nothing(self) -> None:
|
||||
facts = EveningFacts(now=_at(50), off_since=_at(0), latch=Latch(date=DAY))
|
||||
assert stop_reason(facts) is None
|
||||
|
||||
def test_a_capped_evening_does_not_fetch(self) -> None:
|
||||
assert not needs_fetch(EveningFacts(now=_at(45), latch=_latch(10)))
|
||||
assert needs_fetch(EveningFacts(now=_at(45), latch=_latch(20)))
|
||||
|
||||
def test_a_free_tomorrow_does_not_fetch(self) -> None:
|
||||
assert not needs_fetch(EveningFacts(now=_at(5), tomorrow_off=FREE_TOMORROW))
|
||||
assert needs_fetch(EveningFacts(now=_at(5)))
|
||||
|
||||
|
||||
def test_a_ring_past_22_is_judged_by_the_stop_rules_alone() -> None:
|
||||
facts = EveningFacts(now=_at(75), off_since=_at(50), latch=_latch(55))
|
||||
assert stop_reason(facts) is None
|
||||
188
wake_alarm/tests/test_fallback_evening.py
Normal file
188
wake_alarm/tests/test_fallback_evening.py
Normal file
@ -0,0 +1,188 @@
|
||||
"""The PC rings at 21:00 when the phone's notifications are off (2026-11-22).
|
||||
|
||||
Switching off "All WakeAlarm notifications" silences tomorrow's ring and no
|
||||
device policy can lock that switch, so the phone reports it as a
|
||||
``notifications`` event and the PC rings in the 21:00 hour until it is back
|
||||
on, for at most 30 minutes, unless tomorrow is a free or sick day.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime, timedelta
|
||||
import json
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from wake_alarm import _fallback, _fallback_evening, _fallback_observe
|
||||
from wake_alarm._fallback_latch import Latch, read_latch, write_latch
|
||||
from wake_alarm._fallback_policy import Decision
|
||||
from wake_alarm._sync import Alarm
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable, Generator
|
||||
from contextlib import AbstractContextManager
|
||||
|
||||
DAY = "2026-11-22"
|
||||
TOMORROW = date(2026, 11, 23)
|
||||
NINE = datetime(2026, 11, 22, 21, 0).astimezone()
|
||||
# Taken before the autouse fixture patches the seam.
|
||||
REAL_NOW = _fallback_evening._now
|
||||
|
||||
|
||||
def _at(minutes: float) -> datetime:
|
||||
return NINE + timedelta(minutes=minutes)
|
||||
|
||||
|
||||
def _notif(minutes: float, *, enabled: bool) -> dict[str, object]:
|
||||
return {
|
||||
"at": _at(minutes).isoformat(),
|
||||
"kind": "notifications",
|
||||
"data": {"enabled": enabled, "trigger": "evening"},
|
||||
}
|
||||
|
||||
|
||||
def _log(*events: dict[str, object]) -> list[tuple[str, str]]:
|
||||
fields = {"phone_events": [list(events), "h"]}
|
||||
return [("p", json.dumps({"alarm": {"fields": fields}}))]
|
||||
|
||||
|
||||
def _evening_latch() -> Latch | None:
|
||||
return read_latch(DAY, _fallback_evening.EVENING_RING_FILE)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def world() -> Generator[MagicMock]:
|
||||
with (
|
||||
patch.object(_fallback_observe, "get_alarm", return_value=Alarm(7, 0, "c")),
|
||||
patch.object(_fallback_evening, "ensure_pair", return_value=("r", "l")),
|
||||
patch.object(_fallback_evening, "_now", return_value=_at(8)),
|
||||
patch.object(_fallback_evening, "ring") as ring,
|
||||
):
|
||||
|
||||
def fake_ring(poll: Callable[[], str | None], **_: object) -> str:
|
||||
return poll() or "still"
|
||||
|
||||
ring.side_effect = fake_ring
|
||||
yield ring
|
||||
|
||||
|
||||
def _fetch(
|
||||
*answers: list[tuple[str, str]] | None,
|
||||
) -> AbstractContextManager[MagicMock]:
|
||||
return patch.object(_fallback_evening, "fetch_firebase_logs", side_effect=answers)
|
||||
|
||||
|
||||
def test_off_rings_until_a_newer_event_says_on(world: MagicMock) -> None:
|
||||
with _fetch(_log(_notif(0, enabled=False)), _log(_notif(7, enabled=True))):
|
||||
decision = _fallback.tick(_at(5))
|
||||
assert decision == Decision(ring=True, reason="notifications_off")
|
||||
world.assert_called_once()
|
||||
latch = _evening_latch()
|
||||
assert latch is not None
|
||||
assert latch.started_at == _at(5).isoformat()
|
||||
assert latch.stop_reason == "notifications_on"
|
||||
assert read_latch(DAY) is None
|
||||
|
||||
|
||||
def test_no_event_today_rings_nothing(world: MagicMock) -> None:
|
||||
with _fetch(_log()):
|
||||
decision = _fallback.tick(_at(5))
|
||||
assert decision == Decision(ring=False, reason="notifications_on")
|
||||
world.assert_not_called()
|
||||
|
||||
|
||||
def test_an_unreachable_tick_rings_nothing(world: MagicMock) -> None:
|
||||
with _fetch(None):
|
||||
assert _fallback.tick(_at(5)).reason == "firebase_unreachable"
|
||||
world.assert_not_called()
|
||||
|
||||
|
||||
def test_an_unreachable_poll_keeps_ringing() -> None:
|
||||
with _fetch(_log(_notif(0, enabled=False)), None):
|
||||
_fallback.tick(_at(5))
|
||||
latch = _evening_latch()
|
||||
assert latch is not None
|
||||
assert latch.stop_reason == "still"
|
||||
|
||||
|
||||
def test_a_free_tomorrow_never_rings_or_fetches(world: MagicMock) -> None:
|
||||
with (
|
||||
patch.object(
|
||||
_fallback_evening.freedays, "is_free_day", side_effect=TOMORROW.__eq__
|
||||
),
|
||||
_fetch() as fetch,
|
||||
):
|
||||
assert _fallback.tick(_at(5)).reason == "free_tomorrow"
|
||||
fetch.assert_not_called()
|
||||
world.assert_not_called()
|
||||
|
||||
|
||||
def test_a_sick_tomorrow_never_rings(world: MagicMock) -> None:
|
||||
with (
|
||||
patch.object(_fallback_evening, "alarm_stands_down_synced") as sick,
|
||||
_fetch(),
|
||||
):
|
||||
sick.side_effect = TOMORROW.__eq__
|
||||
assert _fallback.tick(_at(5)).reason == "sick_tomorrow"
|
||||
world.assert_not_called()
|
||||
|
||||
|
||||
def test_a_free_today_before_a_workday_still_rings(world: MagicMock) -> None:
|
||||
today = NINE.date()
|
||||
with (
|
||||
patch.object(
|
||||
_fallback_evening.freedays, "is_free_day", side_effect=today.__eq__
|
||||
),
|
||||
_fetch(_log(_notif(0, enabled=False)), _log(_notif(7, enabled=True))),
|
||||
):
|
||||
assert _fallback.tick(_at(5)).ring
|
||||
world.assert_called_once()
|
||||
|
||||
|
||||
def test_a_capped_evening_stays_quiet_without_fetching(world: MagicMock) -> None:
|
||||
write_latch(
|
||||
Latch(date=DAY, started_at=_at(0).isoformat()),
|
||||
_fallback_evening.EVENING_RING_FILE,
|
||||
)
|
||||
with _fetch() as fetch:
|
||||
assert _fallback.tick(_at(31)).reason == "cap"
|
||||
fetch.assert_not_called()
|
||||
world.assert_not_called()
|
||||
latch = _evening_latch()
|
||||
assert latch is not None
|
||||
assert latch.stop_reason == "cap"
|
||||
|
||||
|
||||
def test_the_catch_up_tick_after_22_is_the_morning_path(world: MagicMock) -> None:
|
||||
with _fetch() as fetch:
|
||||
assert _fallback.tick(_at(90)).reason == "outside_window"
|
||||
fetch.assert_not_called()
|
||||
world.assert_not_called()
|
||||
|
||||
|
||||
def test_dry_run_reports_and_writes_nothing(
|
||||
capsys: pytest.CaptureFixture[str],
|
||||
) -> None:
|
||||
with (
|
||||
_fetch(_log(_notif(0, enabled=False))),
|
||||
patch.object(_fallback_evening, "alarm_stands_down_synced") as synced,
|
||||
):
|
||||
_fallback.main(["--dry-run", "--at", _at(5).isoformat()])
|
||||
out = capsys.readouterr().out
|
||||
assert "WOULD RING: notifications_off" in out
|
||||
assert "off_since=2026-11-22 21:00" in out
|
||||
synced.assert_not_called()
|
||||
assert _evening_latch() is None
|
||||
|
||||
|
||||
def test_dry_run_outside_the_hour_is_the_morning_report(
|
||||
capsys: pytest.CaptureFixture[str],
|
||||
) -> None:
|
||||
_fallback.main(["--dry-run", "--at", _at(90).isoformat()])
|
||||
assert "quiet: outside_window" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_the_clock_seam_is_aware_local_now() -> None:
|
||||
assert REAL_NOW().tzinfo is not None
|
||||
Loading…
Reference in New Issue
Block a user