- note --size 1|2|3 magnifies the text and wraps to 48/24/16 columns, then resets the printer to normal size - Web page gets a Size menu defaulting to Large; the API validates it - README/CLAUDE.md: the printer has no Wi-Fi (UB-E04 needs an adapter), so it is cabled to stppi's eth0 at 192.168.192.168 Co-Authored-By: Claude Opus 5.5 <[email protected]>
480 lines
15 KiB
Python
480 lines
15 KiB
Python
import argparse
|
|
import io
|
|
|
|
import pytest
|
|
from conftest import FakePrinter, 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
|
|
|
|
|
|
def test_cmd_note_wraps_and_cuts():
|
|
p = FakePrinter()
|
|
rc = receipt.cmd_note(p, make_args(text="hello " * 20))
|
|
|
|
assert rc == 0
|
|
assert p.calls[0][0] == "textln"
|
|
assert all(len(line) <= receipt.TEXT_COLUMNS for line in p.calls[0][1].split("\n"))
|
|
assert p.calls[-1] == ("cut", None)
|
|
|
|
|
|
def test_cmd_note_large_size_wraps_narrower_and_resets():
|
|
p = FakePrinter()
|
|
rc = receipt.cmd_note(p, make_args(text="hello " * 20, size=2))
|
|
|
|
assert rc == 0
|
|
assert p.calls[0] == ("set", {"custom_size": True, "width": 2, "height": 2})
|
|
assert all(len(line) <= receipt.TEXT_COLUMNS // 2 for line in p.calls[1][1].split("\n"))
|
|
assert p.calls[2:] == [("set", {"normal_textsize": True}), ("cut", None)]
|
|
|
|
|
|
def test_cmd_note_timestamp_header():
|
|
p = FakePrinter()
|
|
rc = receipt.cmd_note(p, make_args(text="hi", timestamp=True))
|
|
|
|
assert rc == 0
|
|
kinds = [c[0] for c in p.calls]
|
|
assert kinds == ["textln", "textln", "textln", "cut"] # date, rule, note, cut
|
|
|
|
|
|
def test_cmd_note_rejects_empty():
|
|
p = FakePrinter()
|
|
rc = receipt.cmd_note(p, make_args(text=""))
|
|
|
|
assert rc == 1
|
|
assert p.calls == []
|
|
|
|
|
|
def test_cmd_qr_prints_content_and_caption():
|
|
p = FakePrinter()
|
|
rc = receipt.cmd_qr(p, make_args(content="https://example.com", message="scan me"))
|
|
|
|
assert rc == 0
|
|
assert ("qr", "https://example.com") in p.calls
|
|
assert ("textln", "scan me") in p.calls
|
|
|
|
|
|
def test_cmd_reprint_picks_most_recent(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)
|
|
|
|
p = FakePrinter()
|
|
rc = receipt.cmd_reprint(p, make_args())
|
|
|
|
assert rc == 0
|
|
assert ("textln", "new") in p.calls
|
|
|
|
|
|
def test_cmd_reprint_by_stem(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)
|
|
|
|
p = FakePrinter()
|
|
rc = receipt.cmd_reprint(p, make_args(name="12345"))
|
|
|
|
assert rc == 0
|
|
assert ("textln", "12345") in p.calls
|
|
|
|
|
|
def test_cmd_reprint_unknown_name(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)
|
|
|
|
p = FakePrinter()
|
|
assert receipt.cmd_reprint(p, make_args(name="nope")) == 1
|
|
assert p.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(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
|