Files
receipt_maker/tests/test_triggers.py
T
adamfandClaude Opus 5.5 ba92f1fbda
CI / test (3.10) (push) Successful in 1m20s
CI / test (3.12) (push) Successful in 1m49s
CI / test (3.13) (push) Successful in 1m5s
Add scheduled and event-driven printing with a new web UI
The web server now runs a scheduler over schedules kept in SQLite
(~/.local/share/receipt-maker, outside the clone). A schedule is a
trigger, a receipt made of blocks, and options:

- Triggers: once, recurring (rrule-based, DST-safe), sun times,
  reminders before calendar (ICS) events, RSS/JSON watchers, webhooks
  with per-schedule secrets.
- Blocks, rendered fresh as one job: templated notes ({date},
  {days_until:..}, rotating {choice}, trigger vars), QR, saved images,
  random image, calendar agenda, feed headlines, dividers.
- Rules: quiet hours (hold/skip/ignore), daily cap, pause, catch-up
  window for missed runs (never replayed), retries on connect failure
  only; a mid-job drop (new PrinterDropped) is never resent.

receipt.py renders through composable Blocks (render_note/image/qr are
wrappers, output unchanged). Print history persists, with Print again.
The page moves to web/ with Print (note/image/QR + paper preview),
Schedules (presets, editor with live preview and next runs), History
and Settings tabs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-23 23:58:26 +01:00

181 lines
7.1 KiB
Python

import datetime as dt
import pytest
from conftest import FIXTURES
pytest.importorskip("dateutil")
pytest.importorskip("pydantic")
from pydantic import TypeAdapter # noqa: E402
import receipt_models as models # noqa: E402
import receipt_triggers as triggers # noqa: E402
from receipt_sources import parse_events # noqa: E402
from receipt_store import UTC # noqa: E402
TRIGGER = TypeAdapter(models.Trigger)
LONDON = models.Settings(location={"latitude": 51.5, "longitude": -0.12})
NOON_FRI = dt.datetime(2026, 10, 23, 11, 0, tzinfo=UTC) # 12:00 BST, a Friday
def trigger(**spec):
return TRIGGER.validate_python(spec)
def local(times):
return [t.astimezone(LONDON.tz).strftime("%a %d %b %H:%M") for t in times]
def test_weekdays_at_two_times():
t = trigger(type="recurring", times=["18:00", "07:30"], weekdays=[0, 1, 2, 3, 4])
assert triggers.describe(t, LONDON) == "Weekdays at 07:30 and 18:00"
assert local(triggers.upcoming(t, NOON_FRI, LONDON, 3)) == [
"Fri 23 Oct 18:00", "Mon 26 Oct 07:30", "Mon 26 Oct 18:00",
]
def test_first_weekday_of_the_month():
t = trigger(type="recurring", freq="monthly", times=["09:00"], weekdays=[0, 1, 2, 3, 4],
setpos=1)
assert triggers.describe(t, LONDON) == "Every month on the first weekday at 09:00"
# 1 Nov 2026 is a Sunday, so the first weekday is Monday the 2nd.
assert local(triggers.upcoming(t, NOON_FRI, LONDON, 2)) == [
"Mon 02 Nov 09:00", "Tue 01 Dec 09:00",
]
def test_last_day_of_the_month():
t = trigger(type="recurring", freq="monthly", times=["09:00"], monthday=-1)
assert triggers.describe(t, LONDON) == "Every month on the last day at 09:00"
assert local(triggers.upcoming(t, NOON_FRI, LONDON, 2)) == [
"Sat 31 Oct 09:00", "Mon 30 Nov 09:00",
]
def test_every_other_week_counts_from_the_start_date():
t = trigger(type="recurring", freq="weekly", interval=2, times=["09:00"], weekdays=[0],
start="2026-10-19")
assert triggers.describe(t, LONDON) == "Every 2 weeks on Mon at 09:00"
assert local(triggers.upcoming(t, NOON_FRI, LONDON, 2)) == [
"Mon 02 Nov 09:00", "Mon 16 Nov 09:00",
]
def test_yearly_and_until():
t = trigger(type="recurring", freq="yearly", times=["08:00"], month=12, monthday=25,
until="2027-12-31")
assert triggers.describe(t, LONDON) == "Every year on 25 Dec at 08:00, until 31 Dec 2027"
assert len(triggers.upcoming(t, NOON_FRI, LONDON, 5)) == 2
def test_custom_rule_keeps_the_times():
t = trigger(type="recurring", times=["09:00"], rrule="FREQ=MONTHLY;BYDAY=-1FR")
assert local(triggers.upcoming(t, NOON_FRI, LONDON, 1)) == ["Fri 30 Oct 09:00"]
def test_bad_custom_rule():
t = trigger(type="recurring", times=["09:00"], rrule="FREQ=SOMETIMES")
with pytest.raises(triggers.TriggerError, match="custom rule"):
triggers.next_fire(t, NOON_FRI, LONDON)
def test_fall_back_fires_once():
# 01:30 happens twice in London on 25 Oct 2026; the first (BST) one fires.
t = trigger(type="recurring", times=["01:30"])
times = triggers.upcoming(t, dt.datetime(2026, 10, 24, 12, tzinfo=UTC), LONDON, 3)
assert [x.isoformat() for x in times] == [
"2026-10-25T00:30:00+00:00", "2026-10-26T01:30:00+00:00", "2026-10-27T01:30:00+00:00",
]
def test_spring_forward_shifts_the_missing_time():
# 01:30 doesn't exist in London on 29 Mar 2026: it fires at 02:30 BST instead.
t = trigger(type="recurring", times=["01:30"])
first = triggers.next_fire(t, dt.datetime(2026, 3, 28, 12, tzinfo=UTC), LONDON)
assert first.astimezone(LONDON.tz).strftime("%d %H:%M %Z") == "29 02:30 BST"
def test_once():
t = trigger(type="once", at="2026-10-24T09:00")
assert triggers.describe(t, LONDON) == "Once, Sat 24 Oct 2026 at 09:00"
assert local([triggers.next_fire(t, NOON_FRI, LONDON)]) == ["Sat 24 Oct 09:00"]
assert triggers.next_fire(t, NOON_FRI + dt.timedelta(days=2), LONDON) is None
def test_sun_times():
t = trigger(type="sun", event="sunrise", offset_minutes=-30)
midsummer = dt.datetime(2026, 6, 20, 12, tzinfo=UTC)
at = triggers.next_fire(t, midsummer, LONDON).astimezone(LONDON.tz)
assert triggers.describe(t, LONDON) == "30 min before sunrise"
assert at.date() == dt.date(2026, 6, 21)
assert dt.time(4, 5) <= at.time() <= dt.time(4, 20) # sunrise is about 04:43 BST
def test_sun_needs_a_location():
t = trigger(type="sun", event="sunset")
assert "set a location" in triggers.describe(t, models.Settings())
with pytest.raises(triggers.TriggerError, match="location"):
triggers.next_fire(t, NOON_FRI, models.Settings())
def test_calendar_fires_skip_exdates_cancellations_and_all_day():
start = dt.datetime(2026, 10, 26, tzinfo=LONDON.tz)
events = parse_events((FIXTURES / "calendar.ics").read_bytes(), start,
start + dt.timedelta(days=3), LONDON.tz)
t = trigger(type="calendar", source_id="x", minutes_before=10)
fires = [(at.astimezone(LONDON.tz).strftime("%a %H:%M"), e.title)
for at, e in triggers.calendar_fires(t, events)]
assert fires == [
("Mon 09:20", "Team standup"),
("Mon 13:50", "Dentist"), # 14:00 UTC is 14:00 GMT after the clocks change
("Wed 09:20", "Team standup"), # Tuesday's is an EXDATE
]
assert triggers.describe(t, LONDON, lambda _id: "Work") == "10 min before events in Work"
def test_calendar_filters():
start = dt.datetime(2026, 10, 26, tzinfo=LONDON.tz)
events = parse_events((FIXTURES / "calendar.ics").read_bytes(), start,
start + dt.timedelta(days=3), LONDON.tz)
dentist = trigger(type="calendar", source_id="x", contains="DENT")
all_day = trigger(type="calendar", source_id="x", contains="holiday", include_all_day=True)
assert [e.title for _, e in triggers.calendar_fires(dentist, events)] == ["Dentist"]
assert [e.title for _, e in triggers.calendar_fires(all_day, events)] == ["Bank holiday"]
@pytest.mark.parametrize("spec,text", [
({"type": "recurring", "times": ["08:00"]}, "Every day at 08:00"),
({"type": "recurring", "times": ["08:00"], "weekdays": [5, 6]}, "Weekends at 08:00"),
({"type": "recurring", "times": ["08:00"], "weekdays": [0, 2, 4]},
"Mon, Wed and Fri at 08:00"),
({"type": "recurring", "freq": "monthly", "times": ["08:00"], "monthday": 12},
"Every month on the 12th at 08:00"),
({"type": "recurring", "freq": "monthly", "times": ["08:00"], "weekdays": [4],
"setpos": -1}, "Every month on the last Fri at 08:00"),
({"type": "sun", "event": "sunset", "offset_minutes": 90}, "1 h 30 min after sunset"),
({"type": "watch", "url": "https://example.com/feed"},
"New items in example.com, checked every 30 min"),
({"type": "watch", "kind": "json", "url": "https://api.test/x", "path": "price",
"condition": "above", "threshold": 100},
"When price at api.test goes above 100, checked every 30 min"),
({"type": "webhook"}, "When its webhook is called (up to 10 an hour)"),
])
def test_describe(spec, text):
assert triggers.describe(trigger(**spec), LONDON) == text