Files
receipt_maker/tests/test_scheduler.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

238 lines
7.7 KiB
Python

import datetime as dt
from types import SimpleNamespace
import pytest
from conftest import CALENDAR_URL, FEED_URL, FakeCache
pytest.importorskip("dateutil")
pytest.importorskip("pydantic")
import receipt_content # noqa: E402
from receipt_scheduler import QueueFull, RateLimited, Scheduler # noqa: E402
from receipt_store import UTC, Store, iso # noqa: E402
MON_0729 = dt.datetime(2026, 10, 26, 7, 29, tzinfo=UTC) # GMT, so local time too
class FakeJobs:
def __init__(self, store):
self.store = store
self.submitted = []
self.full = False
def submit(self, kind, payload, user, *, source="manual", schedule_id=None, name=None):
if self.full:
raise QueueFull
job = SimpleNamespace(id=f"job{len(self.submitted)}", state="queued", error=None,
message="", payload=payload)
self.store.add_run(kind, source, "queued", run_id=job.id, schedule_id=schedule_id,
created_at=MON_0729)
self.submitted.append(job)
return job
@pytest.fixture
def env():
store = Store()
store.save_settings({"timezone": "Europe/London", "daily_cap": 30})
jobs = FakeJobs(store)
empty = b"BEGIN:VCALENDAR\r\nVERSION:2.0\r\nEND:VCALENDAR\r\n"
cache = FakeCache({"https://calendar.test/empty.ics": empty})
sched = Scheduler(store, jobs, clock=lambda: MON_0729, cache=cache)
return store, jobs, sched
def note(text):
return {"type": "note", "text": text}
def add(store, sched, trigger, blocks=None, **options):
row = store.add_schedule("test", {"trigger": trigger, "blocks": blocks or [note("hi")],
"options": options})
return sched.reschedule(row, MON_0729)
DAILY_0730 = {"type": "recurring", "times": ["07:30"]}
def test_fires_when_due_and_advances(env):
store, jobs, sched = env
row = add(store, sched, DAILY_0730)
sched.tick(MON_0729)
assert jobs.submitted == []
sched.tick(MON_0729 + dt.timedelta(minutes=1))
assert len(jobs.submitted) == 1
assert b"hi" in jobs.submitted[0].payload
assert store.schedule(row["id"])["next_run_at"] == "2026-10-27T07:30:00Z"
def test_missed_run_is_logged_not_printed(env):
store, jobs, sched = env
row = add(store, sched, DAILY_0730)
sched.tick(MON_0729 + dt.timedelta(hours=2))
assert jobs.submitted == []
assert store.runs()[0]["state"] == "missed"
assert store.schedule(row["id"])["next_run_at"] == "2026-10-27T07:30:00Z"
def test_once_turns_itself_off(env):
store, jobs, sched = env
row = add(store, sched, {"type": "once", "at": "2026-10-26T07:30"})
sched.tick(MON_0729 + dt.timedelta(minutes=1))
assert len(jobs.submitted) == 1
assert store.schedule(row["id"])["enabled"] is False
def test_quiet_hours_hold_until_they_end(env):
store, jobs, sched = env
store.save_settings({"quiet_start": "22:00", "quiet_end": "08:00"})
row = add(store, sched, DAILY_0730)
sched.tick(MON_0729 + dt.timedelta(minutes=1))
assert jobs.submitted == []
assert store.schedule(row["id"])["next_run_at"] == "2026-10-26T08:00:00Z"
sched.tick(dt.datetime(2026, 10, 26, 8, 0, 30, tzinfo=UTC))
assert len(jobs.submitted) == 1
def test_quiet_hours_skip_and_pause(env):
store, jobs, sched = env
store.save_settings({"quiet_start": "22:00", "quiet_end": "08:00"})
add(store, sched, DAILY_0730, quiet="skip")
sched.tick(MON_0729 + dt.timedelta(minutes=1))
assert jobs.submitted == []
assert store.runs()[0]["state"] == "skipped"
def test_daily_cap(env):
store, jobs, sched = env
store.save_settings({"daily_cap": 1})
store.add_run("schedule", "schedule", "done", created_at=MON_0729)
add(store, sched, DAILY_0730)
sched.tick(MON_0729 + dt.timedelta(minutes=1))
assert jobs.submitted == []
assert "limit" in store.runs()[0]["message"]
def test_queue_full_retries_next_tick(env):
store, jobs, sched = env
add(store, sched, DAILY_0730)
jobs.full = True
sched.tick(MON_0729 + dt.timedelta(minutes=1))
jobs.full = False
sched.tick(MON_0729 + dt.timedelta(minutes=2))
assert len(jobs.submitted) == 1
@pytest.mark.parametrize("error,retried", [("unavailable", True), ("dropped", False)])
def test_retries_connect_failures_only(env, error, retried):
store, jobs, sched = env
add(store, sched, DAILY_0730)
sched.tick(MON_0729 + dt.timedelta(minutes=1))
job = jobs.submitted[0]
job.state, job.error = "failed", error
sched.job_finished(job)
sched.tick(MON_0729 + dt.timedelta(minutes=10))
assert len(jobs.submitted) == (2 if retried else 1)
def test_note_choices_rotate(env):
store, jobs, sched = env
add(store, sched, DAILY_0730, blocks=[{"type": "note", "choices": ["A1", "B2"]}])
sched.tick(MON_0729 + dt.timedelta(minutes=1))
sched.tick(MON_0729 + dt.timedelta(days=1, minutes=1))
assert b"A1" in jobs.submitted[0].payload
assert b"B2" in jobs.submitted[1].payload
def test_watcher_primes_then_prints_new_items(env):
store, jobs, sched = env
row = add(store, sched, {"type": "watch", "url": FEED_URL, "every_minutes": 5},
blocks=[note("{item.title}")])
sched.tick(MON_0729)
assert jobs.submitted == [] # first look only records what's there
seen = store.state(row["id"], "seen")
store.set_state(row["id"], "seen", seen[1:]) # as if "Third post" were new
sched.tick(MON_0729 + dt.timedelta(minutes=6))
assert len(jobs.submitted) == 1
assert b"Third post" in jobs.submitted[0].payload
assert b"Second post" not in jobs.submitted[0].payload
def test_calendar_reminders_fire_once_across_restarts(env):
store, jobs, sched = env
source = store.add_source("Work", "ics", CALENDAR_URL)
add(store, sched, {"type": "calendar", "source_id": source["id"], "minutes_before": 10},
blocks=[note("{event.title} at {event.start}")])
at = dt.datetime(2026, 10, 26, 9, 20, 30, tzinfo=UTC) # standup 09:30 GMT
sched.tick(at)
Scheduler(store, jobs, cache=FakeCache()).tick(at + dt.timedelta(seconds=30))
assert len(jobs.submitted) == 1
assert b"Team standup at 09:30" in jobs.submitted[0].payload
def test_webhook_rate_limit(env):
store, jobs, sched = env
row = add(store, sched, {"type": "webhook", "per_hour": 1}, blocks=[note("{payload.text}")])
job, _ = sched.fire_webhook(row, {"text": "hello"}, MON_0729)
assert b"hello" in job.payload
with pytest.raises(RateLimited):
sched.fire_webhook(row, {"text": "again"}, MON_0729)
def test_skip_if_empty(env):
store, jobs, sched = env
source = store.add_source("Empty", "ics", "https://calendar.test/empty.ics")
agenda = {"type": "agenda", "source_ids": [source["id"]]}
add(store, sched, DAILY_0730, blocks=[agenda], skip_if_empty=True)
sched.tick(MON_0729 + dt.timedelta(minutes=1))
assert jobs.submitted == []
assert store.runs()[0]["state"] == "skipped"
def test_template_never_reaches_attributes():
warnings = []
now = dt.datetime(2026, 12, 20, tzinfo=UTC)
text = receipt_content.fill(
"{x.__class__} {payload.__class__} {{lit}} {days_until:12-25} {nope}",
now, {"payload": {"a": 1}}, warnings,
)
assert text == "{x.__class__} {lit} 5 {nope}"
assert warnings == ["Unknown variable {x.__class__}", "Unknown variable {nope}"]
def test_store_keeps_payloads_for_recent_runs_only(monkeypatch):
store = Store()
monkeypatch.setattr("receipt_store.KEEP_PAYLOADS", 2)
for i in range(3):
store.add_run("note", "manual", "done", payload=b"x",
created_at=MON_0729 + dt.timedelta(minutes=i))
assert [r["has_payload"] for r in store.runs()] == [1, 1, 0]
assert iso(MON_0729) == "2026-10-26T07:29:00Z"