Files
adamfandClaude Opus 5.5 597bace442
CI / test (3.10) (push) Failing after 56s
CI / test (3.12) (push) Failing after 42s
CI / test (3.13) (push) Failing after 47s
Send each print as one job, queue web prints, and harden deploys
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]>
2026-10-23 22:07:58 +01:00

512 lines
17 KiB
Python

import argparse
import io
import pytest
from conftest import CUT, INIT, FakePrinter, escpos_bytes, make_args
from PIL import Image
import receipt
class FakeResponse:
def __init__(self, json_data=None, content=b""):
self._json = json_data
self.content = content
def raise_for_status(self):
pass
def json(self):
return self._json
def __enter__(self):
return self
def __exit__(self, *exc):
return False
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 test_prepare_for_print_resizes_and_dithers(tmp_path):
src = tmp_path / "wide.png"
Image.new("RGB", (200, 100), "gray").save(src)
prepared = receipt.prepare_for_print(src)
assert prepared.size == (receipt.PRINT_WIDTH_PX, receipt.PRINT_WIDTH_PX // 2)
assert prepared.mode == "1"
def test_prepare_for_print_composites_transparency_onto_white(tmp_path):
src = tmp_path / "transparent.png"
Image.new("RGBA", (100, 100), (0, 0, 0, 0)).save(src)
prepared = receipt.prepare_for_print(src)
# Fully transparent input must come out white (255), not black
assert prepared.getpixel((288, 288)) == 255
def test_wrap_text_wraps_long_lines_and_keeps_blank_lines():
long_line = "word " * 20
wrapped = receipt.wrap_text(f"{long_line}\n\nshort")
lines = wrapped.split("\n")
assert all(len(line) <= receipt.TEXT_COLUMNS for line in lines)
assert "" in lines # blank line preserved
assert lines[-1] == "short"
def test_positive_int_rejects_zero_and_negatives():
with pytest.raises(argparse.ArgumentTypeError):
receipt.positive_int("0")
with pytest.raises(argparse.ArgumentTypeError):
receipt.positive_int("-3")
assert receipt.positive_int("2") == 2
def test_download_saves_image(tmp_path, monkeypatch):
monkeypatch.setattr(receipt, "IMG_DIR", tmp_path / "img")
catalog = make_catalog([{"tim": 12345, "ext": ".jpg"}])
calls = []
def fake_get(url, timeout, stream=False):
calls.append(url)
if url == receipt.BANT_CATALOG_URL:
return FakeResponse(json_data=catalog)
return FakeResponse(content=b"jpegbytes")
monkeypatch.setattr(receipt.requests, "get", fake_get)
dest = receipt.download_random_bant_image()
assert dest.name == "12345.jpg"
assert dest.read_bytes() == b"jpegbytes"
assert calls == [receipt.BANT_CATALOG_URL, "https://i.4cdn.org/bant/12345.jpg"]
def test_download_reuses_cached_image(tmp_path, monkeypatch):
img_dir = tmp_path / "img"
img_dir.mkdir()
(img_dir / "12345.jpg").write_bytes(b"cached")
monkeypatch.setattr(receipt, "IMG_DIR", img_dir)
catalog = make_catalog([{"tim": 12345, "ext": ".jpg"}])
calls = []
def fake_get(url, timeout, stream=False):
calls.append(url)
return FakeResponse(json_data=catalog)
monkeypatch.setattr(receipt.requests, "get", fake_get)
dest = receipt.download_random_bant_image()
assert dest.read_bytes() == b"cached"
assert calls == [receipt.BANT_CATALOG_URL] # image itself not re-fetched
def test_download_skips_unprintable_formats(tmp_path, monkeypatch):
monkeypatch.setattr(receipt, "IMG_DIR", tmp_path / "img")
catalog = make_catalog(
[{"tim": 1, "ext": ".gif"}, {"tim": 2, "ext": ".webm"}, {"no_image": True}]
)
monkeypatch.setattr(
receipt.requests, "get", lambda url, timeout: FakeResponse(json_data=catalog)
)
assert receipt.download_random_bant_image() is None
@pytest.fixture
def fake_printer(monkeypatch):
p = FakePrinter()
monkeypatch.setattr(receipt, "get_printer", lambda config: p)
return p
CONFIG = receipt.PrinterConfig(usb=True) # usb avoids the network setup script
def test_render_note_is_one_reset_job_with_one_cut():
payload = receipt.render_note("hello " * 20)
assert payload.startswith(INIT)
assert payload.endswith(CUT)
assert payload.count(CUT) == 1
assert receipt.wrap_text("hello " * 20).encode() in payload
def test_render_note_large_size_wraps_narrower():
payload = receipt.render_note("hello " * 20, size=2)
big = escpos_bytes(lambda p: p.set(custom_size=True, width=2, height=2))
assert payload.startswith(INIT + big)
assert receipt.wrap_text("hello " * 20, receipt.TEXT_COLUMNS // 2).encode() in payload
def test_render_note_timestamp_header():
payload = receipt.render_note("hi", timestamp=True)
assert b"-" * receipt.TEXT_COLUMNS in payload
assert payload.index(b"-" * receipt.TEXT_COLUMNS) < payload.index(b"hi\n")
@pytest.mark.parametrize("text", ["", " \n "])
def test_render_note_rejects_empty(text):
with pytest.raises(receipt.InvalidJob, match="Nothing to print"):
receipt.render_note(text)
def test_render_note_rejects_over_paper_budget():
max_lines = receipt.MAX_PRINT_HEIGHT_DOTS // receipt.LINE_HEIGHT_DOTS // 3
receipt.render_note("x\n" * max_lines, size=3) # exactly at the limit is fine
with pytest.raises(receipt.InvalidJob, match="too long"):
receipt.render_note("x\n" * (max_lines + 1), size=3)
def test_cmd_note_sends_once_and_closes(fake_printer):
rc = receipt.cmd_note(CONFIG, make_args(text="hello"))
assert rc == 0
assert fake_printer.calls == ["open", "raw", "close"]
assert b"hello" in fake_printer.payloads[0]
def test_cmd_qr_prints_content_and_caption(fake_printer):
rc = receipt.cmd_qr(CONFIG, make_args(content="https://example.com", message="scan me"))
assert rc == 0
# The QR raster as escpos renders it; the caption already selected the codepage.
expected_qr = escpos_bytes(lambda p: p.qr("https://example.com", size=8, center=True))
assert b"scan me" in fake_printer.payloads[0]
assert expected_qr.removeprefix(b"\x1bt\x00") in fake_printer.payloads[0]
def test_send_retries_a_failed_connect(monkeypatch):
p = FakePrinter(fail_open=1)
monkeypatch.setattr(receipt, "get_printer", lambda config: p)
receipt.send(CONFIG, b"job")
assert p.calls == ["open", "open", "raw", "close"]
assert p.payloads == [b"job"]
def test_send_gives_up_after_two_failed_connects(monkeypatch):
p = FakePrinter(fail_open=2)
monkeypatch.setattr(receipt, "get_printer", lambda config: p)
with pytest.raises(receipt.PrinterUnavailable, match="can't reach"):
receipt.send(CONFIG, b"job")
assert "raw" not in p.calls
def test_send_never_replays_after_a_mid_job_drop(monkeypatch):
p = FakePrinter(fail_raw=True)
monkeypatch.setattr(receipt, "get_printer", lambda config: p)
with pytest.raises(receipt.PrinterUnavailable, match="partially"):
receipt.send(CONFIG, b"job")
assert p.calls == ["open", "raw", "close"] # one attempt; a retry could print it twice
def test_connect_reruns_setup_on_retry(monkeypatch):
p = FakePrinter(fail_open=1)
setups = []
monkeypatch.setattr(receipt, "get_printer", lambda config: p)
monkeypatch.setattr(receipt, "setup_network", setups.append)
receipt.connect(receipt.PrinterConfig())
assert len(setups) == 2
def test_connect_skips_setup_with_no_setup(monkeypatch):
monkeypatch.setattr(receipt, "get_printer", lambda config: FakePrinter())
monkeypatch.setattr(
receipt, "setup_network", lambda config: pytest.fail("should not run the connect script")
)
receipt.connect(receipt.PrinterConfig(no_setup=True))
def test_cmd_reprint_picks_most_recent(fake_printer, tmp_path, monkeypatch):
img_dir = tmp_path / "img"
img_dir.mkdir()
older = img_dir / "old.png"
newer = img_dir / "new.png"
Image.new("RGB", (10, 10)).save(older)
Image.new("RGB", (10, 10)).save(newer)
import os
os.utime(older, (1000, 1000))
os.utime(newer, (2000, 2000))
monkeypatch.setattr(receipt, "IMG_DIR", img_dir)
rc = receipt.cmd_reprint(CONFIG, make_args())
assert rc == 0
assert b"new\n" in fake_printer.payloads[0]
def test_cmd_reprint_by_stem(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.cmd_reprint(CONFIG, make_args(name="12345"))
assert rc == 0
assert b"12345\n" in fake_printer.payloads[0]
def test_cmd_reprint_unknown_name(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)
with pytest.raises(receipt.InvalidJob, match="No cached image"):
receipt.cmd_reprint(CONFIG, make_args(name="nope"))
assert fake_printer.calls == []
def test_parser_handles_all_subcommands():
parser = receipt.build_parser()
args = parser.parse_args(["image", "3"])
assert args.command == "image" and args.count == 3
args = parser.parse_args(["--usb", "note", "hello", "-t"])
assert args.usb and args.text == "hello" and args.timestamp
args = parser.parse_args(["note"])
assert args.text is None and args.size == 1 # stdin mode
args = parser.parse_args(["note", "big", "--size", "3"])
assert args.size == 3
args = parser.parse_args(["--ip", "10.0.0.5", "--port", "9101", "status"])
assert args.ip == "10.0.0.5" and args.port == 9101
args = parser.parse_args(["qr", "https://example.com", "scan me"])
assert args.content == "https://example.com" and args.message == "scan me"
args = parser.parse_args(["reprint", "12345"])
assert args.name == "12345"
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(fake_printer, monkeypatch):
monkeypatch.setattr(receipt, "download_random_bant_image", lambda: None)
assert receipt.cmd_image(CONFIG, make_args(count=2)) == 1 # nothing printed
assert fake_printer.calls == []
def test_cmd_image_sends_each_image_as_its_own_job(fake_printer, monkeypatch, tmp_path):
img = tmp_path / "1.png"
Image.new("RGB", (10, 10)).save(img)
monkeypatch.setattr(receipt, "download_random_bant_image", lambda: img)
assert receipt.cmd_image(CONFIG, make_args(count=2)) == 0
assert len(fake_printer.payloads) == 2
assert all(job.startswith(INIT) and job.count(CUT) == 1 for job in fake_printer.payloads)
def test_cmd_image_skips_a_corrupt_download(fake_printer, monkeypatch, tmp_path):
bad = tmp_path / "1.png"
bad.write_bytes(b"not an image")
monkeypatch.setattr(receipt, "download_random_bant_image", lambda: bad)
assert receipt.cmd_image(CONFIG, make_args(count=1)) == 1
assert fake_printer.payloads == []
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_prepare_for_print_shrinks_very_tall_images(tmp_path):
src = tmp_path / "strip.png"
Image.new("RGB", (100, 10_000), "gray").save(src) # would be 57600 dots at full width
prepared = receipt.prepare_for_print(src)
assert prepared.size == (receipt.PRINT_WIDTH_PX, receipt.MAX_PRINT_HEIGHT_DOTS)
assert prepared.getpixel((0, 0)) == 255 # white margin around the centered strip
def test_render_image_rejects_non_images():
with pytest.raises(receipt.InvalidJob, match="Not a printable image"):
receipt.render_image(io.BytesIO(b"not an image"))
def test_cmd_print_from_memory(fake_printer, tmp_path):
buf = io.BytesIO()
Image.new("RGBA", (40, 20), (0, 0, 0, 0)).save(buf, "PNG")
rc = receipt.cmd_print(CONFIG, make_args(path=None, data=buf.getvalue(), message="cap"))
assert rc == 0
payload = fake_printer.payloads[0]
assert payload.startswith(INIT)
assert payload.index(b"cap\n") < payload.index(b"\x1b*") # caption, then the bit image
assert payload.endswith(CUT)
assert list(tmp_path.iterdir()) == []
def test_cmd_print_missing_file(fake_printer, tmp_path):
with pytest.raises(receipt.InvalidJob, match="File not found"):
receipt.cmd_print(CONFIG, make_args(path=tmp_path / "nope.png"))
assert fake_printer.calls == []
def test_cmd_status_actually_connects(monkeypatch):
p = FakePrinter(fail_open=2)
monkeypatch.setattr(receipt, "get_printer", lambda config: p)
with pytest.raises(receipt.PrinterUnavailable):
receipt.cmd_status(receipt.PrinterConfig(no_setup=True))
# ---- run_action (used by the TUI) ----
def test_run_action_note(fake_printer):
result = receipt.run_action("note", make_args(), text="hello", timestamp=False)
assert result.rc == 0 and result.error is None
assert b"hello" in fake_printer.payloads[0]
assert fake_printer.calls[-1] == "close" # handle released after action
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)
result = receipt.run_action("reprint", make_args(), name="12345")
assert result.rc == 0
assert b"12345\n" in fake_printer.payloads[0]
def test_run_action_classifies_printer_errors(monkeypatch):
monkeypatch.setattr(receipt, "get_printer", lambda config: FakePrinter(fail_open=2))
result = receipt.run_action("note", make_args(), text="hi", timestamp=False)
assert (result.rc, result.error) == (1, "unavailable")
assert "no route to printer" in result.output
def test_run_action_classifies_invalid_jobs(fake_printer):
result = receipt.run_action("note", make_args(), text=" ", timestamp=False)
assert (result.rc, result.error) == (1, "invalid")
assert result.output == "Nothing to print."
assert fake_printer.calls == []
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 config: pytest.fail("should not connect"))
result = receipt.run_action("list", make_args())
assert result.rc == 0
assert "empty" in result.output
def test_run_action_runs_setup_quietly_once(fake_printer, monkeypatch):
configs = []
monkeypatch.setattr(receipt, "setup_network", configs.append)
result = receipt.run_action("status", make_args(usb=False))
assert result.rc == 0
assert [c.quiet_setup for c in configs] == [True] # captured, so it can't corrupt the TUI
assert "reachable" in result.output
def test_run_action_no_setup_skips_connect_script(fake_printer, monkeypatch):
monkeypatch.setattr(
receipt, "setup_network", lambda config: pytest.fail("should not run the connect script")
)
result = receipt.run_action(
"note", make_args(usb=False, no_setup=True), text="hi", timestamp=False
)
assert result.rc == 0