Files
uberbringer/internal/pkg/receipt/fuzz_test.go
T
57_WolveandClaude Opus 5.5 3e9779f71a
Security / Vulnerability check (push) Successful in 41s
Test / Lint and test (push) Successful in 1m50s
Add the list block and the module layer with the note module
The list block prints items with a dot, dash, number or checkbox bullet,
wrapping a long item with a hanging indent; a checkbox list ticks its
done items as [√], or [x] on code pages without √. It stands alone or
inside a box, and its items, bullet and done fields carry their enums
and limits as jsonschema tags.

internal/pkg/modules holds modules that build ordinary jobs from their
own payloads: a registry by name, an Env with the clock, time zone and
time layout, strict payload decoding that reports every problem, ErrSkip
and PayloadError. The note module prints a boxed note with an optional
checklist and a time stamp in the footer.

Three routes join the route table: POST /api/v1/print/{module} and
POST /api/v1/preview/{module}, which take ?copies and a reserved
?printer, and GET /api/v1/modules. Print and the module route share one
submit path, and preview shares one too. New error codes:
invalid_payload, invalid_query, unknown_printer, module_not_found and
module_failed; a module that builds an invalid receipt is logged and
reported to Sentry once. [format] gains timezone and time_layout, the
binary embeds the time zone database, and uberbringer preview takes
--module.

The note receipt passed on the TM-T88IV, and its bytes are pinned in
TestPaperReceipts. docs/api.md describes the list block, the module
routes and the note payload; docs/swagger.json is regenerated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:55:50 -06:00

197 lines
7.2 KiB
Go

package receipt_test
import (
"bytes"
"context"
"strings"
"testing"
"uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/receipt"
)
// FuzzBlocks lays out random boxes, rules, kv blocks and lists on random
// printers and code pages, and checks that every line is exactly the
// block's width, no wider than the line, with the borders in the first and
// last columns, and that no control byte reaches the printer inside the
// text.
func FuzzBlocks(f *testing.F) {
f.Add(uint8(0), uint8(0), uint8(0), uint8(1), uint8(0), uint8(1), false, uint8(0), "Title", "Footer", "Some text that wraps", "key", "value")
f.Add(uint8(0x3C), uint8(1), uint8(9), uint8(2), uint8(1), uint8(3), true, uint8(12), "“A long title” — with folds…", "", "line\nline\ttab 🎉👨\u200D👩\u200D👧", "k", "")
f.Add(uint8(1), uint8(2), uint8(6), uint8(0), uint8(0), uint8(0), false, uint8(200), "", "", "Label", "", "")
f.Add(uint8(2), uint8(3), uint8(4), uint8(1), uint8(1), uint8(2), false, uint8(7), "", "", "", "A key that is long", "a value that wraps over several lines")
f.Add(uint8(0xF8), uint8(4), uint8(3), uint8(2), uint8(0), uint8(0), true, uint8(3), "\x1b@\x00", "\x07", "\x1bd\x05 text \x1dV", "\x0a", "\x09")
f.Add(uint8(3), uint8(1), uint8(3), uint8(0), uint8(1), uint8(2), true, uint8(5), "A done item", "", "An item that wraps\nwith a hanging indent", "k", "v")
f.Add(uint8(0x80), uint8(0x83), uint8(2), uint8(0), uint8(0), uint8(1), true, uint8(0), "Title", "", "text", "", "")
f.Fuzz(func(t *testing.T, kind, printerSel, style, size, font, padding uint8, fit bool, columns uint8,
title, footer, text, key, value string) {
el := fuzzBlock(kind, style, size, font, padding, fit, columns, title, footer, text, key, value)
job := receipt.Job{Elements: []receipt.Element{el}}
if job.Validate() != nil {
return
}
models := []string{"tm-t88", "tm-t20", "generic-58mm"}
codePages := []escpos.CodePage{escpos.CodePage437, escpos.CodePage850, escpos.CodePage858, escpos.CodePage1252}
profile, err := escpos.LookupProfile(models[int(printerSel)%len(models)])
if err != nil {
t.Fatal(err)
}
cp := codePages[int(printerSel/3)%len(codePages)]
override := 0
if printerSel&0x80 != 0 {
override = 30
}
r := receipt.NewRenderer(receipt.Options{
Profile: profile, CodePage: cp, Columns: override,
MaxPixels: 1000, MaxHeight: 1000, MaxLines: 100_000,
}, &fakeFetcher{})
out, err := r.Render(context.Background(), job)
if err != nil {
t.Fatalf("Render: %v", err)
}
p, err := r.Preview(context.Background(), job)
if err != nil {
t.Fatalf("Preview: %v", err)
}
var lines []string
for _, l := range p.Lines {
if l.Kind == escpos.LineText {
lines = append(lines, l.Text)
}
}
if len(lines) == 0 {
t.Fatal("a block printed no lines")
}
lineDots := profile.DotsPerLine
if override > 0 {
lineDots = override * profile.FontAWidth
}
blockSize := max(el.Size, 1)
cols := lineDots / (profile.GlyphWidth(fontOf(el.Font)) * blockSize)
width := len([]rune(lines[0]))
for i, line := range lines {
n := len([]rune(line))
if n != width || n > cols {
t.Fatalf("line %d %q is %d wide; want %d like line 0, and at most %d", i, line, n, width, cols)
}
}
if el.Type == "box" {
checkBoxBorders(t, lines)
}
// No tab may reach the printer, and every line feed ends a line.
if bytes.IndexByte(out, '\t') >= 0 {
t.Errorf("stream has a tab: % X", out)
}
if n := bytes.Count(out, []byte{'\n'}); n != len(lines) {
t.Errorf("stream has %d line feeds for %d lines", n, len(lines))
}
})
}
func fontOf(name string) escpos.Font {
if strings.EqualFold(name, "b") {
return escpos.FontB
}
return escpos.FontA
}
// fuzzBlock builds a box, rule, kv or list element from the fuzzer's values.
// The low bits of kind pick the type; for a box, the others pick its
// children.
func fuzzBlock(kind, style, size, font, padding uint8, fit bool, columns uint8, title, footer, text, key, value string) receipt.Element {
boxStyles := []string{"single", "double", "double-h", "double-v", "ascii"}
ruleStyles := []string{"single", "double", "light", "medium", "dark", "solid", "dashed", "dotted", "ascii"}
leaders := []string{".", "·", " ", "_", "-", "─"}
aligns := []string{"left", "center", "right"}
el := receipt.Element{Size: 1 + int(size)%3, Columns: int(columns)}
if font%2 == 1 {
el.Font = "b"
}
switch kind % 4 {
case 0:
el.Type = "box"
el.Style = boxStyles[int(style)%len(boxStyles)]
el.Title, el.Footer, el.Fit = title, footer, fit
el.Padding = intPtr(int(padding) % 4)
el.Align = aligns[int(style)%len(aligns)]
if style&0x10 != 0 {
el.TitleStyle = "capped"
}
children := kind >> 2
if children == 0 {
el.Text = text
if el.Text == "" {
el.Text = "x"
}
break
}
if children&1 != 0 {
el.Children = append(el.Children, receipt.Element{Type: "text", Text: text, Align: aligns[int(padding)%3], Wrap: boolPtr(children&0x10 == 0)})
}
if children&2 != 0 {
el.Children = append(el.Children, receipt.Element{Type: "rule", Text: key, Style: []string{"single", "double"}[int(style)%2], Align: aligns[int(size)%3]})
}
if children&4 != 0 {
el.Children = append(el.Children, receipt.Element{Type: "kv", Leader: leaders[int(font)%len(leaders)], Pairs: []receipt.Pair{{Key: key + "k", Value: value}}})
}
if children&8 != 0 {
el.Children = append(el.Children, receipt.Element{Type: "feed", Lines: 1 + int(padding)%3})
}
if children&0x20 != 0 {
list := fuzzList(style, fit, title, text, value)
list.Size, list.Columns, list.Font = 0, 0, ""
el.Children = append(el.Children, list)
}
case 1:
el.Type = "rule"
el.Style = ruleStyles[int(style)%len(ruleStyles)]
el.Text = text
el.Align = aligns[int(padding)%3]
case 2:
el.Type = "kv"
el.Leader = leaders[int(style)%len(leaders)]
el.Pairs = []receipt.Pair{{Key: key + "k", Value: value}, {Key: title + "t", Value: text, Bold: fit}}
default:
list := fuzzList(style, fit, title, text, value)
el.Type, el.Bullet, el.Items, el.Done = list.Type, list.Bullet, list.Items, list.Done
}
return el
}
// fuzzList builds a list whose items are the fuzzer's strings. style picks
// the bullet, and fit marks the first item done on a checklist.
func fuzzList(style uint8, fit bool, items ...string) receipt.Element {
bullets := []string{"dot", "dash", "number", "checkbox"}
el := receipt.Element{Type: "list", Bullet: bullets[int(style)%len(bullets)]}
for _, item := range items {
el.Items = append(el.Items, item+"i")
}
if fit && el.Bullet == "checkbox" {
el.Done = []int{0}
}
return el
}
// checkBoxBorders checks that each box line, after its centring margin,
// starts and ends with a border glyph.
func checkBoxBorders(t *testing.T, lines []string) {
t.Helper()
const (
left = "┌╔╒╓+│║|└╚╘╙├╞╟╠"
right = "┐╗╕╖+│║|┘╝╛╜┤╡╢╣"
)
margin := len(lines[0]) - len(strings.TrimLeft(lines[0], " "))
for i, line := range lines {
runes := []rune(line[margin:])
if line[:margin] != strings.Repeat(" ", margin) || len(runes) < 2 {
t.Fatalf("line %d %q does not share the box margin %d", i, line, margin)
}
if !strings.ContainsRune(left, runes[0]) || !strings.ContainsRune(right, runes[len(runes)-1]) {
t.Fatalf("line %d %q does not start and end with a border", i, line)
}
}
}