package receipt_test import ( "bytes" "context" "errors" "fmt" "strings" "testing" "uberbringer/internal/pkg/escpos" "uberbringer/internal/pkg/receipt" ) func intPtr(n int) *int { return &n } // previewLines previews job on a TM-T88 in cp and returns its text lines, // without the final cut. func previewLines(t *testing.T, cp escpos.CodePage, elements ...receipt.Element) []string { t.Helper() p, err := newPreviewer(t, "tm-t88", cp).Preview(context.Background(), receipt.Job{Elements: elements}) 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) } } return lines } func expectLines(t *testing.T, got []string, want ...string) { t.Helper() if strings.Join(got, "\n") != strings.Join(want, "\n") { t.Errorf("printed:\n%s\nwant:\n%s", strings.Join(got, "\n"), strings.Join(want, "\n")) } } // TestMockups pins the boxes docs/api.md shows, each printed from one // element. func TestMockups(t *testing.T) { t.Run("double box, capped title, centred", func(t *testing.T) { got := previewLines(t, escpos.CodePage437, receipt.Element{ Type: "box", Style: "double", Title: "ACHTUNG", TitleStyle: "capped", Align: "center", Text: "The coffee machine is being descaled.\nDo not use until 10:30.", }) expectLines(t, got, "╔═╡ ACHTUNG ╞════════════════════════════╗", "║ The coffee machine is being descaled. ║", "║ Do not use until 10:30. ║", "╚════════════════════════════════════════╝", ) }) t.Run("fit, single", func(t *testing.T) { got := previewLines(t, escpos.CodePage437, receipt.Element{Type: "box", Fit: true, Padding: intPtr(3), Text: "!!! ACHTUNG !!!"}) expectLines(t, got, " ┌─────────────────────┐", " │ !!! ACHTUNG !!! │", " └─────────────────────┘", ) }) t.Run("fit, double", func(t *testing.T) { got := previewLines(t, escpos.CodePage437, receipt.Element{Type: "box", Style: "double", Fit: true, Padding: intPtr(2), Text: "!!! ACHTUNG !!!"}) expectLines(t, got, " ╔═══════════════════╗", " ║ !!! ACHTUNG !!! ║", " ╚═══════════════════╝", ) }) } // TestBoxMatrix lays out every box style, title style, padding, size and // font in every golden code page, and checks the geometry of each line. func TestBoxMatrix(t *testing.T) { styles := []string{"single", "double", "double-h", "double-v", "ascii"} const ( tops = "┌╔╒╓+" topEnds = "┐╗╕╖+" sides = "│║|" bottoms = "└╚╘╙+" botEnds = "┘╝╛╜+" joins = "├╞╟╠+" joinEnd = "┤╡╢╣+" ) for _, cp := range goldenCodePages { r := newPreviewer(t, "tm-t88", cp) for _, style := range styles { for _, titleStyle := range []string{"inline", "capped"} { for padding := range 4 { for size := 1; size <= 3; size++ { for _, font := range []string{"a", "b"} { el := receipt.Element{ Type: "box", Style: style, Title: "Title", TitleStyle: titleStyle, Padding: intPtr(padding), Size: size, Font: font, Footer: "foot", Children: []receipt.Element{ {Type: "text", Text: "Some text that wraps across the lines of the box."}, {Type: "rule", Text: "label"}, {Type: "kv", Pairs: []receipt.Pair{{Key: "k", Value: "value"}}}, {Type: "rule", Style: "double"}, }, } name := fmt.Sprintf("%s/%s/%s/p%d/s%d/%s", cp, style, titleStyle, padding, size, font) p, err := r.Preview(context.Background(), receipt.Job{Elements: []receipt.Element{el}}) if err != nil { t.Fatalf("%s: %v", name, err) } glyph := map[string]int{"a": 12, "b": 9}[font] cols := 512 / (glyph * size) var lines []string for _, l := range p.Lines { if l.Kind == escpos.LineText { lines = append(lines, l.Text) } } for i, line := range lines { runes := []rune(line) if len(runes) != cols { t.Errorf("%s: line %d %q is %d wide, want %d", name, i, line, len(runes), cols) continue } first, last := string(runes[0]), string(runes[len(runes)-1]) var wantFirst, wantLast string switch { case i == 0: wantFirst, wantLast = tops, topEnds case i == len(lines)-1: wantFirst, wantLast = bottoms, botEnds case strings.Contains(joins, first): wantFirst, wantLast = joins, joinEnd default: wantFirst, wantLast = sides, sides } if !strings.Contains(wantFirst, first) || !strings.Contains(wantLast, last) { t.Errorf("%s: line %d %q does not start and end with a border", name, i, line) } for _, r := range line { if !cp.CanEncode(r) { t.Errorf("%s: line %d has %q, which %s cannot print", name, i, r, cp) } } } } } } } } } } func TestBlockStyleRuns(t *testing.T) { p, err := newPreviewer(t, "tm-t88", escpos.CodePage437).Preview(context.Background(), receipt.Job{Elements: []receipt.Element{ {Type: "box", Text: "Bold", Bold: true, Underline: 1, Invert: true, Title: "T"}, {Type: "kv", Pairs: []receipt.Pair{{Key: "Key", Value: "Value", Bold: true}}}, {Type: "rule", Text: "Label", Bold: true, Size: 2}, }}) if err != nil { t.Fatal(err) } styled := func(line int) []escpos.Run { return p.Lines[line].Runs } bold := escpos.Run{Bold: true, Font: escpos.FontA, W: 1, H: 1} tests := []struct { line int want []escpos.Run }{ {0, nil}, // the top border, title included, is plain {1, []escpos.Run{{From: 2, To: 6, Bold: true, Underline: escpos.UnderlineThin, Invert: true, Font: escpos.FontA, W: 1, H: 1}}}, {2, nil}, {3, []escpos.Run{withSpan(bold, 0, 3), withSpan(bold, 37, 42)}}, {4, []escpos.Run{ {From: 0, To: 8, Font: escpos.FontA, W: 2, H: 2}, {From: 8, To: 13, Bold: true, Font: escpos.FontA, W: 2, H: 2}, {From: 13, To: 21, Font: escpos.FontA, W: 2, H: 2}, }}, } for _, tt := range tests { if got := styled(tt.line); fmt.Sprint(got) != fmt.Sprint(tt.want) { t.Errorf("line %d %q runs = %+v, want %+v", tt.line, p.Lines[tt.line].Text, got, tt.want) } } } func TestBoxTitleBold(t *testing.T) { p, err := newPreviewer(t, "tm-t88", escpos.CodePage437).Preview(context.Background(), receipt.Job{Elements: []receipt.Element{ {Type: "box", Title: "Title", TitleBold: true, Text: "x"}, {Type: "box", Title: "Capped", TitleStyle: "capped", TitleBold: true, Style: "double", Text: "x"}, }}) if err != nil { t.Fatal(err) } bold := escpos.Run{Bold: true, Font: escpos.FontA, W: 1, H: 1} tests := []struct { line int text string want []escpos.Run }{ {0, "┌─ Title ", []escpos.Run{withSpan(bold, 3, 8)}}, {1, "│ x ", nil}, {3, "╔═╡ Capped ╞", []escpos.Run{withSpan(bold, 4, 10)}}, } for _, tt := range tests { line := p.Lines[tt.line] if !strings.HasPrefix(line.Text, tt.text) || fmt.Sprint(line.Runs) != fmt.Sprint(tt.want) { t.Errorf("line %d %q runs = %+v, want %q... with %+v", tt.line, line.Text, line.Runs, tt.text, tt.want) } } } func withSpan(r escpos.Run, from, to int) escpos.Run { r.From, r.To = from, to return r } func TestBoxLineSpacing(t *testing.T) { r := receipt.NewRenderer(receipt.Options{ Profile: escpos.Profile{Name: "tm-t88", DotsPerLine: 512, FontAWidth: 12, FontBWidth: 9}, CodePage: escpos.CodePage437, MaxPixels: 1000, MaxHeight: 1000, BoxLineSpacing: 24, }, &fakeFetcher{}) out, err := r.Render(context.Background(), receipt.Job{Elements: []receipt.Element{ {Type: "rule"}, {Type: "box", Text: "spaced"}, {Type: "kv", Pairs: []receipt.Pair{{Key: "a", Value: "b"}}}, }}) if err != nil { t.Fatal(err) } set, reset := []byte{0x1B, '3', 24}, []byte{0x1B, '2'} if bytes.Count(out, set) != 1 || bytes.Count(out, reset) != 1 { t.Fatalf("want one ESC 3 24 and one ESC 2, got % X", out) } top := bytes.Index(out, escpos.CodePage437.Encode("┌")) bottom := bytes.Index(out, escpos.CodePage437.Encode("┘")) if i := bytes.Index(out, set); i > top || bytes.Index(out, reset) < bottom { t.Error("the line spacing must be set before the box and restored after it") } if i := bytes.Index(out, set); i < bytes.LastIndex(out[:top], escpos.CodePage437.Encode("─")) { t.Error("the rule before the box must keep the default spacing") } plain := render(t, receipt.Job{Elements: []receipt.Element{{Type: "box", Text: "default"}}}) if bytes.Contains(plain, set[:2]) || bytes.Contains(plain, reset) { t.Error("without BoxLineSpacing no line spacing command may be sent") } } func TestLineLimit(t *testing.T) { r := receipt.NewRenderer(receipt.Options{ Profile: escpos.Profile{Name: "tm-t88", DotsPerLine: 512, FontAWidth: 12, FontBWidth: 9}, CodePage: escpos.CodePage437, MaxPixels: 1000, MaxHeight: 1000, MaxLines: 100, }, &fakeFetcher{}) tests := []struct { name string job receipt.Job lines int // 0 when the job is within the limit }{ {"within", receipt.Job{Elements: []receipt.Element{{Type: "feed", Lines: 99}}}, 0}, {"exactly the limit", receipt.Job{Elements: []receipt.Element{{Type: "feed", Lines: 99}, {Type: "text", Text: "x"}}}, 0}, {"one over", receipt.Job{Elements: []receipt.Element{{Type: "feed", Lines: 100}, {Type: "text", Text: "x"}}}, 101}, {"copies count", receipt.Job{Copies: 3, Elements: []receipt.Element{{Type: "feed", Lines: 40}}}, 120}, {"wrapped text", receipt.Job{Elements: []receipt.Element{{Type: "text", Text: strings.Repeat("word ", 1000)}}}, 120}, {"box", receipt.Job{Elements: []receipt.Element{{Type: "box", Text: strings.Repeat("\n", 98)}}}, 101}, {"kv rows in a box", receipt.Job{Elements: []receipt.Element{{Type: "box", Children: []receipt.Element{{Type: "kv", Pairs: manyPairs(100)}}}}}, 102}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { _, renderErr := r.Render(context.Background(), tt.job) p, previewErr := r.Preview(context.Background(), tt.job) for name, err := range map[string]error{"Render": renderErr, "Preview": previewErr} { var limit *receipt.LineLimitError switch { case tt.lines == 0 && err != nil: t.Errorf("%s: %v", name, err) case tt.lines > 0 && !errors.As(err, &limit): t.Errorf("%s: err = %v, want *LineLimitError", name, err) case tt.lines > 0 && tt.name != "wrapped text" && limit.Lines != tt.lines: t.Errorf("%s: %d lines, want %d", name, limit.Lines, tt.lines) case tt.lines > 0 && limit.Error() != fmt.Sprintf("receipt would print %d lines, limit is 100", limit.Lines): t.Errorf("%s: message %q", name, limit.Error()) } } if tt.lines == 0 && p.LineCount > 100 { t.Errorf("LineCount = %d", p.LineCount) } }) } } func manyPairs(n int) []receipt.Pair { pairs := make([]receipt.Pair, n) for i := range pairs { pairs[i] = receipt.Pair{Key: "k", Value: "v"} } return pairs } func TestPreview(t *testing.T) { fetcher := &fakeFetcher{err: errors.New("preview must not fetch")} r := receipt.NewRenderer(receipt.Options{ Profile: escpos.Profile{Name: "tm-t88", DotsPerLine: 512, FontAWidth: 12, FontBWidth: 9}, CodePage: escpos.CodePage437, MaxPixels: 1000, MaxHeight: 1000, }, fetcher) job := receipt.Job{Copies: 2, Elements: []receipt.Element{ {Type: "text", Text: "Tea “Earl Grey” 🍵", Align: "center"}, {Type: "raw", Hex: "1B 61 01 07"}, {Type: "image", URL: "https://images.example/logo.png?size=2", Width: 384}, {Type: "image", Base64: "iVBORw0KGgo=", Width: 600}, {Type: "image", URL: "https://images.example/wide.png", Width: 600, Optional: true}, {Type: "qr", Data: "https://example.com"}, {Type: "barcode", Symbology: "ean8", Data: "9638507"}, {Type: "cut", Mode: "full"}, }} p, err := r.Preview(context.Background(), job) if err != nil { t.Fatal(err) } if len(fetcher.urls) != 0 { t.Errorf("preview fetched %v", fetcher.urls) } copyLines := []string{ strings.Repeat(" ", 12) + `Tea "Earl Grey" ?`, "[raw 4 bytes]", "[image 384 dots: logo.png]", "[image 600 dots: base64]", "[image 512 dots: wide.png]", "[qr: https://example.com]", "[barcode ean8: 9638507]", " - - - - - - - - full cut - - - - - - - -", } var got []string for _, l := range p.Lines { got = append(got, l.Text) } expectLines(t, got, append(copyLines, copyLines...)...) if p.Lines[2].Data != "https://images.example/logo.png?size=2" || p.Lines[3].Data != "base64" { t.Errorf("image data = %q, %q", p.Lines[2].Data, p.Lines[3].Data) } if p.Columns != 42 || p.CodePage != escpos.CodePage437 || p.LineCount != 12 { t.Errorf("columns %d, code page %s, %d lines; want 42, cp437 and 12", p.Columns, p.CodePage, p.LineCount) } wantWarnings := []string{ "elements[0]: 1 character not in cp437 printed as ?", "elements[3] (image): width 600 is wider than the 512-dot paper, so the job would fail", } if strings.Join(p.Warnings, "\n") != strings.Join(wantWarnings, "\n") { t.Errorf("warnings = %q, want %q", p.Warnings, wantWarnings) } } func TestPreviewRejectsInvalidJobs(t *testing.T) { _, err := newPreviewer(t, "tm-t88", escpos.CodePage437).Preview(context.Background(), receipt.Job{}) var ve *receipt.ValidationError if !errors.As(err, &ve) { t.Errorf("err = %v, want *ValidationError", err) } } // TestRenderBlocksBytes pins the commands a block is printed with. func TestRenderBlocksBytes(t *testing.T) { out := render(t, receipt.Job{Elements: []receipt.Element{ {Type: "text", Text: "x", Newline: boolPtr(false)}, {Type: "rule", Columns: 4, Size: 2, Text: "", Style: "double"}, }}) want := []byte{ 'x', 0x1B, 'E', 0, 0x1B, '-', 0, 0x1D, 'B', 0, 0x1D, '!', 0, 0x1B, 'M', 0, // the text and its reset 0x0A, // the inline line is ended before the block 0x1B, 'a', 0, 0x1B, 'M', 0, 0x1D, '!', 0x11, // left, Font A, size 2 0x1B, 'E', 0, 0x1B, '-', 0, 0x1D, 'B', 0, // plain 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, // centred on 24 columns 0xCD, 0xCD, 0xCD, 0xCD, 0x0A, 0x1B, 'E', 0, 0x1B, '-', 0, 0x1D, 'B', 0, 0x1D, '!', 0, 0x1B, 'M', 0, // reset } if !bytes.Contains(out, want) { t.Errorf("stream % X does not contain % X", out, want) } }