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 "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[-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"