Send each print as one job, queue web prints, and harden deploys
CI / test (3.10) (push) Failing after 56s
CI / test (3.12) (push) Failing after 42s
CI / test (3.13) (push) Failing after 47s

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]>
This commit is contained in:
2026-10-23 22:07:58 +01:00
co-authored by Claude Opus 5.5
parent 30d1b83817
commit 597bace442
10 changed files with 778 additions and 436 deletions
+31 -16
View File
@@ -2,30 +2,45 @@
import argparse
from escpos import printer
import receipt
class FakePrinter:
"""Records escpos calls instead of talking to hardware."""
"""Records the connection lifecycle and raw job payloads instead of talking to hardware."""
def __init__(self):
def __init__(self, fail_open=0, fail_raw=False):
self.calls = []
self.payloads = []
self.fail_open = fail_open # how many open() calls raise before one succeeds
self.fail_raw = fail_raw
def textln(self, text=""):
self.calls.append(("textln", text))
def open(self):
self.calls.append("open")
if self.fail_open:
self.fail_open -= 1
raise OSError("no route to printer")
def image(self, img, **kwargs):
self.calls.append(("image", img))
def qr(self, content, **kwargs):
self.calls.append(("qr", content))
def set(self, **kwargs):
self.calls.append(("set", kwargs))
def cut(self):
self.calls.append(("cut", None))
def _raw(self, data):
self.calls.append("raw")
if self.fail_raw:
raise OSError("connection reset")
self.payloads.append(data)
def close(self):
self.calls.append(("close", None))
self.calls.append("close")
def escpos_bytes(build):
"""What the given escpos calls render to, for asserting on payloads."""
p = printer.Dummy(profile=receipt.PRINTER_PROFILE)
build(p)
return p.output
INIT = escpos_bytes(lambda p: p.hw("INIT"))
CUT = escpos_bytes(lambda p: p.cut())
def make_args(**overrides):
+190 -158
View File
@@ -2,7 +2,7 @@ import argparse
import io
import pytest
from conftest import FakePrinter, make_args
from conftest import CUT, INIT, FakePrinter, escpos_bytes, make_args
from PIL import Image
import receipt
@@ -124,53 +124,121 @@ def test_download_skips_unprintable_formats(tmp_path, monkeypatch):
assert receipt.download_random_bant_image() is None
def test_cmd_note_wraps_and_cuts():
@pytest.fixture
def fake_printer(monkeypatch):
p = FakePrinter()
rc = receipt.cmd_note(p, make_args(text="hello " * 20))
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 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)
assert fake_printer.calls == ["open", "raw", "close"]
assert b"hello" in fake_printer.payloads[0]
def test_cmd_note_large_size_wraps_narrower_and_resets():
p = FakePrinter()
rc = receipt.cmd_note(p, make_args(text="hello " * 20, size=2))
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
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)]
# 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_cmd_note_timestamp_header():
p = FakePrinter()
rc = receipt.cmd_note(p, make_args(text="hi", timestamp=True))
def test_send_retries_a_failed_connect(monkeypatch):
p = FakePrinter(fail_open=1)
monkeypatch.setattr(receipt, "get_printer", lambda config: p)
assert rc == 0
kinds = [c[0] for c in p.calls]
assert kinds == ["textln", "textln", "textln", "cut"] # date, rule, note, cut
receipt.send(CONFIG, b"job")
assert p.calls == ["open", "open", "raw", "close"]
assert p.payloads == [b"job"]
def test_cmd_note_rejects_empty():
p = FakePrinter()
rc = receipt.cmd_note(p, make_args(text=""))
def test_send_gives_up_after_two_failed_connects(monkeypatch):
p = FakePrinter(fail_open=2)
monkeypatch.setattr(receipt, "get_printer", lambda config: p)
assert rc == 1
assert p.calls == []
with pytest.raises(receipt.PrinterUnavailable, match="can't reach"):
receipt.send(CONFIG, b"job")
assert "raw" not in 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"))
def test_send_never_replays_after_a_mid_job_drop(monkeypatch):
p = FakePrinter(fail_raw=True)
monkeypatch.setattr(receipt, "get_printer", lambda config: p)
assert rc == 0
assert ("qr", "https://example.com") in p.calls
assert ("textln", "scan me") in p.calls
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_cmd_reprint_picks_most_recent(tmp_path, monkeypatch):
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"
@@ -183,35 +251,33 @@ def test_cmd_reprint_picks_most_recent(tmp_path, monkeypatch):
os.utime(newer, (2000, 2000))
monkeypatch.setattr(receipt, "IMG_DIR", img_dir)
p = FakePrinter()
rc = receipt.cmd_reprint(p, make_args())
rc = receipt.cmd_reprint(CONFIG, make_args())
assert rc == 0
assert ("textln", "new") in p.calls
assert b"new\n" in fake_printer.payloads[0]
def test_cmd_reprint_by_stem(tmp_path, monkeypatch):
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)
p = FakePrinter()
rc = receipt.cmd_reprint(p, make_args(name="12345"))
rc = receipt.cmd_reprint(CONFIG, make_args(name="12345"))
assert rc == 0
assert ("textln", "12345") in p.calls
assert b"12345\n" in fake_printer.payloads[0]
def test_cmd_reprint_unknown_name(tmp_path, monkeypatch):
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)
p = FakePrinter()
assert receipt.cmd_reprint(p, make_args(name="nope")) == 1
assert p.calls == []
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():
@@ -269,27 +335,30 @@ def test_cmd_clean_nothing_to_do(tmp_path, monkeypatch):
assert receipt.cmd_clean(yes=True) == 0
def test_cmd_image_continues_past_failures(monkeypatch):
def test_cmd_image_continues_past_failures(fake_printer, 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 == []
assert receipt.cmd_image(CONFIG, make_args(count=2)) == 1 # nothing printed
assert fake_printer.calls == []
def test_cmd_image_prints_and_cuts(monkeypatch, tmp_path):
from PIL import Image
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)
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
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):
@@ -326,97 +395,58 @@ def test_wrap_unbreakable_long_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 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
def image(self, img, **kwargs):
self.calls.append("image")
if self.tag == 1:
raise OSError("dropped")
prepared = receipt.prepare_for_print(src)
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
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_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_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(tmp_path):
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")
p = FakePrinter()
rc = receipt.cmd_print(p, make_args(path=None, data=buf.getvalue(), message="cap"))
rc = receipt.cmd_print(CONFIG, 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
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()) == []
# ---- run_action (shared by the TUI and the web server) ----
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 == []
@pytest.fixture
def fake_printer(monkeypatch):
p = FakePrinter()
monkeypatch.setattr(receipt, "get_printer", lambda args: p)
return p
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):
rc, output = receipt.run_action("note", make_args(), text="hello", timestamp=False)
result = 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
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):
@@ -425,55 +455,57 @@ def test_run_action_reprint_uses_cache(fake_printer, tmp_path, monkeypatch):
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")
result = receipt.run_action("reprint", make_args(), name="12345")
assert rc == 0
assert ("textln", "12345") in fake_printer.calls
assert result.rc == 0
assert b"12345\n" in fake_printer.payloads[0]
def test_run_action_captures_output_and_errors(monkeypatch):
def boom(args):
raise OSError("no printer")
def test_run_action_classifies_printer_errors(monkeypatch):
monkeypatch.setattr(receipt, "get_printer", lambda config: FakePrinter(fail_open=2))
monkeypatch.setattr(receipt, "get_printer", boom)
result = receipt.run_action("note", make_args(), text="hi", timestamp=False)
rc, output = 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
assert rc == 1
assert "no printer" in 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 args: pytest.fail("should not connect"))
monkeypatch.setattr(receipt, "get_printer", lambda config: pytest.fail("should not connect"))
rc, output = receipt.run_action("list", make_args())
result = receipt.run_action("list", make_args())
assert rc == 0
assert "empty" in output
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):
def fail(args):
pytest.fail("should not run the connect script")
monkeypatch.setattr(
receipt, "setup_network", lambda config: 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(
result = 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
assert result.rc == 0
+81 -22
View File
@@ -1,7 +1,7 @@
import io
import pytest
from conftest import FakePrinter, make_args
from conftest import CUT, INIT, FakePrinter, make_args
from PIL import Image
import receipt
@@ -19,14 +19,25 @@ 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)
monkeypatch.setattr(receipt, "get_printer", lambda config: p)
return p
@pytest.fixture
def client():
base = make_args(usb=False, no_setup=True)
return TestClient(receipt_web.create_app(base, TOKEN))
config = receipt.PrinterConfig(no_setup=True)
return TestClient(receipt_web.create_app(config, TOKEN))
def finished_job(client, res):
"""Wait for the job a POST queued and return its final record."""
assert res.status_code == 202, res.text
job = res.json()["job"]
res = client.get(f"/api/jobs/{job['id']}?wait=5", headers=HEADERS)
assert res.status_code == 200
job = res.json()["job"]
assert job["state"] in receipt_web.FINISHED
return job
def png_bytes(size=(20, 10)):
@@ -70,17 +81,25 @@ def test_post_needs_page_header(client, fake_printer):
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)]
job = finished_job(client, res)
assert (job["state"], job["message"]) == ("done", "Printed.")
assert fake_printer.calls == ["open", "raw", "close"]
assert b"hello" in fake_printer.payloads[0]
def test_note_size(client, fake_printer):
res = client.post("/api/note", headers=HEADERS, json={"text": "hello", "size": 3})
assert res.status_code == 200
assert ("set", {"custom_size": True, "width": 3, "height": 3}) in fake_printer.calls
finished_job(client, res)
assert receipt.render_note("hello", size=3) == fake_printer.payloads[0]
def test_note_over_paper_budget_is_400(client, fake_printer):
res = client.post("/api/note", headers=HEADERS, json={"text": "x\n" * 1000, "size": 3})
assert res.status_code == 400
assert "too long" in res.json()["detail"]
assert fake_printer.calls == []
@pytest.mark.parametrize("size", [0, 4])
@@ -103,7 +122,50 @@ def test_status_reports_reachable(client, fake_printer):
res = client.get("/api/status", headers=HEADERS)
assert res.status_code == 200
assert res.json()["busy"] is False
assert "reachable" in res.json()["output"]
assert fake_printer.calls == ["open", "close"] # a real connect, not just a handle
def test_status_unreachable_is_503(client, monkeypatch):
monkeypatch.setattr(receipt, "get_printer", lambda config: FakePrinter(fail_open=2))
res = client.get("/api/status", headers=HEADERS)
assert res.status_code == 503
assert res.json()["ok"] is False
def test_status_does_not_wait_behind_a_print(client, fake_printer):
jobs = client.app.state.jobs
with jobs.printer_lock: # as if the worker were mid-print
res = client.get("/api/status", headers=HEADERS)
assert res.json()["busy"] is True
assert fake_printer.calls == []
def test_unknown_job_is_404(client):
assert client.get("/api/jobs/nope", headers=HEADERS).status_code == 404
def test_job_records_the_nginx_user(client, fake_printer):
res = client.post(
"/api/note", headers={**HEADERS, "X-Remote-User": "adam"}, json={"text": "hi"}
)
finished_job(client, res)
assert client.app.state.jobs._jobs[res.json()["job"]["id"]].user == "adam"
def test_full_queue_is_503(client, fake_printer, monkeypatch):
jobs = client.app.state.jobs
monkeypatch.setattr(jobs, "_pending", receipt_web.queue.Queue(1))
jobs._pending.put_nowait(("placeholder", b"")) # the worker is parked on the old queue
res = client.post("/api/note", headers=HEADERS, json={"text": "hi"})
assert res.status_code == 503
def test_image_prints_from_memory(client, fake_printer):
@@ -114,11 +176,10 @@ def test_image_prints_from_memory(client, fake_printer):
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
assert finished_job(client, res)["state"] == "done"
payload = fake_printer.payloads[0]
assert payload.startswith(INIT) and payload.endswith(CUT)
assert b"caption\n" in payload
def test_image_rejects_non_image(client, fake_printer):
@@ -141,16 +202,14 @@ def test_image_rejects_oversize(client, fake_printer, monkeypatch):
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)
def test_printer_error_fails_the_job(client, monkeypatch):
monkeypatch.setattr(receipt, "get_printer", lambda config: FakePrinter(fail_open=2))
res = client.post("/api/note", headers=HEADERS, json={"text": "hi"})
assert res.status_code == 502
assert res.json() == {"ok": False, "output": "Error: no printer"}
job = finished_job(client, res)
assert (job["state"], job["error"]) == ("failed", "unavailable")
assert "no route to printer" in job["message"]
def test_serve_refuses_without_token(monkeypatch, capsys):