Files
uberbringer/internal/pkg/escpos/escpos_test.go
T
57_WolveandClaude Opus 5.5 afcf96431f
CI / Lint, test and scan (push) Successful in 1m42s
Fix /healthz false alarms; default to 512-dot TM-T88 profile
Hardware testing on the real printer (an Epson TM-T88IV, not a TM-T20II)
turned up two problems, and an adversarial review found three more.

Printer status
- Treat DLE EOT 2 bits (cover open, paper-end stop) as offline causes:
  Status.Normalized clears them while DLE EOT 1 reports the printer
  online. The TM-T88IV reported online + cover open while printing and
  cutting a long receipt, which made /healthz return 503.
- PaperOut now comes only from the DLE EOT 4 roll-paper sensor; the
  paper-end stop is reported separately as PaperEndStop.
- /healthz re-reads a printer that looks not ready after 750 ms and only
  reports a problem that is still there.
- A status read cut short by the caller's deadline now returns
  context.DeadlineExceeded (503 "timeout") instead of
  ErrStatusUnsupported, which /healthz reported as 200 "unknown" and
  could hide an offline printer.

Printer profiles
- Default model is now tm-t88 (512 dots, 42/56 columns). A profile wider
  than the printer makes it break words mid-line; a narrower one only
  shortens lines.
- Add tm-m50 (TM-m50/II) and document TM-T88IV-VII, 58 mm paper on
  180-dpi printers, and that the TM-T88VII does not report paper near-end
  through real-time status.
- README example banner shortened to 42 characters to fit the default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 21:51:12 -06:00

474 lines
16 KiB
Go

package escpos_test
import (
"bytes"
"errors"
"image"
"image/color"
"strings"
"testing"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
)
// Byte-exact checks against the Epson ESC/POS command reference.
func TestCommands(t *testing.T) {
tests := []struct {
name string
build func(b *escpos.Builder)
want []byte
}{
{"initialize", func(b *escpos.Builder) { b.Initialize() }, []byte{0x1B, 0x40}},
{"line feed", func(b *escpos.Builder) { b.LineFeed() }, []byte{0x0A}},
{"feed 3", func(b *escpos.Builder) { b.Feed(3) }, []byte{0x1B, 0x64, 3}},
{"line spacing", func(b *escpos.Builder) { b.LineSpacing(30) }, []byte{0x1B, 0x33, 30}},
{"default line spacing", func(b *escpos.Builder) { b.DefaultLineSpacing() }, []byte{0x1B, 0x32}},
{"bold on", func(b *escpos.Builder) { b.Bold(true) }, []byte{0x1B, 0x45, 1}},
{"bold off", func(b *escpos.Builder) { b.Bold(false) }, []byte{0x1B, 0x45, 0}},
{"underline thick", func(b *escpos.Builder) { b.Underline(escpos.UnderlineThick) }, []byte{0x1B, 0x2D, 2}},
{"reverse", func(b *escpos.Builder) { b.Reverse(true) }, []byte{0x1D, 0x42, 1}},
{"justify center", func(b *escpos.Builder) { b.Justify(escpos.JustifyCenter) }, []byte{0x1B, 0x61, 1}},
{"font b", func(b *escpos.Builder) { b.Font(escpos.FontB) }, []byte{0x1B, 0x4D, 1}},
{"code page 437", func(b *escpos.Builder) { b.SelectCodePage(escpos.CodePage437) }, []byte{0x1B, 0x74, 0}},
{"code page 850", func(b *escpos.Builder) { b.SelectCodePage(escpos.CodePage850) }, []byte{0x1B, 0x74, 2}},
{"code page 858", func(b *escpos.Builder) { b.SelectCodePage(escpos.CodePage858) }, []byte{0x1B, 0x74, 19}},
{"code page 1252", func(b *escpos.Builder) { b.SelectCodePage(escpos.CodePage1252) }, []byte{0x1B, 0x74, 16}},
{"partial cut", func(b *escpos.Builder) { b.Cut(escpos.CutPartial, 0) }, []byte{0x1D, 0x56, 66, 0}},
{"full cut", func(b *escpos.Builder) { b.Cut(escpos.CutFull, 5) }, []byte{0x1D, 0x56, 65, 5}},
{"barcode height", func(b *escpos.Builder) { b.BarcodeHeight(80) }, []byte{0x1D, 0x68, 80}},
{"barcode hri", func(b *escpos.Builder) { b.BarcodeHRI(escpos.HRIBelow) }, []byte{0x1D, 0x48, 2}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var b escpos.Builder
tt.build(&b)
if !bytes.Equal(b.Bytes(), tt.want) {
t.Errorf("got % X, want % X", b.Bytes(), tt.want)
}
})
}
}
func TestSize(t *testing.T) {
tests := []struct {
width, height int
want byte
wantErr bool
}{
{1, 1, 0x00, false},
{2, 2, 0x11, false},
{8, 8, 0x77, false},
{3, 1, 0x20, false},
{1, 4, 0x03, false},
{0, 1, 0, true},
{9, 1, 0, true},
{1, 9, 0, true},
}
for _, tt := range tests {
var b escpos.Builder
err := b.Size(tt.width, tt.height)
if tt.wantErr {
if !errors.Is(err, escpos.ErrInvalidArgument) || b.Len() != 0 {
t.Errorf("Size(%d,%d): err=%v len=%d, want ErrInvalidArgument and nothing written",
tt.width, tt.height, err, b.Len())
}
continue
}
want := []byte{0x1D, 0x21, tt.want}
if err != nil || !bytes.Equal(b.Bytes(), want) {
t.Errorf("Size(%d,%d) = % X, %v; want % X", tt.width, tt.height, b.Bytes(), err, want)
}
}
}
func TestBarcodeWidthUsesWidthCommand(t *testing.T) {
var b escpos.Builder
if err := b.BarcodeWidth(3); err != nil {
t.Fatal(err)
}
if want := []byte{0x1D, 0x77, 3}; !bytes.Equal(b.Bytes(), want) {
t.Errorf("got % X, want % X", b.Bytes(), want)
}
if err := b.BarcodeWidth(7); !errors.Is(err, escpos.ErrInvalidArgument) {
t.Errorf("BarcodeWidth(7) err = %v, want ErrInvalidArgument", err)
}
}
func TestBarcode(t *testing.T) {
tests := []struct {
name string
sym escpos.Symbology
data string
want []byte
wantErr bool
}{
{name: "ean13 with check digit", sym: escpos.EAN13, data: "4006381333931",
want: append([]byte{0x1D, 0x6B, 67, 13}, "4006381333931"...)},
{name: "ean13 without check digit", sym: escpos.EAN13, data: "400638133393",
want: append([]byte{0x1D, 0x6B, 67, 12}, "400638133393"...)},
{name: "ean13 wrong check digit", sym: escpos.EAN13, data: "4006381333932", wantErr: true},
{name: "ean13 letters", sym: escpos.EAN13, data: "40063813339A", wantErr: true},
{name: "ean8", sym: escpos.EAN8, data: "96385074",
want: append([]byte{0x1D, 0x6B, 68, 8}, "96385074"...)},
{name: "ean8 wrong length", sym: escpos.EAN8, data: "123", wantErr: true},
{name: "upca", sym: escpos.UPCA, data: "036000291452",
want: append([]byte{0x1D, 0x6B, 65, 12}, "036000291452"...)},
{name: "upce short", sym: escpos.UPCE, data: "123456",
want: append([]byte{0x1D, 0x6B, 66, 6}, "123456"...)},
{name: "upce long must start with 0", sym: escpos.UPCE, data: "12345678901", wantErr: true},
{name: "code39", sym: escpos.CODE39, data: "ABC-123",
want: append([]byte{0x1D, 0x6B, 69, 7}, "ABC-123"...)},
{name: "code39 lowercase", sym: escpos.CODE39, data: "abc", wantErr: true},
{name: "code128 code set B", sym: escpos.CODE128, data: "Hello-1",
want: append([]byte{0x1D, 0x6B, 73, 9}, "{BHello-1"...)},
{name: "code128 escapes brace", sym: escpos.CODE128, data: "a{b",
want: append([]byte{0x1D, 0x6B, 73, 6}, "{Ba{{b"...)},
{name: "code128 non-ascii", sym: escpos.CODE128, data: "Grüße", wantErr: true},
{name: "code128 too long", sym: escpos.CODE128, data: strings.Repeat("x", 254), wantErr: true},
{name: "empty", sym: escpos.CODE128, data: "", wantErr: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var b escpos.Builder
err := b.Barcode(tt.sym, tt.data)
if tt.wantErr {
if !errors.Is(err, escpos.ErrInvalidArgument) || b.Len() != 0 {
t.Fatalf("err=%v len=%d, want ErrInvalidArgument and nothing written", err, b.Len())
}
return
}
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(b.Bytes(), tt.want) {
t.Errorf("got % X, want % X", b.Bytes(), tt.want)
}
})
}
}
func TestQRCode(t *testing.T) {
var b escpos.Builder
if err := b.QRCode([]byte("hi"), 6, escpos.QRCorrectionM); err != nil {
t.Fatal(err)
}
want := []byte{
0x1D, 0x28, 0x6B, 4, 0, 0x31, 0x41, 0x32, 0, // model 2
0x1D, 0x28, 0x6B, 3, 0, 0x31, 0x43, 6, // module size
0x1D, 0x28, 0x6B, 3, 0, 0x31, 0x45, 49, // correction M
0x1D, 0x28, 0x6B, 5, 0, 0x31, 0x50, 0x30, 'h', 'i', // store
0x1D, 0x28, 0x6B, 3, 0, 0x31, 0x51, 0x30, // print
}
if !bytes.Equal(b.Bytes(), want) {
t.Errorf("got % X\nwant % X", b.Bytes(), want)
}
}
func TestQRCodeStoreLengthUsesHighByte(t *testing.T) {
var b escpos.Builder
data := bytes.Repeat([]byte{'x'}, 300)
if err := b.QRCode(data, 4, escpos.QRCorrectionL); err != nil {
t.Fatal(err)
}
store := []byte{0x1D, 0x28, 0x6B, byte(303 & 0xFF), byte(303 >> 8), 0x31, 0x50, 0x30}
if !bytes.Contains(b.Bytes(), store) {
t.Errorf("store header % X not found", store)
}
}
func TestQRCodeRejects(t *testing.T) {
tests := map[string]func(b *escpos.Builder) error{
"empty": func(b *escpos.Builder) error { return b.QRCode(nil, 4, escpos.QRCorrectionM) },
"too long": func(b *escpos.Builder) error {
return b.QRCode(make([]byte, escpos.MaxQRData+1), 4, escpos.QRCorrectionM)
},
"module too big": func(b *escpos.Builder) error { return b.QRCode([]byte("x"), 17, escpos.QRCorrectionM) },
"bad correction": func(b *escpos.Builder) error { return b.QRCode([]byte("x"), 4, 47) },
"module too small": func(b *escpos.Builder) error { return b.QRCode([]byte("x"), 0, escpos.QRCorrectionM) },
}
for name, call := range tests {
t.Run(name, func(t *testing.T) {
var b escpos.Builder
if err := call(&b); !errors.Is(err, escpos.ErrInvalidArgument) || b.Len() != 0 {
t.Errorf("err=%v len=%d, want ErrInvalidArgument and nothing written", err, b.Len())
}
})
}
}
func TestEncodeCodePage437(t *testing.T) {
tests := []struct {
name string
in string
want []byte
}{
{"ascii", "Hello, World!", []byte("Hello, World!")},
{"box drawing", "┌─┐│└┘", []byte{0xDA, 0xC4, 0xBF, 0xB3, 0xC0, 0xD9}},
{"shading", "░▒▓█", []byte{0xB0, 0xB1, 0xB2, 0xDB}},
{"double box", "╔═╗", []byte{0xC9, 0xCD, 0xBB}},
{"umlauts", "Über ä ö", []byte{0x9A, 'b', 'e', 'r', ' ', 0x84, ' ', 0x94}},
{"symbols", "£°±", []byte{0x9C, 0xF8, 0xF1}},
{"unmappable emoji", "hi 🎉", []byte("hi ?")},
{"keeps newline and tab", "a\nb\tc", []byte("a\nb\tc")},
// ESC is dropped, so the '@' that followed it is harmless text.
{"drops control characters", "a\x1b@b\x00c\r", []byte("a@bc")},
{"smiley maps below 0x20 so becomes ?", "☺", []byte("?")},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := escpos.CodePage437.Encode(tt.in)
if !bytes.Equal(got, tt.want) {
t.Errorf("Encode(%q) = % X, want % X", tt.in, got, tt.want)
}
})
}
}
func TestEncodeOtherCodePages(t *testing.T) {
if got := escpos.CodePage858.Encode("€"); !bytes.Equal(got, []byte{0xD5}) {
t.Errorf("cp858 € = % X, want D5", got)
}
if got := escpos.CodePage1252.Encode("ێ"); !bytes.Equal(got, []byte{0x80, 0xE9}) {
t.Errorf("cp1252 ێ = % X, want 80 E9", got)
}
if got := escpos.CodePage850.Encode("é"); !bytes.Equal(got, []byte{0x82}) {
t.Errorf("cp850 é = % X, want 82", got)
}
}
func TestParseCodePage(t *testing.T) {
for _, name := range []string{"cp437", "CP437", "437"} {
if cp, err := escpos.ParseCodePage(name); err != nil || cp != escpos.CodePage437 {
t.Errorf("ParseCodePage(%q) = %v, %v", name, cp, err)
}
}
if _, err := escpos.ParseCodePage("ebcdic"); !errors.Is(err, escpos.ErrInvalidArgument) {
t.Errorf("ParseCodePage(ebcdic) err = %v", err)
}
}
func TestRasterImagePacksBitsAndPadsWidth(t *testing.T) {
// 10x2 image: row 0 is black at x=0 and x=9, row 1 is all white.
img := image.NewGray(image.Rect(0, 0, 10, 2))
for i := range img.Pix {
img.Pix[i] = 0xFF
}
img.SetGray(0, 0, color.Gray{})
img.SetGray(9, 0, color.Gray{})
var b escpos.Builder
if err := b.RasterImage(img); err != nil {
t.Fatal(err)
}
want := []byte{
0x1D, 0x76, 0x30, 0, 2, 0, 2, 0, // 2 bytes wide, 2 rows
0x80, 0x40, // row 0: bit for x=0, bit for x=9
0x00, 0x00, // row 1: padding stays white
}
if !bytes.Equal(b.Bytes(), want) {
t.Errorf("got % X, want % X", b.Bytes(), want)
}
}
func TestRasterImageRespectsBoundsOrigin(t *testing.T) {
// A sub-image whose bounds do not start at (0,0).
full := image.NewGray(image.Rect(0, 0, 16, 4))
for i := range full.Pix {
full.Pix[i] = 0xFF
}
full.SetGray(8, 2, color.Gray{})
sub := full.SubImage(image.Rect(8, 2, 16, 3))
var b escpos.Builder
if err := b.RasterImage(sub); err != nil {
t.Fatal(err)
}
want := []byte{0x1D, 0x76, 0x30, 0, 1, 0, 1, 0, 0x80}
if !bytes.Equal(b.Bytes(), want) {
t.Errorf("got % X, want % X", b.Bytes(), want)
}
}
func TestRasterImageBandsTallImages(t *testing.T) {
img := image.NewGray(image.Rect(0, 0, 8, 600))
var b escpos.Builder
if err := b.RasterImage(img); err != nil {
t.Fatal(err)
}
headers := []([]byte){
{0x1D, 0x76, 0x30, 0, 1, 0, 0x00, 0x01}, // 256 rows
{0x1D, 0x76, 0x30, 0, 1, 0, 0x00, 0x01}, // 256 rows
{0x1D, 0x76, 0x30, 0, 1, 0, 88, 0}, // 88 rows
}
out := b.Bytes()
for i, h := range headers {
if !bytes.HasPrefix(out, h) {
t.Fatalf("band %d header = % X, want % X", i, out[:min(8, len(out))], h)
}
rows := int(h[6]) | int(h[7])<<8
out = out[8+rows:]
}
if len(out) != 0 {
t.Errorf("%d trailing bytes", len(out))
}
}
func TestRasterImageTransparentIsWhite(t *testing.T) {
img := image.NewNRGBA(image.Rect(0, 0, 8, 1))
img.SetNRGBA(0, 0, color.NRGBA{A: 0}) // transparent black: paper shows
img.SetNRGBA(1, 0, color.NRGBA{A: 255}) // opaque black
img.SetNRGBA(2, 0, color.NRGBA{R: 255, G: 255, B: 255, A: 255})
var b escpos.Builder
if err := b.RasterImage(img); err != nil {
t.Fatal(err)
}
if got := b.Bytes()[8]; got != 0x40 {
t.Errorf("row byte = %08b, want 01000000", got)
}
}
func TestRasterImageEmpty(t *testing.T) {
var b escpos.Builder
if err := b.RasterImage(image.NewGray(image.Rect(0, 0, 0, 0))); !errors.Is(err, escpos.ErrInvalidArgument) {
t.Errorf("err = %v, want ErrInvalidArgument", err)
}
}
func TestStatusApply(t *testing.T) {
tests := []struct {
name string
resps map[escpos.StatusKind]byte
want escpos.Status
ready bool
}{
{
name: "healthy",
resps: map[escpos.StatusKind]byte{1: 0x12, 2: 0x12, 3: 0x12, 4: 0x12},
want: escpos.Status{Online: true},
ready: true,
},
{
name: "cover open",
resps: map[escpos.StatusKind]byte{1: 0x1A, 2: 0x16, 3: 0x12, 4: 0x12},
want: escpos.Status{CoverOpen: true},
},
{
name: "paper near end",
resps: map[escpos.StatusKind]byte{1: 0x12, 2: 0x12, 3: 0x12, 4: 0x1E},
want: escpos.Status{Online: true, PaperNearEnd: true},
ready: true,
},
{
name: "paper out",
resps: map[escpos.StatusKind]byte{1: 0x1A, 2: 0x32, 3: 0x12, 4: 0x72},
want: escpos.Status{PaperEndStop: true, PaperOut: true},
},
{
// The reading a TM-T88IV gave mid-print: online, yet DLE EOT 2
// claims the cover is open. Apply keeps the raw bits.
name: "online with stale cover bit",
resps: map[escpos.StatusKind]byte{1: 0x12, 2: 0x16, 3: 0x12, 4: 0x12},
want: escpos.Status{Online: true, CoverOpen: true},
},
{
name: "cutter error",
resps: map[escpos.StatusKind]byte{1: 0x1A, 2: 0x52, 3: 0x1A, 4: 0x12},
want: escpos.Status{CutterError: true},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var s escpos.Status
for _, kind := range escpos.StatusKinds() {
if err := s.Apply(kind, tt.resps[kind]); err != nil {
t.Fatal(err)
}
}
if s != tt.want {
t.Errorf("status = %+v, want %+v", s, tt.want)
}
if s.Ready() != tt.ready {
t.Errorf("Ready() = %v, want %v", s.Ready(), tt.ready)
}
})
}
}
func TestStatusNormalized(t *testing.T) {
tests := []struct {
name string
in escpos.Status
want escpos.Status
ready bool
}{
{
name: "online clears stale offline causes",
in: escpos.Status{Online: true, CoverOpen: true, PaperEndStop: true},
want: escpos.Status{Online: true},
ready: true,
},
{
name: "offline keeps the cover open cause",
in: escpos.Status{CoverOpen: true},
want: escpos.Status{CoverOpen: true},
},
{
name: "online keeps sensor and error bits",
in: escpos.Status{Online: true, PaperOut: true, CutterError: true},
want: escpos.Status{Online: true, PaperOut: true, CutterError: true},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := tt.in.Normalized()
if got != tt.want {
t.Errorf("Normalized() = %+v, want %+v", got, tt.want)
}
if got.Ready() != tt.ready {
t.Errorf("Ready() = %v, want %v", got.Ready(), tt.ready)
}
})
}
}
func TestStatusApplyRejectsGarbage(t *testing.T) {
var s escpos.Status
if err := s.Apply(escpos.StatusPrinter, 'H'); !errors.Is(err, escpos.ErrInvalidArgument) {
t.Errorf("err = %v, want ErrInvalidArgument", err)
}
}
func TestStatusRequest(t *testing.T) {
if got := escpos.StatusRequest(escpos.StatusPaper); !bytes.Equal(got, []byte{0x10, 0x04, 4}) {
t.Errorf("got % X", got)
}
}
func TestLookupProfile(t *testing.T) {
tests := []struct {
model string
wantName string
colsA, colsB int
}{
{"tm-t20ii", "tm-t20", 48, 64},
{"TM-T88V", "tm-t88", 42, 56},
{"tm-t88iv", "tm-t88", 42, 56},
{"tm-t88vii", "tm-t88", 42, 56},
{"tm-m50ii", "tm-m50", 42, 56},
{"generic-58mm", "generic-58mm", 32, 42},
}
for _, tt := range tests {
p, err := escpos.LookupProfile(tt.model)
if err != nil {
t.Fatalf("LookupProfile(%q): %v", tt.model, err)
}
if p.Name != tt.wantName || p.Columns(escpos.FontA) != tt.colsA || p.Columns(escpos.FontB) != tt.colsB {
t.Errorf("%q: name=%s cols=%d/%d, want %s %d/%d", tt.model, p.Name,
p.Columns(escpos.FontA), p.Columns(escpos.FontB), tt.wantName, tt.colsA, tt.colsB)
}
}
if _, err := escpos.LookupProfile("sol-802"); !errors.Is(err, escpos.ErrInvalidArgument) {
t.Errorf("unknown model err = %v", err)
}
}