Files
receipt_maker/tests/test_web.py
T
adamfandClaude Opus 5.5 0d4e2130a6
CI / test (3.10) (push) Successful in 1m24s
CI / test (3.12) (push) Successful in 1m5s
CI / test (3.13) (push) Successful in 1m3s
Add serve --local for using the web page on this machine
The page is unreachable without nginx, since every route but /healthz
needs the X-Receipt-Token header it adds. `serve --local` serves it
without a token instead: it only binds to a loopback address and answers
only requests whose Host is localhost, 127.0.0.1 or ::1, so another site
can't reach it by DNS rebinding. POSTs still need the page header.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-14 22:24:52 +00:00

363 lines
13 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", local=False))
assert rc == 1
assert receipt_web.TOKEN_ENV in capsys.readouterr().err
def test_local_serve_refuses_other_addresses(capsys):
rc = receipt_web.serve(make_args(listen="0.0.0.0:8765", local=True))
assert rc == 1
assert "localhost" in capsys.readouterr().err
@pytest.fixture
def local_client():
config = receipt.PrinterConfig(no_setup=True)
return TestClient(receipt_web.create_app(config, None), base_url="http://localhost:8765")
def test_local_mode_needs_no_token(local_client, fake_printer):
assert "Receipt printer" in local_client.get("/").text
res = local_client.post("/api/note", headers={"X-Requested-With": "receipt"},
json={"text": "hi"})
job = finished_job(local_client, res)
assert job["state"] == "done"
assert fake_printer.calls == ["open", "raw", "close"]
@pytest.mark.parametrize("host", ["evil.example", "192.168.1.5:8765"])
def test_local_mode_refuses_other_hosts(local_client, fake_printer, host):
res = local_client.post("/api/note", json={"text": "hi"},
headers={"Host": host, "X-Requested-With": "receipt"})
assert res.status_code == 400
assert local_client.get("/", headers={"Host": host}).status_code == 400
assert fake_printer.calls == []
def test_local_mode_still_needs_page_header(local_client, fake_printer):
assert local_client.post("/api/note", json={"text": "hi"}).status_code == 403
assert fake_printer.calls == []
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