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]>
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
"""Shared test fakes."""
|
||||
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
|
||||
from escpos import printer
|
||||
|
||||
@@ -54,3 +55,34 @@ def make_args(**overrides):
|
||||
}
|
||||
defaults.update(overrides)
|
||||
return argparse.Namespace(**defaults)
|
||||
|
||||
|
||||
FIXTURES = Path(__file__).parent / "fixtures"
|
||||
CALENDAR_URL = "https://calendar.test/work.ics"
|
||||
FEED_URL = "https://feed.test/rss.xml"
|
||||
|
||||
|
||||
class FakeCache:
|
||||
"""Stands in for receipt_sources.SourceCache: canned bodies by URL, no network."""
|
||||
|
||||
def __init__(self, bodies=None):
|
||||
self.bodies = {
|
||||
CALENDAR_URL: (FIXTURES / "calendar.ics").read_bytes(),
|
||||
FEED_URL: (FIXTURES / "feed.xml").read_bytes(),
|
||||
**(bodies or {}),
|
||||
}
|
||||
self.gets = []
|
||||
|
||||
def get(self, url, max_age):
|
||||
from receipt_sources import SourceError
|
||||
|
||||
self.gets.append(url)
|
||||
body = self.bodies.get(url)
|
||||
if isinstance(body, Exception):
|
||||
raise body
|
||||
if body is None:
|
||||
raise SourceError("couldn't connect")
|
||||
return body
|
||||
|
||||
def forget(self, url):
|
||||
pass
|
||||
|
||||
Vendored
+33
@@ -0,0 +1,33 @@
|
||||
BEGIN:VCALENDAR
|
||||
VERSION:2.0
|
||||
PRODID:-//receipt-maker tests//EN
|
||||
BEGIN:VEVENT
|
||||
UID:standup@test
|
||||
DTSTART;TZID=Europe/London:20261019T093000
|
||||
DTEND;TZID=Europe/London:20261019T094500
|
||||
RRULE:FREQ=DAILY
|
||||
EXDATE;TZID=Europe/London:20261027T093000
|
||||
SUMMARY:Team standup
|
||||
LOCATION:Room 4
|
||||
END:VEVENT
|
||||
BEGIN:VEVENT
|
||||
UID:holiday@test
|
||||
DTSTART;VALUE=DATE:20261028
|
||||
DTEND;VALUE=DATE:20261029
|
||||
SUMMARY:Bank holiday
|
||||
END:VEVENT
|
||||
BEGIN:VEVENT
|
||||
UID:dentist@test
|
||||
DTSTART:20261026T140000Z
|
||||
DTEND:20261026T150000Z
|
||||
SUMMARY:Dentist
|
||||
LOCATION:High St
|
||||
END:VEVENT
|
||||
BEGIN:VEVENT
|
||||
UID:cancelled@test
|
||||
DTSTART:20261026T160000Z
|
||||
DTEND:20261026T170000Z
|
||||
SUMMARY:Cancelled thing
|
||||
STATUS:CANCELLED
|
||||
END:VEVENT
|
||||
END:VCALENDAR
|
||||
Vendored
+10
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<rss version="2.0">
|
||||
<channel>
|
||||
<title>Test Feed</title>
|
||||
<item><guid>post-3</guid><title>Third post</title><link>https://example.com/3</link>
|
||||
<description><p>The <b>third</b> one</p></description></item>
|
||||
<item><guid>post-2</guid><title>Second post</title><link>https://example.com/2</link></item>
|
||||
<item><guid>post-1</guid><title>First post</title><link>https://example.com/1</link></item>
|
||||
</channel>
|
||||
</rss>
|
||||
@@ -0,0 +1,237 @@
|
||||
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"
|
||||
@@ -0,0 +1,180 @@
|
||||
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
|
||||
@@ -219,3 +219,105 @@ def test_serve_refuses_without_token(monkeypatch, capsys):
|
||||
|
||||
assert rc == 1
|
||||
assert receipt_web.TOKEN_ENV in capsys.readouterr().err
|
||||
|
||||
|
||||
SCHEDULE = {"name": "Chore", "trigger": {"type": "recurring", "times": ["08:00"]},
|
||||
"blocks": [{"type": "note", "text": "Water the plants"}]}
|
||||
|
||||
|
||||
def test_static_files_need_the_token(client):
|
||||
assert client.get("/static/app.js").status_code == 401
|
||||
res = client.get("/static/app.js", headers=HEADERS)
|
||||
assert res.status_code == 200 and "javascript" in res.headers["content-type"]
|
||||
assert client.get("/static/..%2Freceipt.py", headers=HEADERS).status_code == 404
|
||||
|
||||
|
||||
def test_schedule_crud(client):
|
||||
res = client.post("/api/schedules", headers=HEADERS, json=SCHEDULE)
|
||||
assert res.status_code == 201, res.text
|
||||
schedule = res.json()["schedule"]
|
||||
assert schedule["summary"] == "Every day at 08:00"
|
||||
assert schedule["next_run_at"]
|
||||
|
||||
edited = {**SCHEDULE, "trigger": {"type": "recurring", "times": ["09:15"],
|
||||
"weekdays": [5, 6]}}
|
||||
res = client.put(f"/api/schedules/{schedule['id']}", headers=HEADERS, json=edited)
|
||||
assert res.json()["schedule"]["summary"] == "Weekends at 09:15"
|
||||
|
||||
res = client.post(f"/api/schedules/{schedule['id']}/duplicate", headers=HEADERS)
|
||||
assert res.json()["schedule"]["enabled"] is False
|
||||
assert len(client.get("/api/schedules", headers=HEADERS).json()["schedules"]) == 2
|
||||
|
||||
assert client.delete(f"/api/schedules/{schedule['id']}", headers=HEADERS).status_code == 200
|
||||
assert client.get(f"/api/schedules/{schedule['id']}", headers=HEADERS).status_code == 404
|
||||
|
||||
|
||||
@pytest.mark.parametrize("change,status", [
|
||||
({"blocks": []}, 422),
|
||||
({"trigger": {"type": "recurring", "times": []}}, 422),
|
||||
({"trigger": {"type": "sun", "event": "sunset"}}, 400), # no location set
|
||||
({"trigger": {"type": "calendar", "source_id": "missing"}}, 400),
|
||||
({"trigger": {"type": "watch", "url": "file:///etc/passwd"}}, 422),
|
||||
])
|
||||
def test_schedule_validation(client, change, status):
|
||||
assert client.post("/api/schedules", headers=HEADERS,
|
||||
json={**SCHEDULE, **change}).status_code == status
|
||||
|
||||
|
||||
def test_schedule_test_print(client, fake_printer):
|
||||
schedule = client.post("/api/schedules", headers=HEADERS, json=SCHEDULE).json()["schedule"]
|
||||
|
||||
res = client.post(f"/api/schedules/{schedule['id']}/run", headers=HEADERS)
|
||||
|
||||
assert finished_job(client, res)["state"] == "done"
|
||||
assert b"Water the plants" in fake_printer.payloads[0]
|
||||
|
||||
|
||||
def test_preview(client):
|
||||
res = client.post("/api/preview", headers=HEADERS, json={"blocks": [
|
||||
{"type": "note", "text": "Hi {nope}"}, {"type": "qr", "content": "https://x.test"}]})
|
||||
|
||||
body = res.json()
|
||||
assert body["parts"][0]["text"] == "Hi {nope}"
|
||||
assert body["parts"][1]["image"].startswith("data:image/png;base64,")
|
||||
assert body["warnings"] == ["Unknown variable {nope}"]
|
||||
|
||||
|
||||
def test_webhook(client, fake_printer):
|
||||
hook = {**SCHEDULE, "trigger": {"type": "webhook", "per_hour": 1},
|
||||
"blocks": [{"type": "note", "text": "{payload.text}"}]}
|
||||
schedule = client.post("/api/schedules", headers=HEADERS, json=hook).json()["schedule"]
|
||||
path, secret = f"/{schedule['hook_path']}", schedule["secret"]
|
||||
token = {"X-Receipt-Token": TOKEN}
|
||||
|
||||
assert client.post(path, content=b"hi").status_code == 401
|
||||
assert client.post(path, headers=token, content=b"hi").status_code == 404
|
||||
assert client.post(f"{path}?key=wrong", headers=token, content=b"hi").status_code == 404
|
||||
res = client.post(path, headers={**token, "X-Hook-Secret": secret}, content=b"Buy milk")
|
||||
assert finished_job(client, res)["state"] == "done"
|
||||
assert b"Buy milk" in fake_printer.payloads[0]
|
||||
res = client.post(f"{path}?key={secret}", headers=token, json={"text": "again"})
|
||||
assert res.status_code == 429
|
||||
big = b"x" * (receipt_web.MAX_HOOK_BODY + 1)
|
||||
assert client.post(f"{path}?key={secret}", headers=token, content=big).status_code == 413
|
||||
|
||||
|
||||
def test_history_and_reprint(client, fake_printer):
|
||||
finished_job(client, client.post("/api/note", headers=HEADERS, json={"text": "again"}))
|
||||
run = client.get("/api/runs", headers=HEADERS).json()["runs"][0]
|
||||
assert (run["name"], run["state"], run["has_payload"]) == ("again", "done", 1)
|
||||
|
||||
res = client.post(f"/api/runs/{run['id']}/reprint", headers=HEADERS)
|
||||
|
||||
assert finished_job(client, res)["state"] == "done"
|
||||
assert fake_printer.payloads[0] == fake_printer.payloads[1]
|
||||
|
||||
|
||||
def test_source_in_use_cant_be_deleted(client):
|
||||
source = client.post("/api/sources", headers=HEADERS, json={
|
||||
"name": "Work", "kind": "ics", "url": "webcal://cal.test/x.ics"}).json()["source"]
|
||||
assert source["url"] == "https://cal.test/x.ics"
|
||||
client.post("/api/schedules", headers=HEADERS, json={
|
||||
**SCHEDULE, "trigger": {"type": "calendar", "source_id": source["id"]}})
|
||||
|
||||
assert client.delete(f"/api/sources/{source['id']}", headers=HEADERS).status_code == 409
|
||||
|
||||
Reference in New Issue
Block a user