- receipt_tui.py: Textual terminal UI (tui subcommand), optional [tui] extra - tests/: pytest suite for CLI and TUI using fakes; no hardware needed - pyproject.toml: packaging with dev/tui extras, ruff config - GitHub Actions CI running ruff and pytest - Rename connect_recipt.sh -> connect_receipt.sh - CLAUDE.md project instructions; README updates Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
@@ -0,0 +1,249 @@
|
||||
import argparse
|
||||
|
||||
import pytest
|
||||
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
|
||||
|
||||
|
||||
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 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)
|
||||
|
||||
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):
|
||||
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):
|
||||
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_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 # stdin mode
|
||||
|
||||
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"):
|
||||
assert parser.parse_args([cmd]).command == cmd
|
||||
@@ -0,0 +1,104 @@
|
||||
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 make_base_args(**overrides):
|
||||
defaults = {
|
||||
"usb": True, # avoids the network setup script in tests
|
||||
"ip": receipt.DEFAULT_PRINTER_IP,
|
||||
"port": receipt.DEFAULT_PRINTER_PORT,
|
||||
"command": "tui",
|
||||
}
|
||||
defaults.update(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[-1] == ("cut", None)
|
||||
|
||||
|
||||
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"
|
||||
Reference in New Issue
Block a user