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

324 lines
12 KiB
Python

import io
import pytest
from conftest import CUT, INIT, FakePrinter, make_args
from PIL import Image
import receipt
pytest.importorskip("fastapi")
pytest.importorskip("multipart")
from fastapi.testclient import TestClient # noqa: E402
import receipt_web # noqa: E402
TOKEN = "t" * 32
HEADERS = {"X-Receipt-Token": TOKEN, "X-Requested-With": "receipt"}
@pytest.fixture
def fake_printer(monkeypatch):
p = FakePrinter()
monkeypatch.setattr(receipt, "get_printer", lambda config: p)
return p
@pytest.fixture
def client():
config = receipt.PrinterConfig(no_setup=True)
return TestClient(receipt_web.create_app(config, TOKEN))
def finished_job(client, res):
"""Wait for the job a POST queued and return its final record."""
assert res.status_code == 202, res.text
job = res.json()["job"]
res = client.get(f"/api/jobs/{job['id']}?wait=5", headers=HEADERS)
assert res.status_code == 200
job = res.json()["job"]
assert job["state"] in receipt_web.FINISHED
return job
def png_bytes(size=(20, 10)):
buf = io.BytesIO()
Image.new("RGB", size, "gray").save(buf, "PNG")
return buf.getvalue()
def test_healthz_is_open(client):
assert client.get("/healthz").json() == {"ok": True}
@pytest.mark.parametrize("token", [None, "wrong"])
@pytest.mark.parametrize("method,path", [("get", "/"), ("get", "/api/status"),
("post", "/api/note")])
def test_token_required(client, fake_printer, token, method, path):
headers = {"X-Requested-With": "receipt"}
if token:
headers["X-Receipt-Token"] = token
res = client.request(method, path, headers=headers, json={"text": "hi"})
assert res.status_code == 401
assert fake_printer.calls == []
def test_page_served_with_token(client):
res = client.get("/", headers={"X-Receipt-Token": TOKEN})
assert res.status_code == 200
assert "Receipt printer" in res.text
def test_post_needs_page_header(client, fake_printer):
res = client.post("/api/note", headers={"X-Receipt-Token": TOKEN}, json={"text": "hi"})
assert res.status_code == 403
assert fake_printer.calls == []
def test_note_prints(client, fake_printer):
res = client.post("/api/note", headers=HEADERS, json={"text": "hello", "timestamp": False})
job = finished_job(client, res)
assert (job["state"], job["message"]) == ("done", "Printed.")
assert fake_printer.calls == ["open", "raw", "close"]
assert b"hello" in fake_printer.payloads[0]
def test_note_size(client, fake_printer):
res = client.post("/api/note", headers=HEADERS, json={"text": "hello", "size": 3})
finished_job(client, res)
assert receipt.render_note("hello", size=3) == fake_printer.payloads[0]
def test_note_over_paper_budget_is_400(client, fake_printer):
res = client.post("/api/note", headers=HEADERS, json={"text": "x\n" * 1000, "size": 3})
assert res.status_code == 400
assert "too long" in res.json()["detail"]
assert fake_printer.calls == []
@pytest.mark.parametrize("size", [0, 4])
def test_note_rejects_bad_size(client, fake_printer, size):
res = client.post("/api/note", headers=HEADERS, json={"text": "hi", "size": size})
assert res.status_code == 422
assert fake_printer.calls == []
@pytest.mark.parametrize("text", ["", " ", "x" * (receipt_web.MAX_NOTE_CHARS + 1)])
def test_note_rejects_empty_and_long(client, fake_printer, text):
res = client.post("/api/note", headers=HEADERS, json={"text": text})
assert res.status_code in (400, 422)
assert fake_printer.calls == []
def test_status_reports_reachable(client, fake_printer):
res = client.get("/api/status", headers=HEADERS)
assert res.status_code == 200
assert res.json()["busy"] is False
assert "reachable" in res.json()["output"]
assert fake_printer.calls == ["open", "close"] # a real connect, not just a handle
def test_status_unreachable_is_503(client, monkeypatch):
monkeypatch.setattr(receipt, "get_printer", lambda config: FakePrinter(fail_open=2))
res = client.get("/api/status", headers=HEADERS)
assert res.status_code == 503
assert res.json()["ok"] is False
def test_status_does_not_wait_behind_a_print(client, fake_printer):
jobs = client.app.state.jobs
with jobs.printer_lock: # as if the worker were mid-print
res = client.get("/api/status", headers=HEADERS)
assert res.json()["busy"] is True
assert fake_printer.calls == []
def test_unknown_job_is_404(client):
assert client.get("/api/jobs/nope", headers=HEADERS).status_code == 404
def test_job_records_the_nginx_user(client, fake_printer):
res = client.post(
"/api/note", headers={**HEADERS, "X-Remote-User": "adam"}, json={"text": "hi"}
)
finished_job(client, res)
assert client.app.state.jobs._jobs[res.json()["job"]["id"]].user == "adam"
def test_full_queue_is_503(client, fake_printer, monkeypatch):
jobs = client.app.state.jobs
monkeypatch.setattr(jobs, "_pending", receipt_web.queue.Queue(1))
jobs._pending.put_nowait(("placeholder", b"")) # the worker is parked on the old queue
res = client.post("/api/note", headers=HEADERS, json={"text": "hi"})
assert res.status_code == 503
def test_image_prints_from_memory(client, fake_printer):
res = client.post(
"/api/image",
headers=HEADERS,
files={"file": ("x.png", png_bytes(), "image/png")},
data={"message": "caption"},
)
assert finished_job(client, res)["state"] == "done"
payload = fake_printer.payloads[0]
assert payload.startswith(INIT) and payload.endswith(CUT)
assert b"caption\n" in payload
def test_image_rejects_non_image(client, fake_printer):
res = client.post(
"/api/image", headers=HEADERS, files={"file": ("x.png", b"not an image", "image/png")}
)
assert res.status_code == 400
assert fake_printer.calls == []
def test_image_rejects_oversize(client, fake_printer, monkeypatch):
monkeypatch.setattr(receipt, "MAX_IMAGE_BYTES", 100)
res = client.post(
"/api/image", headers=HEADERS, files={"file": ("x.png", png_bytes((200, 200)), "image/png")}
)
assert res.status_code == 413
assert fake_printer.calls == []
def test_printer_error_fails_the_job(client, monkeypatch):
monkeypatch.setattr(receipt, "get_printer", lambda config: FakePrinter(fail_open=2))
res = client.post("/api/note", headers=HEADERS, json={"text": "hi"})
job = finished_job(client, res)
assert (job["state"], job["error"]) == ("failed", "unavailable")
assert "no route to printer" in job["message"]
def test_serve_refuses_without_token(monkeypatch, capsys):
monkeypatch.delenv(receipt_web.TOKEN_ENV, raising=False)
rc = receipt_web.serve(make_args(listen="127.0.0.1:8765"))
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