Add a web server for printing from the site, deployed on stppi
CI / test (3.12) (push) Failing after 43s
CI / test (3.10) (push) Failing after 6m6s
CI / test (3.13) (push) Failing after 36s

`./receipt.py serve` (receipt_web.py, the new [web] extra) serves a page
for printing a note or an uploaded image. The site's nginx gates
/receipt/ on the admin session and proxies to it over Tailscale, adding
X-Receipt-Token; nothing but /healthz answers without it, and POSTs also
need X-Requested-With: receipt. Jobs run one at a time behind a lock
around run_action(), and uploads print from memory.

run_action(), _dispatch() and setup_network_quiet() move from the TUI to
receipt.py so the server doesn't need textual. --no-setup (needs_setup())
skips the sudo connect script everywhere it would run; serve always sets
it. cmd_print takes in-memory `data`.

deploy/ has the systemd user units. receipt-update.timer runs update.sh
every 5 minutes: it fast-forwards the clone from Gitea, runs the tests
and restarts receipt-web, rolling back if they fail.

Also included from earlier uncommitted work: the CI matrix moved to the
right place, connect_receipt.sh no longer re-parses CLI values in
bash -c, RECEIPT_PRINTER_IP/PORT are validated, pyusb is declared, the
ruff S rules are on, and the img/ cache and junk/ are no longer tracked.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-23 21:22:31 +01:00
co-authored by Claude Opus 5.5
parent e333d6729f
commit f55b20fb82
65 changed files with 1142 additions and 124712 deletions
+38
View File
@@ -0,0 +1,38 @@
"""Shared test fakes."""
import argparse
class FakePrinter:
"""Records escpos calls instead of talking to hardware."""
def __init__(self):
self.calls = []
def textln(self, text=""):
self.calls.append(("textln", text))
def image(self, img, **kwargs):
self.calls.append(("image", img))
def qr(self, content, **kwargs):
self.calls.append(("qr", content))
def cut(self):
self.calls.append(("cut", None))
def close(self):
self.calls.append(("close", None))
def make_args(**overrides):
defaults = {
"usb": True, # avoids the network setup script in tests
"ip": "192.168.192.168",
"port": 9100,
"timestamp": False,
"message": None,
"name": None,
}
defaults.update(overrides)
return argparse.Namespace(**defaults)
+249 -35
View File
@@ -1,6 +1,8 @@
import argparse
import io
import pytest
from conftest import FakePrinter, make_args
from PIL import Image
import receipt
@@ -17,46 +19,21 @@ class FakeResponse:
def json(self):
return self._json
def __enter__(self):
return self
class FakePrinter:
"""Records escpos calls instead of talking to hardware."""
def __exit__(self, *exc):
return False
def __init__(self):
self.calls = []
def textln(self, text=""):
self.calls.append(("textln", text))
def image(self, img, **kwargs):
self.calls.append(("image", img))
def qr(self, content, **kwargs):
self.calls.append(("qr", content))
def cut(self):
self.calls.append(("cut", None))
def close(self):
self.calls.append(("close", None))
def iter_content(self, chunk_size):
for i in range(0, len(self.content), chunk_size):
yield self.content[i : i + chunk_size]
def make_catalog(threads):
return [{"threads": threads}]
def make_args(**overrides):
defaults = {
"usb": True, # avoids the network setup script in tests
"ip": receipt.DEFAULT_PRINTER_IP,
"port": receipt.DEFAULT_PRINTER_PORT,
"timestamp": False,
"message": None,
"name": None,
}
defaults.update(overrides)
return argparse.Namespace(**defaults)
def test_prepare_for_print_resizes_and_dithers(tmp_path):
src = tmp_path / "wide.png"
Image.new("RGB", (200, 100), "gray").save(src)
@@ -100,7 +77,7 @@ def test_download_saves_image(tmp_path, monkeypatch):
catalog = make_catalog([{"tim": 12345, "ext": ".jpg"}])
calls = []
def fake_get(url, timeout):
def fake_get(url, timeout, stream=False):
calls.append(url)
if url == receipt.BANT_CATALOG_URL:
return FakeResponse(json_data=catalog)
@@ -123,7 +100,7 @@ def test_download_reuses_cached_image(tmp_path, monkeypatch):
catalog = make_catalog([{"tim": 12345, "ext": ".jpg"}])
calls = []
def fake_get(url, timeout):
def fake_get(url, timeout, stream=False):
calls.append(url)
return FakeResponse(json_data=catalog)
@@ -248,5 +225,242 @@ def test_parser_handles_all_subcommands():
args = parser.parse_args(["reprint", "12345"])
assert args.name == "12345"
for cmd in ("status", "list", "clean", "reprint"):
for cmd in ("status", "list", "clean", "reprint", "serve"):
assert parser.parse_args([cmd]).command == cmd
args = parser.parse_args(["--no-setup", "serve", "--listen", "127.0.0.1:9000"])
assert args.no_setup and args.listen == "127.0.0.1:9000"
def test_cmd_clean_removes_files_but_not_dirs(tmp_path, monkeypatch, capsys):
img_dir = tmp_path / "img"
legacy = tmp_path / "img_fullwidth"
img_dir.mkdir()
legacy.mkdir()
(img_dir / "1.png").write_bytes(b"x")
(img_dir / "subdir").mkdir() # must not crash the sweep
(legacy / "2.png").write_bytes(b"x")
(legacy / "subdir").mkdir()
monkeypatch.setattr(receipt, "IMG_DIR", img_dir)
monkeypatch.setattr(receipt, "LEGACY_FULLWIDTH_DIR", legacy)
assert receipt.cmd_clean(yes=True) == 0
assert list(img_dir.iterdir()) == [img_dir / "subdir"]
assert list(legacy.iterdir()) == [legacy / "subdir"]
def test_cmd_clean_nothing_to_do(tmp_path, monkeypatch):
monkeypatch.setattr(receipt, "IMG_DIR", tmp_path / "img")
monkeypatch.setattr(receipt, "LEGACY_FULLWIDTH_DIR", tmp_path / "legacy")
assert receipt.cmd_clean(yes=True) == 0
def test_cmd_image_continues_past_failures(monkeypatch):
monkeypatch.setattr(receipt, "download_random_bant_image", lambda: None)
p = FakePrinter()
assert receipt.cmd_image(p, make_args(count=2)) == 1 # nothing printed
assert p.calls == []
def test_cmd_image_prints_and_cuts(monkeypatch, tmp_path):
from PIL import Image
img = tmp_path / "1.png"
Image.new("RGB", (10, 10)).save(img)
monkeypatch.setattr(receipt, "download_random_bant_image", lambda: img)
monkeypatch.setattr(receipt, "prepare_for_print", lambda p: Image.new("1", (576, 10)))
p = FakePrinter()
assert receipt.cmd_image(p, make_args(count=2)) == 0
kinds = [c[0] for c in p.calls]
assert kinds.count("image") == 2
assert kinds.count("cut") == 2
def test_download_size_cap(tmp_path, monkeypatch):
monkeypatch.setattr(receipt, "IMG_DIR", tmp_path / "img")
catalog = make_catalog([{"tim": 7, "ext": ".png"}])
class BigBody(FakeResponse):
def iter_content(self, chunk_size):
yield b"x" * (receipt.MAX_IMAGE_BYTES // 2)
yield b"x" * (receipt.MAX_IMAGE_BYTES + 1) # push over the cap
def fake_get(url, timeout, stream=False):
return BigBody(json_data=catalog) if url == receipt.BANT_CATALOG_URL else BigBody()
monkeypatch.setattr(receipt.requests, "get", fake_get)
assert receipt.download_random_bant_image() is None
assert not (tmp_path / "img" / "7.png").exists()
def test_valid_ip_rejects_metacharacters():
import argparse as ap
with pytest.raises(ap.ArgumentTypeError):
receipt._valid_ip("$(id)")
with pytest.raises(ap.ArgumentTypeError):
receipt._valid_ip("999.1.1.1")
assert receipt._valid_ip(" 10.0.0.5 ") == "10.0.0.5"
def test_wrap_unbreakable_long_token():
token = "x" * 80
wrapped = receipt.wrap_text(token)
assert all(len(line) <= receipt.TEXT_COLUMNS for line in wrapped.split("\n"))
def test_print_image_retries_once_on_failure(monkeypatch, tmp_path):
class Flaky:
def __init__(self, tag):
self.tag = tag
self.calls = []
def image(self, img, **kwargs):
self.calls.append("image")
if self.tag == 1:
raise OSError("dropped")
def close(self):
self.calls.append("close")
def textln(self, t):
self.calls.append(("textln", t))
def cut(self):
self.calls.append("cut")
first = Flaky(1)
second = Flaky(2)
monkeypatch.setattr(receipt, "get_printer", lambda args: second)
monkeypatch.setattr(receipt, "setup_network", lambda args: None)
args = make_args()
img = tmp_path / "x.png"
Image.new("RGB", (10, 10)).save(img)
monkeypatch.setattr(receipt, "prepare_for_print", lambda p: Image.new("1", (576, 10)))
p = receipt.print_image(first, img, args)
assert p is second # caller keeps the live handle
assert "close" in first.calls
assert second.calls == ["image"]
assert args._printer is second # main() closes this one
def test_print_image_retry_skips_setup_with_no_setup(monkeypatch):
class Flaky(FakePrinter):
def image(self, img, **kwargs):
raise OSError("dropped")
second = FakePrinter()
monkeypatch.setattr(receipt, "get_printer", lambda args: second)
monkeypatch.setattr(
receipt, "setup_network", lambda args: pytest.fail("should not run the connect script")
)
monkeypatch.setattr(receipt, "prepare_for_print", lambda p: Image.new("1", (576, 10)))
p = receipt.print_image(Flaky(), "unused", make_args(usb=False, no_setup=True))
assert p is second
def test_cmd_print_from_memory(tmp_path):
buf = io.BytesIO()
Image.new("RGBA", (40, 20), (0, 0, 0, 0)).save(buf, "PNG")
p = FakePrinter()
rc = receipt.cmd_print(p, make_args(path=None, data=buf.getvalue(), message="cap"))
assert rc == 0
assert [c[0] for c in p.calls] == ["textln", "image", "cut"]
assert p.calls[1][1].size[0] == receipt.PRINT_WIDTH_PX
assert list(tmp_path.iterdir()) == []
# ---- run_action (shared by the TUI and the web server) ----
@pytest.fixture
def fake_printer(monkeypatch):
p = FakePrinter()
monkeypatch.setattr(receipt, "get_printer", lambda args: p)
return p
def test_run_action_note(fake_printer):
rc, output = receipt.run_action("note", make_args(), text="hello", timestamp=False)
assert rc == 0
assert ("textln", "hello") in fake_printer.calls
assert fake_printer.calls[-2] == ("cut", None)
assert fake_printer.calls[-1] == ("close", None) # handle released after action
def test_run_action_qr(fake_printer):
rc, _ = receipt.run_action("qr", make_args(), content="https://example.com", message=None)
assert rc == 0
assert ("qr", "https://example.com") in fake_printer.calls
def test_run_action_reprint_uses_cache(fake_printer, tmp_path, monkeypatch):
img_dir = tmp_path / "img"
img_dir.mkdir()
Image.new("RGB", (10, 10)).save(img_dir / "12345.png")
monkeypatch.setattr(receipt, "IMG_DIR", img_dir)
rc, _ = receipt.run_action("reprint", make_args(), name="12345")
assert rc == 0
assert ("textln", "12345") in fake_printer.calls
def test_run_action_captures_output_and_errors(monkeypatch):
def boom(args):
raise OSError("no printer")
monkeypatch.setattr(receipt, "get_printer", boom)
rc, output = receipt.run_action("note", make_args(), text="hi", timestamp=False)
assert rc == 1
assert "no printer" in output
def test_run_action_list_needs_no_printer(monkeypatch, tmp_path):
monkeypatch.setattr(receipt, "IMG_DIR", tmp_path / "img")
monkeypatch.setattr(receipt, "get_printer", lambda args: pytest.fail("should not connect"))
rc, output = receipt.run_action("list", make_args())
assert rc == 0
assert "empty" in output
def test_run_action_no_setup_skips_connect_script(fake_printer, monkeypatch):
def fail(args):
pytest.fail("should not run the connect script")
monkeypatch.setattr(receipt, "setup_network", fail)
monkeypatch.setattr(receipt, "setup_network_quiet", fail)
rc, _ = receipt.run_action(
"note", make_args(usb=False, no_setup=True), text="hi", timestamp=False
)
assert rc == 0
def test_run_action_status_runs_connect_script_once(fake_printer, monkeypatch):
calls = []
monkeypatch.setattr(receipt, "setup_network_quiet", lambda args: calls.append("quiet"))
monkeypatch.setattr(receipt, "setup_network", lambda args: calls.append("loud"))
rc, output = receipt.run_action("status", make_args(usb=False))
assert rc == 0
assert calls == ["quiet"] # captured; cmd_status doesn't rerun it uncaptured
assert "reachable" in output
-86
View File
@@ -1,33 +1,12 @@
import argparse
import pytest
from PIL import Image
import receipt
receipt_tui = pytest.importorskip("receipt_tui")
class FakePrinter:
def __init__(self):
self.calls = []
def textln(self, text=""):
self.calls.append(("textln", text))
def image(self, img, **kwargs):
self.calls.append(("image", img))
def qr(self, content, **kwargs):
self.calls.append(("qr", content))
def cut(self):
self.calls.append(("cut", None))
def close(self):
self.calls.append(("close", None))
def make_base_args(**overrides):
defaults = {
"usb": True, # avoids the network setup script in tests
@@ -39,70 +18,5 @@ def make_base_args(**overrides):
return argparse.Namespace(**defaults)
@pytest.fixture
def fake_printer(monkeypatch):
p = FakePrinter()
monkeypatch.setattr(receipt, "get_printer", lambda args: p)
return p
def test_run_action_note(fake_printer):
rc, output = receipt_tui.run_action(
"note", make_base_args(), text="hello", timestamp=False
)
assert rc == 0
assert ("textln", "hello") in fake_printer.calls
assert fake_printer.calls[-2] == ("cut", None)
assert fake_printer.calls[-1] == ("close", None) # handle released after action
def test_run_action_qr(fake_printer):
rc, _ = receipt_tui.run_action(
"qr", make_base_args(), content="https://example.com", message=None
)
assert rc == 0
assert ("qr", "https://example.com") in fake_printer.calls
def test_run_action_reprint_uses_cache(fake_printer, tmp_path, monkeypatch):
img_dir = tmp_path / "img"
img_dir.mkdir()
Image.new("RGB", (10, 10)).save(img_dir / "12345.png")
monkeypatch.setattr(receipt, "IMG_DIR", img_dir)
rc, _ = receipt_tui.run_action("reprint", make_base_args(), name="12345")
assert rc == 0
assert ("textln", "12345") in fake_printer.calls
def test_run_action_captures_output_and_errors(monkeypatch):
def boom(args):
raise OSError("no printer")
monkeypatch.setattr(receipt, "get_printer", boom)
rc, output = receipt_tui.run_action(
"note", make_base_args(), text="hi", timestamp=False
)
assert rc == 1
assert "no printer" in output
def test_run_action_list_needs_no_printer(monkeypatch, tmp_path):
monkeypatch.setattr(receipt, "IMG_DIR", tmp_path / "img")
monkeypatch.setattr(
receipt, "get_printer", lambda args: pytest.fail("should not connect")
)
rc, output = receipt_tui.run_action("list", make_base_args())
assert rc == 0
assert "empty" in output
def test_parser_accepts_tui():
assert receipt.build_parser().parse_args(["tui"]).command == "tui"
+147
View File
@@ -0,0 +1,147 @@
import io
import pytest
from conftest import 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 args: p)
return p
@pytest.fixture
def client():
base = make_args(usb=False, no_setup=True)
return TestClient(receipt_web.create_app(base, TOKEN))
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})
assert res.status_code == 200
assert res.json()["ok"] is True
assert ("textln", "hello") in fake_printer.calls
assert fake_printer.calls[-2:] == [("cut", None), ("close", None)]
@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 "reachable" in res.json()["output"]
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 res.status_code == 200, res.text
kinds = [c[0] for c in fake_printer.calls]
assert kinds == ["textln", "image", "cut", "close"]
assert fake_printer.calls[0] == ("textln", "caption")
assert fake_printer.calls[1][1].size[0] == receipt.PRINT_WIDTH_PX
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_is_502(client, monkeypatch):
def boom(args):
raise OSError("no printer")
monkeypatch.setattr(receipt, "get_printer", boom)
res = client.post("/api/note", headers=HEADERS, json={"text": "hi"})
assert res.status_code == 502
assert res.json() == {"ok": False, "output": "Error: no printer"}
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