Render every print to a complete ESC/POS payload (reset, content, cut)
and send it once over a fresh connection. Only the connect is retried,
so a link that drops mid-job can no longer print a partial image followed
by a full one, and no text size leaks into the next job. Prints are
capped at about 1 m of paper: tall images shrink, over-long notes are
refused.
Replace the argparse/stdout plumbing with PrinterConfig, InvalidJob and
PrinterUnavailable, and one run_command() dispatcher shared by the CLI
and TUI. Status now really connects; before, escpos's lazy open meant
the web server always reported the printer ready. Rendering with the
TM-T20II profile makes QR centering take effect.
The web server validates and renders jobs in the request (400 on bad
input), queues them for a single worker and answers 202; the page
long-polls /api/jobs/{id}, so no request outlives nginx's proxy timeout
while its job still prints. Status reports busy instead of waiting, and
jobs are logged with the nginx user.
update.sh tests new commits in a scratch worktree before touching the
live clone, and rolls back if /healthz doesn't answer after the restart.
The unit runs from the venv, and the web server defaults to localhost.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
222 lines
6.8 KiB
Python
222 lines
6.8 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
|