Files
uberbringer/internal/pkg/receipt/fuzz_test.go
T
57_WolveandClaude Opus 5.5 4562f0cebb
Security / Vulnerability check (push) Successful in 50s
Test / Lint and test (push) Successful in 1m59s
Add box, rule and kv blocks, text folding and receipt preview
Phase 1 of docs/plans/formatters.md: single and double CP437 boxes from
one /print element, and a way to see a receipt without using paper.

- receipt: box, rule and kv elements, laid out when the job renders from
  the printer profile, size and font (never fixed widths). Boxes take a
  title (inline or capped), a footer, padding, fit and columns, and a
  body of text or children (text, feed, kv, and rules as dividers joined
  to the borders). Glyphs a code page lacks fall back per set: double-h
  and double-v to double, then single, then ascii; a missing junction
  switches line weight first.
- Validation names nested elements (elements[0].children[3] (qr)),
  checks fields per block type, allows one level of children and counts
  them toward the 500-element limit. Block fields on the older types are
  problems, as they were unknown fields before.
- Text is composed to NFC and characters the code page lacks fold to
  look-alikes (curly quotes, dashes, ellipsis, arrows, check marks, euro,
  trademark), as the owner approved on 2026-11-29. An emoji sequence
  prints as one '?'. Encodable text is untouched.
- escpos: CodePage.CanEncode and Decode, and Interpret, which reads a
  command stream back as the printer would print it. It takes the
  profile so that it can follow the printer's own wrapping and
  alignment; raw spans stay opaque.
- POST /api/v1/preview and `uberbringer preview` show the lines a job
  prints, as text or JSON with styles, without fetching images.
- Config: [format] max_lines (default 2000), refused with 422
  too_many_lines on preview; printer.box_line_spacing (default 0).

Byte compatibility: testdata/compat fixtures were rendered by 9b91109
before the renderer changed, and still match it and the new renderer.
examples/blocks.json was printed on the TM-T88IV; the owner judged the
border gaps at the default spacing fine (2026-11-30), so
box_line_spacing stays 0, and TestPaperReceipts pins its bytes.

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

171 lines
6.1 KiB
Go

package receipt_test
import (
"bytes"
"context"
"strings"
"testing"
"uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/receipt"
)
// FuzzBlocks lays out random boxes, rules and kv blocks 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.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 or kv 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 % 3 {
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})
}
case 1:
el.Type = "rule"
el.Style = ruleStyles[int(style)%len(ruleStyles)]
el.Text = text
el.Align = aligns[int(padding)%3]
default:
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}}
}
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)
}
}
}