Files
uberbringer/internal/pkg/escpos/interpret_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

232 lines
7.3 KiB
Go

package escpos_test
import (
"errors"
"fmt"
"image"
"reflect"
"strings"
"testing"
"uberbringer/internal/pkg/escpos"
)
var tmT88 = escpos.Profile{Name: "tm-t88", DotsPerLine: 512, FontAWidth: 12, FontBWidth: 9}
func interpret(t *testing.T, b *escpos.Builder, opaque ...escpos.Span) []escpos.PreviewLine {
t.Helper()
lines, err := escpos.Interpret(b.Bytes(), escpos.CodePage437, tmT88, opaque)
if err != nil {
t.Fatalf("Interpret: %v", err)
}
return lines
}
func texts(lines []escpos.PreviewLine) []string {
out := make([]string, len(lines))
for i, l := range lines {
out[i] = l.Text
}
return out
}
func mustOK(t *testing.T, err error) {
t.Helper()
if err != nil {
t.Fatal(err)
}
}
// TestInterpretBuilderOutput runs every command the Builder emits through
// the interpreter.
func TestInterpretBuilderOutput(t *testing.T) {
var b escpos.Builder
b.Initialize()
b.SelectCodePage(escpos.CodePage437)
b.Text(escpos.CodePage437.Encode("Plain ┌─┐ £"))
b.LineFeed()
b.Justify(escpos.JustifyCenter)
b.Bold(true)
b.Text([]byte("Hi"))
b.Bold(false)
b.LineFeed()
b.Justify(escpos.JustifyRight)
b.Text([]byte("R"))
b.LineFeed()
b.Justify(escpos.JustifyLeft)
b.Font(escpos.FontB)
mustOK(t, b.Size(2, 3))
b.Underline(escpos.UnderlineThick)
b.Reverse(true)
b.Text([]byte("big"))
b.Reverse(false)
b.Underline(escpos.UnderlineNone)
mustOK(t, b.Size(1, 1))
b.Font(escpos.FontA)
b.Text([]byte(" tail"))
b.LineFeed()
b.LineSpacing(20)
b.Text([]byte("spaced"))
b.Feed(3)
b.DefaultLineSpacing()
mustOK(t, b.QRCode([]byte("https://example.com/x"), 4, escpos.QRCorrectionH))
b.BarcodeHeight(60)
mustOK(t, b.BarcodeWidth(2))
b.BarcodeHRI(escpos.HRIBelow)
mustOK(t, b.Barcode(escpos.CODE128, "A{B-1"))
mustOK(t, b.Barcode(escpos.EAN13, "4006381333931"))
mustOK(t, b.RasterImage(image.NewGray(image.Rect(0, 0, 100, 300))))
b.Cut(escpos.CutFull, 3)
b.Text([]byte("after"))
b.Cut(escpos.CutPartial, 0)
got := interpret(t, &b)
want := []escpos.PreviewLine{
{Kind: escpos.LineText, Text: "Plain ┌─┐ £"},
{Kind: escpos.LineText, Text: strings.Repeat(" ", 20) + "Hi", Runs: []escpos.Run{{From: 20, To: 22, Bold: true, Font: escpos.FontA, W: 1, H: 1}}},
{Kind: escpos.LineText, Text: strings.Repeat(" ", 41) + "R"},
{Kind: escpos.LineText, Text: "big tail", Runs: []escpos.Run{{From: 0, To: 3, Underline: escpos.UnderlineThick, Invert: true, Font: escpos.FontB, W: 2, H: 3}}},
{Kind: escpos.LineText, Text: "spaced"},
{Kind: escpos.LineText},
{Kind: escpos.LineText},
{Kind: escpos.LineQR, Text: "[qr: https://example.com/x]", Data: "https://example.com/x"},
{Kind: escpos.LineBarcode, Text: "[barcode code128: A{B-1]", Data: "A{B-1"},
{Kind: escpos.LineBarcode, Text: "[barcode ean13: 4006381333931]", Data: "4006381333931"},
{Kind: escpos.LineImage, Text: "[image 104x300 dots]", Data: "104x300"},
{Kind: escpos.LineCut, Text: " - - - - - - - - full cut - - - - - - - -", Data: "full"},
{Kind: escpos.LineText, Text: "after"},
{Kind: escpos.LineCut, Text: " - - - - - - - partial cut - - - - - - - -", Data: "partial"},
}
if !reflect.DeepEqual(got, want) {
t.Errorf("lines:\n%s\nwant:\n%s", dump(got), dump(want))
}
}
func dump(lines []escpos.PreviewLine) string {
var b strings.Builder
for _, l := range lines {
fmt.Fprintf(&b, "%s %q %q %+v\n", l.Kind, l.Text, l.Data, l.Runs)
}
return b.String()
}
func TestInterpretPrinterWrapsLongLines(t *testing.T) {
var b escpos.Builder
b.Text([]byte(strings.Repeat("y", 60)))
b.LineFeed()
mustOK(t, b.Size(2, 2))
b.Text([]byte(strings.Repeat("z", 25)))
got := texts(interpret(t, &b))
want := []string{strings.Repeat("y", 42), strings.Repeat("y", 18), strings.Repeat("z", 21), strings.Repeat("z", 4)}
if !reflect.DeepEqual(got, want) {
t.Errorf("lines = %q, want %q", got, want)
}
}
func TestInterpretJustifyTakesEffectAtLineStart(t *testing.T) {
var b escpos.Builder
b.Text([]byte("ab"))
b.Justify(escpos.JustifyRight) // mid-line: ignored by the printer
b.Text([]byte("cd"))
b.LineFeed()
b.Text([]byte("ef"))
b.LineFeed()
got := texts(interpret(t, &b))
if want := []string{"abcd", "ef"}; !reflect.DeepEqual(got, want) {
t.Errorf("lines = %q, want %q", got, want)
}
}
func TestInterpretTabs(t *testing.T) {
var b escpos.Builder
b.Text([]byte("ab\tc"))
got := texts(interpret(t, &b))
if want := []string{"ab c"}; !reflect.DeepEqual(got, want) {
t.Errorf("lines = %q, want %q", got, want)
}
}
func TestInterpretOpaqueSpans(t *testing.T) {
var b escpos.Builder
b.Text([]byte("before "))
from := b.Len()
b.Raw([]byte{0x1B, 0x61, 0x01, 0x07, 0x1C, 0xFF})
to := b.Len()
b.Text([]byte("after"))
b.LineFeed()
end := b.Len()
got := interpret(t, &b, escpos.Span{From: from, To: to}, escpos.Span{From: end, To: end})
want := []escpos.PreviewLine{
{Kind: escpos.LineText, Text: "before "},
{Kind: escpos.LineRaw, Text: "[raw 6 bytes]", Data: "6"},
{Kind: escpos.LineText, Text: "after"},
{Kind: escpos.LineRaw, Text: "[raw 0 bytes]", Data: "0"},
}
if !reflect.DeepEqual(got, want) {
t.Errorf("lines:\n%s\nwant:\n%s", dump(got), dump(want))
}
}
func TestInterpretFunctionAForms(t *testing.T) {
var b escpos.Builder
b.Raw([]byte{0x1D, 'k', 4})
b.Raw([]byte("AB-1"))
b.Raw([]byte{0, 0x1D, 'V', 1})
got := interpret(t, &b)
want := []escpos.PreviewLine{
{Kind: escpos.LineBarcode, Text: "[barcode code39: AB-1]", Data: "AB-1"},
{Kind: escpos.LineCut, Text: " - - - - - - - partial cut - - - - - - - -", Data: "partial"},
}
if !reflect.DeepEqual(got, want) {
t.Errorf("lines:\n%s\nwant:\n%s", dump(got), dump(want))
}
}
func TestInterpretRejects(t *testing.T) {
tests := []struct {
name string
stream []byte
opaque []escpos.Span
}{
{"unknown ESC command", []byte{0x1B, 'Z', 1}, nil},
{"unknown GS command", []byte{0x1D, 'Z', 1}, nil},
{"unknown GS ( function", []byte{0x1D, '(', 'L', 2, 0, '0', '1'}, nil},
{"PDF417, not QR", []byte{0x1D, '(', 'k', 3, 0, '0', 'A', 0}, nil},
{"control byte", []byte("a\x07b"), nil},
{"DEL", []byte("a\x7fb"), nil},
{"DLE EOT status request", []byte{0x10, 0x04, 1}, nil},
{"truncated ESC", []byte{0x1B}, nil},
{"truncated ESC a", []byte{0x1B, 'a'}, nil},
{"truncated QR store", []byte{0x1D, '(', 'k', 10, 0, '1', 'P', '0', 'x'}, nil},
{"truncated raster", []byte{0x1D, 'v', '0', 0, 2, 0, 2, 0, 0xFF}, nil},
{"unterminated function A barcode", []byte{0x1D, 'k', 4, 'A'}, nil},
{"unsupported code page", []byte{0x1B, 't', 99}, nil},
{"span inside a command", []byte{0x1B, 'a', 1, 'x'}, []escpos.Span{{From: 1, To: 2}}},
{"span past the end", []byte("abc"), []escpos.Span{{From: 2, To: 9}}},
{"spans out of order", []byte("abcd"), []escpos.Span{{From: 2, To: 3}, {From: 0, To: 1}}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := escpos.Interpret(tt.stream, escpos.CodePage437, tmT88, tt.opaque)
if !errors.Is(err, escpos.ErrInvalidArgument) {
t.Errorf("err = %v, want ErrInvalidArgument", err)
}
})
}
}
func TestInterpretCodePageSwitch(t *testing.T) {
var b escpos.Builder
b.SelectCodePage(escpos.CodePage1252)
b.Text(escpos.CodePage1252.Encode("“€”"))
b.LineFeed()
b.Text([]byte("cleared"))
b.Initialize() // clears the print buffer and selects the default table
b.Text([]byte{0xC4})
got := texts(interpret(t, &b))
if want := []string{"“€”", "─"}; !reflect.DeepEqual(got, want) {
t.Errorf("lines = %q, want %q", got, want)
}
}