diff --git a/AGENTS.md b/AGENTS.md
index 09731c1..dfab0a0 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -4,12 +4,12 @@ Operational context, architectural invariants, and strict guardrails for AI agen
## 1. Project Overview & Tech Stack
-Poster is a Go library and CLI utility for controlling ESC/POS thermal receipt printers via a versioned JSON document protocol (`v1.0`), programmatic Go builders, native Windows Print Spooler integration (`winspool.drv`), an Atkinson/Threshold dithering graphics pipeline, an auto-balancing table layout engine, and a standalone 2D visual PNG emulator.
+Poster is a Go library and CLI utility for controlling ESC/POS thermal receipt printers via a versioned JSON document protocol (`v1.0`), programmatic Go builders, pluggable `io.WriteCloser` transports (Windows Spooler, raw TCP, file/device, in-memory buffer), a multi-algorithm dithering graphics pipeline, an auto-balancing pure-text table engine, multi-codepage text encoding, and a 2D PNG emulator that can render both documents (via `PrinterActions`) and raw ESC/POS byte streams.
- **Language / Runtime**: Go `1.24.6+` (`module github.com/adcondev/poster`)
- **Target Platforms**:
- - **Windows (`//go:build windows`)**: Full native hardware printing and printer discovery via `winspool.drv`.
- - **Cross-Platform (`linux`, `darwin`, `windows`)**: Pure Go compilation and test execution for all ESC/POS command builders, composer, JSON schema/builder/executor, graphics, tables, profiles, emulator, and non-Windows connection stubs (`//go:build !windows`).
+ - **Windows (`//go:build windows`)**: Native Spooler printing and printer discovery via `winspool.drv`.
+ - **Cross-Platform (`linux`, `darwin`, `windows`)**: Everything else — command builders, composer, schema/builder/executor, graphics, tables, profiles, emulator, and `TCPConnector` / `FileConnector` / `BufferConnector`.
- **Release & Commit Tooling**: Node.js (`standard-version`, `@commitlint/cli`, `prettier`), Go `Taskfile.yml`, `golangci-lint` v2, and GitHub Actions.
---
@@ -19,22 +19,22 @@ Poster is a Go library and CLI utility for controlling ESC/POS thermal receipt p
| Path | Responsibility |
|---|---|
| `api/v1/` | **Canonical Contract**: `ticket_document.schema.json` (JSON Schema Draft-07) and `TICKET_DOCUMENT_V1.md`. |
-| `cmd/poster/` | CLI binary (`main.go`, `parsing.go`, `printing.go` [`windows`], `printing_stub.go` [`!windows`]). Version injected via `-ldflags "-X main.AppVersion=..."`. |
+| `cmd/poster/` | CLI binary (`main.go`, `parsing.go`, `printing.go` [`windows`], `printing_stub.go` [`!windows`]). Flags: `-t windows\|tcp\|network\|file`, `-network`, `-o/-output`, `-preview`, `--dry-run`, `--list*`. Version injected via `-ldflags "-X main.AppVersion=..."`. |
| `internal/calculate/` | Pure math conversions between millimeters, DPI, and dots (`DotsPerLine`, `MmToDots`, `DotsToMm`). |
| `internal/load/` | Path-traversal-safe file loader (`SecureFilepath`) and image decoder (`PNG`, `JPEG`, `BMP` via `golang.org/x/image/bmp`). |
| `internal/testutils/` | Shared test assertions, byte slice validators, and fake/mock helpers. |
-| `pkg/commands/*` | Stateless, pure ESC/POS byte generators (`barcode`, `bitimage`, `character`, `linespacing`, `mechanismcontrol`, `print`, `printposition`, `qrcode`, `shared`). Each subpackage exposes a `Capability` interface and `NewCommands()`. |
+| `pkg/commands/*` | Stateless, pure ESC/POS byte generators (`barcode`, `bitimage`, `character`, `linespacing`, `mechanismcontrol`, `print`, `printposition`, `qrcode` [QR + PDF417], `shared`). Each subpackage exposes a `Capability` interface and `NewCommands()`. |
| `pkg/composer/` | High-level protocol facade (`EscposProtocol`) aggregating all `pkg/commands/*` capabilities into atomic ESC/POS sequences. |
-| `pkg/connection/` | Transport abstraction (`Connector` implementing `io.WriteCloser`, `PrinterService`) and Windows Spooler (`winspool.drv`) implementation + printer enumeration. |
-| `pkg/constants/` | Centralized typed string enums, paper/dot geometry constants (`576` dots for 80mm, `384` dots for 58mm), and schema-aligned defaults. |
-| `pkg/document/schema/` | Top-level JSON AST (`Document`, `ProfileConfig`, `Command`), `ParseDocument`, and structural/version validation (`Validate`). |
+| `pkg/connection/` | `Connector` (`io.WriteCloser`) implementations: `WindowsPrintConnector` (`winspool.drv`), `TCPConnector`, `FileConnector`, `BufferConnector`; cross-platform printer filtering + Windows enumeration. |
+| `pkg/constants/` | Centralized typed string enums, paper/dot geometry constants (`576` dots for 80mm, `384` dots for 58mm), size limits (`MaxJSONSize`), and schema-aligned defaults. |
+| `pkg/document/schema/` | Top-level JSON AST (`Document`, `ProfileConfig`, `Command`, per-command structs), `ParseDocument`, and structural/version validation (`Validate`). |
| `pkg/document/builder/` | Fluent Go DSL (`DocumentBuilder`) for programmatic construction of `schema.Document` payloads. |
-| `pkg/document/executor/` | Document execution engine (`Executor`, `CommandHandler` registry) translating `schema.Document` commands into `service.PrinterActions` calls. |
-| `pkg/emulator/` | Standalone 2D visual receipt renderer (`Engine`, `DynamicCanvas`, embedded `JetBrainsMono`/`Ticketing` TTF fonts + 5x7 ASCII fallback) outputting PNG previews. |
-| `pkg/graphics/` | Image scaling (`BiLinear`, `NearestNeighbor`), `Atkinson`/`Threshold` dithering into 1-bit `MonochromeBitmap`, QR image generation (`yeqown/go-qrcode/v2`), and barcode config mapping. |
-| `pkg/profile/` | Hardware profiles (`80mm`, `58mm`, `PT-210`, `GP-58N`, `EC-PM-80250`) and UTF-8 to 1-byte code page encoding (`charmap`, `ShiftJIS`). |
-| `pkg/service/` | Stateful printer orchestrator (`Printer`), `PrinterActions` interface (including `Close() error`), and `MockPrinter`. |
-| `pkg/tables/` | Multi-column receipt layout engine (`TabEngine`), UTF-8 rune word-wrapping, alignment padding, and widest-column-first `ReduceToFit`. |
+| `pkg/document/executor/` | Document execution engine (`Executor`, `CommandHandler` registry, `RegisterHandler`) translating `schema.Document` commands into `service.PrinterActions` calls. |
+| `pkg/emulator/` | 2D receipt renderer (`Engine`, `DynamicCanvas`, embedded TTF fonts), `emulator.Printer` (`service.PrinterActions` adapter), and raw byte parser (`Engine.ParseESC`, `RenderBytesToPNG`). |
+| `pkg/graphics/` | Image loading/scaling, `Atkinson`/`FloydSteinberg`/`Ordered`/`Threshold` dithering into 1-bit `MonochromeBitmap` (+ `SubBand`), QR image generation (`yeqown/go-qrcode/v2`), and barcode symbology mapping. |
+| `pkg/profile/` | Hardware profiles + model presets (`ProfileFromModel`), 25 code tables (`ParseCodeTable`), `NormalizeTypography`, and `EncodeBytesSafe` (multi-codepage `ESC t n` switching, `'?'` fallback, `StrictEncoding`). |
+| `pkg/service/` | Stateful printer orchestrator (`Printer`, `NewPrinterWithOptions`), `PrinterActions` interface (including `Close() error`), and `MockPrinter`. |
+| `pkg/tables/` | Pure-text multi-column layout engine (`TabEngine`, `Render`, `RenderStructured`) — no ESC/POS bytes; UTF-8 rune word-wrapping, alignment padding, widest-column-first `ReduceToFit`. |
---
@@ -52,15 +52,21 @@ Poster is a Go library and CLI utility for controlling ESC/POS thermal receipt p
- `executor.Execute` MUST fail fast (return an error) on unsupported `doc.Version`, unknown command types, invalid command payloads, or profile configuration errors.
3. **Hardware, Service & Emulator Boundaries**:
- `executor.Executor` and all `CommandHandler` implementations MUST depend on the `service.PrinterActions` interface (including `Close() error`), never the concrete `*service.Printer` struct.
- - `pkg/emulator` is an independent 2D canvas preview engine, not a `connection.Connector`.
- - `pkg/connection` is scoped strictly to Windows Print Spooler (`winspool.drv`) and `io.WriteCloser` mocks/files. OS-specific files (`//go:build windows` vs `//go:build !windows`) MUST export identical struct field types and signatures so cross-platform builds and tests never diverge.
+ - `pkg/emulator` is a preview engine, not a `connection.Connector`. It integrates via `emulator.Printer` (implements `service.PrinterActions`) and `ParseESC` / `RenderBytesToPNG` (consumes raw bytes). `ParseESC` MUST never panic or index out of bounds on truncated/malformed input.
+ - `pkg/connection` transports are `io.WriteCloser` only (Windows Spooler, TCP, file/device, buffer). OS-specific files (`//go:build windows` vs `//go:build !windows`) MUST export identical struct field types and signatures so cross-platform builds and tests never diverge.
+ - `pkg/tables` MUST remain pure text (no `pkg/composer` import, no raw ESC/POS bytes). Styling (e.g., bold headers) is applied by callers via `RenderStructured` + `PrinterActions`.
4. **Standard Paper & Dot Geometry (203 DPI / 8 dpmm)**:
- **80mm paper** (`72mm` printable width): `576` dots per line (`48` Font A chars, `64` Font B chars).
- **58mm paper** (`48mm` printable width): `384` dots per line (`32` Font A chars, `42` Font B chars).
- - All packages (`pkg/constants`, `pkg/profile`, `pkg/commands/shared`, `pkg/document/executor`, `internal/calculate`) MUST resolve to these exact standard dot widths.
-5. **QR & Barcode Rendering Policy**:
+ - All packages (`pkg/constants`, `pkg/profile`, `pkg/commands/shared`, `pkg/document/executor`, `internal/calculate`) MUST resolve to these exact standard dot widths. Image/QR max widths MUST derive from `Profile.DotsPerLine`, never a hardcoded 80mm constant.
+5. **QR, PDF417 & Barcode Rendering Policy**:
- **QR Codes (`service.PrintQR`)**: Use native ESC/POS (`GS ( k`) only when `Profile.HasQR == true` AND neither `logo` nor `circle_shape` is enabled. Whenever `logo` or `circle_shape` is requested (or `Profile.HasQR == false`), automatically render via the software bitmap pipeline (`pkg/graphics`).
- - **1D Barcodes (`service.PrintBarcode`)**: Use native ESC/POS (`GS k`) hardware commands. Do not claim software rasterization for 1D barcodes unless implemented in `pkg/graphics`.
+ - **PDF417**: Native `GS ( k` (`cn=48`) only; no software fallback yet.
+ - **1D Barcodes (`service.PrintBarcode`)**: Use native ESC/POS (`GS k`) hardware commands. Do not claim software rasterization for 1D barcodes on hardware unless implemented in `pkg/graphics` (the emulator renders them in software for previews only).
+6. **Text Encoding Policy**:
+ - `service.Printer.Print` / `PrintLine` MUST encode via `Profile.EncodeBytesSafe` (typography normalization → active code table → optional `ESC t n` auto-switch → `'?'` fallback, or error when `StrictEncoding`).
+ - New code tables MUST be added to `profile.ParseCodeTable` and `constants.ValidCodeTables` together.
+7. **Resource Limits**: JSON input ≤ `constants.MaxJSONSize` (10MB); image height ≤ `graphics.MaxImagePixelHeight` (32000); tall bitmaps are band-split when `Profile.MaxBandHeight > 0`.
---
@@ -101,4 +107,5 @@ All commits and PR titles MUST follow Conventional Commits:
1. **Token Economy**: NEVER `cat` or read binary files, images (`assets/images/poster.png`), large base64/text dumps (`assets/images/imagen.txt`, `assets/images/logo.txt`), or full `CHANGELOG.md` (use `head -n 40 CHANGELOG.md`). Prefer `go doc`, `grep -E "^(type|func) "`, and targeted line ranges.
2. **No Unsafe Slice Indexing**: Never index `&data[0]` or slice `s[:n-1]` without explicit length/bounds checks (`len(data) == 0`).
3. **No Hardcoded Local Paths or Versions**: Never commit machine-specific paths in `Taskfile.yml` or hardcoded version strings in `cmd/poster/main.go`.
-4. **No Unimplemented Transport Claims**: Do not document ZPL, Scale protocols, raw TCP/9100, Serial COM, or Bluetooth as active features until implemented and tested.
+4. **No Unimplemented Transport Claims**: Do not document ZPL, Scale protocols, Serial COM, Bluetooth, USB-native (libusb), or bidirectional status (`DLE EOT` / ASB) as active features until implemented and tested. (Raw TCP/9100 and file/device output ARE implemented.)
+5. **Coverage Floor**: Do not merge changes that drop any library package below ~85% statement coverage without an explicit, documented reason.
diff --git a/README.md b/README.md
index 0ec69bd..87ae11a 100644
--- a/README.md
+++ b/README.md
@@ -1,7 +1,7 @@
# Poster: Thermal Printer Driver & ESC/POS Utility

-
+

[](https://github.com/adcondev/poster/actions/workflows/ci.yml)
@@ -24,20 +24,24 @@ A professional, production-ready Go library and command-line utility for control
## 🚀 Key Features
- **JSON Document Protocol**: Define print jobs using a clean, versioned JSON schema (`v1.0`). Decouples business logic from hardware commands with full schema validation.
-- **Native Windows Integration**: Prints directly via the Windows Print Spooler API (`winspool.drv`), supporting USB, Serial, and Network printers installed in Windows.
+- **Pluggable Transports (`io.WriteCloser`)**: Native Windows Print Spooler (`winspool.drv`), pure-Go cross-platform raw TCP (`:9100`), file/device output (`.bin` files, `/dev/usb/lp*`), and in-memory buffers.
- **Advanced Graphics Engine**:
- - High-quality monochrome rasterization with **Atkinson** and **Threshold** dithering.
- - Configurable image scaling (`bilinear` and `nns` / `nearest_neighbor`).
+ - Monochrome rasterization with **Atkinson**, **Floyd-Steinberg**, **Ordered (4x4 Bayer)**, and **Threshold** dithering.
+ - Configurable image scaling (`bilinear` and `nns` / `nearest_neighbor`), profile-aware max width, and automatic horizontal **band chunking** (`MaxBandHeight`) for small-buffer printers.
- Supports PNG, JPEG, and BMP formats (file paths or Base64).
-- **Smart QR & Native Barcodes**:
+- **Smart QR, PDF417 & Native Barcodes**:
- **QR Codes**: Automatically selects between native printer firmware commands (`GS ( k`) and software bitmap rendering (`pkg/graphics`) when custom **logo overlays**, **circular modules** (`circle_shape`), or non-QR profiles are used.
- - **1D Barcodes**: Fast native ESC/POS (`GS k`) generation supporting `CODE128` (auto Set A/B/C), `EAN13`, `EAN8`, `UPCA`, `UPCE`, `CODE39`, `ITF`, and `CODABAR`.
-- **Dynamic Table Layout**: Built-in engine for generating aligned receipts with UTF-8 word wrapping, multi-column support, configurable column spacing (`0+`), **automatic overflow detection**, and **smart widest-column-first auto-reduction** (`ReduceToFit`).
-- **Visual Emulator**: Standalone 2D receipt preview engine (`pkg/emulator`) with embedded TrueType fonts (`JetBrainsMono`, `Ticketing`) and 5x7 ASCII fallback that renders print jobs to PNG images without physical hardware.
-- **Hardware Profiles & Encodings**: Built-in profiles for standard 80mm (`576` dots), 58mm (`384` dots), PT-210, GP-58N, and EC-PM-80250 printers with 23 single-byte and Shift-JIS character code tables.
+ - **PDF417**: Native `GS ( k` (`cn=48`) with columns, rows, module width, row height, and error-correction level.
+ - **1D Barcodes**: Native ESC/POS (`GS k`) supporting `CODE128` (auto Set B/C), `CODE128_AUTO`, `GS1-128`, `CODE93`, `EAN13`, `EAN8`, `UPCA`, `UPCE`, `CODE39`, `ITF`, and `CODABAR`.
+- **Dynamic Table Layout**: Pure-text engine (`pkg/tables`, no ESC/POS coupling) with UTF-8 word wrapping, multi-column support, Font B, configurable column spacing, overflow detection, and widest-column-first `ReduceToFit`.
+- **Visual Emulator & Reverse Parser**:
+ - `emulator.Printer` implements `service.PrinterActions`, so any `schema.Document` can be rendered to PNG via the same `executor` (`poster -preview out.png`).
+ - `emulator.RenderBytesToPNG` parses **raw ESC/POS byte streams** (text, styles, alignment, cuts, `GS v 0` rasters) back into a PNG preview.
+- **International Encoding ("Magic Encode")**: 25 code tables, smart-typography normalization (curly quotes, dashes, ellipsis, NBSP), optional mid-string `ESC t n` auto-switching across fallback code pages, and `'?'` replacement (or `StrictEncoding`) for unmappable runes.
+- **Hardware Profiles**: Generic 80mm (`576` dots) / 58mm (`384` dots), PT-210, GP-58N, EC-PM-80250, Epson TM-T20III / TM-T88VI, Star TSP100, Bixolon SRP-350III, and Xprinter XP-58 / XP-80 presets resolvable by model name (`profile.ProfileFromModel`).
- **Smart Printer Discovery**: Enumerates and filters physical vs. virtual thermal/POS printers installed in the Windows Print Spooler.
-- **11 Document Command Types**: `text`, `image`, `barcode`, `qr`, `table`, `separator`, `feed`, `cut`, `raw`, `pulse`, `beep`.
-- **Raw Command Support**: Send raw hex ESC/POS byte sequences with safety checks against bidirectional lockups.
+- **12 Document Command Types**: `text`, `image`, `barcode`, `qr`, `pdf417`, `table`, `separator`, `feed`, `cut`, `raw`, `pulse`, `beep`.
+- **Raw Command Support**: Send raw hex/base64 ESC/POS byte sequences with optional safety checks against bidirectional lockups.
## 🏗️ Architecture
@@ -73,9 +77,14 @@ flowchart TD
subgraph "Transport & Preview"
Service --> Connector["Connector (io.WriteCloser)
(pkg/connection)"]
- Connector --> WinAPI["Windows Spooler API
(winspool.drv)"]
+ Connector --> WinAPI["Windows Spooler
(winspool.drv)"]
+ Connector --> TCP["TCPConnector
(:9100)"]
+ Connector --> File["FileConnector / BufferConnector"]
WinAPI --> Device["Physical Thermal Printer"]
- Emulator["Visual Emulator
(pkg/emulator)"] --> PNG["PNG Receipt Preview"]
+ TCP --> Device
+ Actions --> EmuPrinter["emulator.Printer
(pkg/emulator)"]
+ EmuPrinter --> PNG["PNG Receipt Preview"]
+ RawBytes["Raw ESC/POS bytes"] --> Parser["emulator.ParseESC"] --> PNG
end
```
@@ -84,20 +93,20 @@ flowchart TD
| Package | Description |
|---|---|
| `api/v1` | Canonical JSON Schema (`ticket_document.schema.json`) and protocol specification (`TICKET_DOCUMENT_V1.md`) |
-| `cmd/poster` | CLI utility for printer discovery, JSON validation (`--dry-run`), and Windows Spooler printing |
+| `cmd/poster` | CLI for printer discovery, JSON validation (`--dry-run`), PNG preview (`-preview`), and printing via Windows Spooler, TCP, or file |
| `internal/calculate` | Millimeter, DPI, and dot-per-line math utilities |
| `internal/load` | Path-traversal-safe file loader and PNG/JPEG/BMP image decoding (file & Base64) |
| `internal/testutils` | Shared unit test assertions, byte slice validators, and mock helpers |
-| `pkg/commands` | Pure, stateless ESC/POS command builders (`barcode`, `bitimage`, `character`, `linespacing`, `mechanismcontrol`, `print`, `printposition`, `qrcode`, `shared`) |
+| `pkg/commands` | Pure, stateless ESC/POS command builders (`barcode`, `bitimage`, `character`, `linespacing`, `mechanismcontrol`, `print`, `printposition`, `qrcode` incl. PDF417, `shared`) |
| `pkg/composer` | High-level ESC/POS protocol facade (`EscposProtocol`) |
-| `pkg/connection` | Transport interfaces (`Connector`, `PrinterService`) and Windows Spooler (`winspool.drv`) implementation |
+| `pkg/connection` | `Connector` interface plus `WindowsPrintConnector`, `TCPConnector`, `FileConnector`, `BufferConnector`, and printer discovery/filtering |
| `pkg/constants` | Shared typed enums, standard paper/dot geometry (`576` / `384` dots), and schema-aligned defaults |
| `pkg/document` | JSON document AST & validator (`schema`), fluent Go DSL (`builder`), and command runner (`executor`) |
-| `pkg/emulator` | Standalone 2D visual receipt emulator rendering PNG images with embedded TTF fonts |
-| `pkg/graphics` | Image scaling, Atkinson/Threshold dithering, 1-bit bitmaps, and QR image rendering |
-| `pkg/profile` | Hardware capability profiles (`80mm`, `58mm`, `PT-210`, `GP-58N`, `EC-PM-80250`) and character code tables |
-| `pkg/service` | Stateful printer service (`Printer`), `PrinterActions` interface, and `MockPrinter` |
-| `pkg/tables` | Multi-column table engine with UTF-8 word wrapping, header styling, and `ReduceToFit` auto-balancing |
+| `pkg/emulator` | 2D receipt renderer, `PrinterActions` adapter (`emulator.Printer`), and raw ESC/POS byte parser (`ParseESC`, `RenderBytesToPNG`) |
+| `pkg/graphics` | Image loading/scaling, Atkinson/Floyd-Steinberg/Ordered/Threshold dithering, 1-bit bitmaps with band slicing, QR rendering, barcode mapping |
+| `pkg/profile` | Hardware profiles & model presets, 25 code tables, typography normalization, and multi-codepage `EncodeBytesSafe` |
+| `pkg/service` | Stateful printer service (`Printer`, functional options), `PrinterActions` interface, and `MockPrinter` |
+| `pkg/tables` | Pure-text multi-column table engine with UTF-8 word wrapping, `RenderStructured`, and `ReduceToFit` auto-balancing |
## 📦 Installation
@@ -130,14 +139,21 @@ task build
### Command Line Interface (CLI)
-The `poster` CLI validates and prints JSON ticket documents via the Windows Print Spooler:
+The `poster` CLI validates, previews, and prints JSON ticket documents:
```bash
-# Print a JSON document to a specific Windows printer
+# Print via the Windows Print Spooler (default transport, Windows only)
poster -file receipt.json -printer "EPSON TM-T88V"
-# Auto-detect the default/first thermal printer and print
-poster -file receipt.json
+# Print to a network printer over raw TCP (any OS)
+poster -file receipt.json -t tcp -network 192.168.1.100:9100
+
+# Write raw ESC/POS bytes to a file or device (any OS)
+poster -file receipt.json -t file -o receipt.bin
+poster -file receipt.json -t file -o /dev/usb/lp0
+
+# Render a PNG preview without hardware (any OS)
+poster -file receipt.json -preview receipt.png
# Dry-run (validate JSON schema and commands without touching hardware)
poster -file receipt.json --dry-run
@@ -247,36 +263,29 @@ import (
)
func main() {
- doc, err := builder.NewDocument().
- SetProfile("Generic 80mm", 80).
- AddText(func(tb *builder.TextBuilder) {
- tb.Text("STORE NAME").Center().Bold().Size("2x2")
- }).
- Separator().
- AddQR(func(qb *builder.QRBuilder) {
- qb.Data("https://example.com").Center().PixelWidth(256)
- }).
- PartialCut().
+ doc := builder.NewDocument().
+ SetProfile("Epson TM-T88VI", 80, "PC858").
+ Text("STORE NAME").Center().Bold().Size("2x2").End().
+ Separator("-").
+ QR("https://example.com").Center().Size(256).End().
+ PDF417("INV-0001|42.50").Center().End().
+ Cut().
Build()
- if err != nil {
- log.Fatal(err)
- }
- conn, err := connection.NewWindowsPrintConnector("POS-80")
+ // Any connection.Connector works: TCP, file, buffer, or Windows Spooler.
+ conn, err := connection.NewTCPConnector("192.168.1.100:9100")
if err != nil {
log.Fatal(err)
}
- defer func() { _ = conn.Close() }()
- prof := profile.CreateProfile80mm()
- printer, err := service.NewPrinter(composer.NewEscpos(), &prof, conn)
+ prof, _ := profile.ProfileFromModel("Epson TM-T88VI")
+ printer, err := service.NewPrinter(composer.NewEscpos(), prof, conn)
if err != nil {
log.Fatal(err)
}
defer func() { _ = printer.Close() }()
- exec := executor.NewExecutor(printer)
- if err := exec.Execute(doc); err != nil {
+ if err := executor.NewExecutor(printer).Execute(doc); err != nil {
log.Fatal(err)
}
}
@@ -298,34 +307,46 @@ import (
func main() {
prof := profile.CreateProfile80mm()
+ prof.AutoSwitchCodePage = true // mid-string ESC t n switching for mixed scripts
- conn, err := connection.NewWindowsPrintConnector("POS-80")
+ conn, err := connection.NewFileConnector("receipt.bin") // or /dev/usb/lp0
if err != nil {
log.Fatal(err)
}
- defer func() { _ = conn.Close() }()
- proto := composer.NewEscpos()
- printer, err := service.NewPrinter(proto, &prof, conn)
+ printer, err := service.NewPrinter(composer.NewEscpos(), prof, conn)
if err != nil {
log.Fatal(err)
}
defer func() { _ = printer.Close() }()
_ = printer.Initialize()
- _ = printer.PrintLine("Hello World!")
+ _ = printer.PrintLine("“Café” — 5 € / Привет")
_ = printer.FullFeedAndCut(2)
}
```
+#### 3. Preview Without Hardware
+
+```go
+// Render a schema.Document to PNG through the same executor.
+emu, _ := emulator.NewPrinter(profile.CreateProfile58mm())
+_ = executor.NewExecutor(emu).Execute(doc)
+_ = emu.SavePNG("preview.png")
+
+// Or reverse-render any captured raw ESC/POS byte stream.
+pngBytes, _ := emulator.RenderBytesToPNG(rawEscPos)
+```
+
## 📋 Supported Document Commands
| Command | Description |
|---|---|
| `text` | Formatted text with optional key-value `label`, alignment, bold, underline (`1dot`/`2dot`), inverse, font (`A`/`B`), and scaling (`1x1`..`8x8`) |
-| `image` | Base64 PNG/JPEG/BMP raster printing with `atkinson` or `threshold` dithering and `bilinear` or `nns` scaling |
-| `barcode` | Native ESC/POS 1D barcodes (`CODE128`, `EAN13`, `EAN8`, `UPCA`, `UPCE`, `CODE39`, `ITF`, `CODABAR`) with HRI text options |
+| `image` | Base64 PNG/JPEG/BMP raster printing with `atkinson`, `floyd_steinberg`, `ordered`, or `threshold` dithering and `bilinear` or `nns` scaling |
+| `barcode` | Native ESC/POS 1D barcodes (`code128`, `code128_auto`, `gs1_128`, `code93`, `ean13`, `ean8`, `upca`, `upce`, `code39`, `itf`, `codabar`) with HRI text options |
| `qr` | Native or software-rendered QR codes with optional center `logo` and `circle_shape` modules |
+| `pdf417` | Native PDF417 2D barcode with `columns`, `rows`, `module_width`, `row_height`, `error_correction` (0–8) |
| `table` | Multi-column tables with column alignment, UTF-8 word wrapping, bold headers, and `auto_reduce` |
| `separator` | Horizontal character repeat separator lines |
| `feed` | Paper advance (`1`–`255` lines) |
@@ -342,18 +363,30 @@ For complete protocol documentation and JSON schema definitions, see [`api/v1/TI
| Target | Status | Description |
|---|---|---|
-| `WindowsPrintConnector` | ✅ Implemented | Native Windows Print Spooler (`winspool.drv`) supporting USB, Serial, and Network printers installed in Windows |
-| `MockPrinter` / `io.WriteCloser` | ✅ Implemented | In-memory mock and custom `io.WriteCloser` streams for unit testing and byte inspection |
+| `WindowsPrintConnector` | ✅ Implemented | Native Windows Print Spooler (`winspool.drv`) for printers installed in Windows (CLI `-t windows`, default) |
+| `TCPConnector` | ✅ Implemented | Pure-Go raw TCP (`host:9100`) with dial/write timeouts, cross-platform (CLI `-t tcp` / `-t network`) |
+| `FileConnector` | ✅ Implemented | Writes raw bytes to a `.bin` file or a device node such as `/dev/usb/lp0` (CLI `-t file -o `) |
+| `BufferConnector` | ✅ Implemented | In-memory `io.WriteCloser` for tests, byte inspection, and piping into `emulator.RenderBytesToPNG` |
+| `emulator.Printer` | ✅ Implemented | `service.PrinterActions` adapter rendering documents to PNG (CLI `-preview `) |
+| `MockPrinter` | ✅ Implemented | Call-recording `PrinterActions` mock for unit testing |
+
+> Serial COM, Bluetooth, and bidirectional status (`DLE EOT` / ASB) are **not yet implemented**.
### Built-in Printer Profiles (`pkg/profile`)
| Profile | Paper Width | Printable Width (203 DPI) | Description |
|---|---|---|---|
-| `CreateProfile80mm()` | 80mm | 576 dots (48 chars Font A) | Standard 80mm ESC/POS (Epson TM-T88 series, etc.) |
-| `CreateProfile58mm()` | 58mm | 384 dots (32 chars Font A) | Generic 58mm thermal printers |
-| `CreatePt210()` | 58mm | 384 dots (32 chars Font A) | GOOJPRT PT-210 portable printer with QR support |
-| `CreateGP58N()` | 58mm | 384 dots (32 chars Font A) | Gainscha GP-58N 58mm thermal printer |
-| `CreateECPM80250()` | 80mm | 576 dots (48 chars Font A) | EC Line EC-PM-80250 80mm thermal printer |
+| `CreateProfile80mm()` | 80mm | 576 dots (48 chars Font A) | Generic 80mm ESC/POS |
+| `CreateProfile58mm()` | 58mm | 384 dots (32 chars Font A) | Generic 58mm (`MaxBandHeight: 256`) |
+| `CreatePt210()` | 58mm | 384 dots | GOOJPRT PT-210 portable printer with QR support |
+| `CreateGP58N()` | 58mm | 384 dots | Gainscha GP-58N |
+| `CreateECPM80250()` | 80mm | 576 dots | EC Line EC-PM-80250 |
+| `CreateEpsonTMT20III()` / `CreateEpsonTMT88VI()` | 80mm | 576 dots | Epson TM-T20III / TM-T88VI (PC858, native QR, auto code-page switching) |
+| `CreateStarTSP100()` | 80mm | 576 dots | Star TSP100 (ESC/POS mode) |
+| `CreateBixolonSRP350III()` | 80mm | 576 dots | Bixolon SRP-350III |
+| `CreateXprinterXP58()` / `CreateXprinterXP80()` | 58mm / 80mm | 384 / 576 dots | Xprinter XP-58 / XP-80 |
+
+Use `profile.ProfileFromModel("tm-t88")` to resolve presets by (case-insensitive) model name; the executor and CLI apply this automatically from `profile.model`.
## 🎨 Visual Emulator
diff --git a/cmd/poster/parsing_test.go b/cmd/poster/parsing_test.go
index 7cbbae0..286228e 100644
--- a/cmd/poster/parsing_test.go
+++ b/cmd/poster/parsing_test.go
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
+ "flag"
"net"
"os"
"path/filepath"
@@ -359,3 +360,200 @@ func TestExecutePrint_TCP(t *testing.T) {
}
}
+func parseFlags(args []string) *Config {
+ origCommandLine := flag.CommandLine
+ origArgs := os.Args
+ defer func() {
+ flag.CommandLine = origCommandLine
+ os.Args = origArgs
+ }()
+
+ flag.CommandLine = flag.NewFlagSet(args[0], flag.ContinueOnError)
+ os.Args = args
+ return parseArgs()
+}
+
+func previewDocument(docPath, previewPath string) error {
+ return executePrint(&Config{
+ JSONFile: docPath,
+ PreviewPath: previewPath,
+ })
+}
+
+func printToFile(docPath, outputPath string) error {
+ return executePrint(&Config{
+ JSONFile: docPath,
+ ConnectionType: "file",
+ OutputFile: outputPath,
+ })
+}
+
+func TestParseFlags(t *testing.T) {
+ t.Run("flags with shorthand and options", func(t *testing.T) {
+ args := []string{
+ "poster",
+ "-f", "test.json",
+ "-p", "ThermalPrinter",
+ "-t", "network",
+ "-network", "192.168.1.50:9100",
+ "-o", "output.bin",
+ "-preview", "preview.png",
+ "--dry-run",
+ "--debug",
+ }
+ cfg := parseFlags(args)
+ if cfg.JSONFile != "test.json" {
+ t.Errorf("expected JSONFile 'test.json', got %q", cfg.JSONFile)
+ }
+ if cfg.PrinterName != "ThermalPrinter" {
+ t.Errorf("expected PrinterName 'ThermalPrinter', got %q", cfg.PrinterName)
+ }
+ if cfg.ConnectionType != "network" {
+ t.Errorf("expected ConnectionType 'network', got %q", cfg.ConnectionType)
+ }
+ if cfg.NetworkAddr != "192.168.1.50:9100" {
+ t.Errorf("expected NetworkAddr '192.168.1.50:9100', got %q", cfg.NetworkAddr)
+ }
+ if cfg.OutputFile != "output.bin" {
+ t.Errorf("expected OutputFile 'output.bin', got %q", cfg.OutputFile)
+ }
+ if cfg.PreviewPath != "preview.png" {
+ t.Errorf("expected PreviewPath 'preview.png', got %q", cfg.PreviewPath)
+ }
+ if !cfg.DryRun {
+ t.Error("expected DryRun true")
+ }
+ if !cfg.Debug {
+ t.Error("expected Debug true")
+ }
+ })
+
+ t.Run("positional args fallback", func(t *testing.T) {
+ args := []string{"poster", "positional.json", "PositionalPrinter"}
+ cfg := parseFlags(args)
+ if cfg.JSONFile != "positional.json" {
+ t.Errorf("expected JSONFile 'positional.json', got %q", cfg.JSONFile)
+ }
+ if cfg.PrinterName != "PositionalPrinter" {
+ t.Errorf("expected PrinterName 'PositionalPrinter', got %q", cfg.PrinterName)
+ }
+ })
+}
+
+func TestCreateProfile(t *testing.T) {
+ t.Run("preset model", func(t *testing.T) {
+ doc := &schema.Document{
+ Profile: schema.ProfileConfig{
+ Model: "TM-T88VI",
+ },
+ }
+ prof := createProfile(doc)
+ if prof == nil {
+ t.Fatal("expected non-nil profile")
+ }
+ if prof.Model != "TM-T88VI" {
+ t.Errorf("expected model TM-T88VI, got %s", prof.Model)
+ }
+ })
+
+ t.Run("58mm fallback profile", func(t *testing.T) {
+ doc := &schema.Document{
+ Profile: schema.ProfileConfig{
+ Model: "Unknown58",
+ PaperWidth: 58,
+ DPI: 203,
+ CodeTable: "PC850",
+ HasQR: true,
+ },
+ }
+ prof := createProfile(doc)
+ if prof == nil {
+ t.Fatal("expected non-nil profile")
+ }
+ if prof.PaperWidth != 58 {
+ t.Errorf("expected PaperWidth 58, got %v", prof.PaperWidth)
+ }
+ if prof.DPI != 203 {
+ t.Errorf("expected DPI 203, got %d", prof.DPI)
+ }
+ if !prof.HasQR {
+ t.Error("expected HasQR true")
+ }
+ })
+
+ t.Run("80mm fallback profile", func(t *testing.T) {
+ doc := &schema.Document{
+ Profile: schema.ProfileConfig{
+ Model: "Unknown80",
+ PaperWidth: 80,
+ },
+ }
+ prof := createProfile(doc)
+ if prof == nil {
+ t.Fatal("expected non-nil profile")
+ }
+ if prof.PaperWidth != 80 {
+ t.Errorf("expected PaperWidth 80, got %v", prof.PaperWidth)
+ }
+ })
+}
+
+func TestPreviewDocument(t *testing.T) {
+ tempDir := t.TempDir()
+ jsonPath := filepath.Join(tempDir, "preview_ticket.json")
+ if err := os.WriteFile(jsonPath, []byte(validTicketJSON), 0600); err != nil {
+ t.Fatalf("Failed to write ticket json: %v", err)
+ }
+
+ previewPath := filepath.Join(tempDir, "output_preview.png")
+ if err := previewDocument(jsonPath, previewPath); err != nil {
+ t.Fatalf("previewDocument failed: %v", err)
+ }
+
+ fi, err := os.Stat(previewPath)
+ if err != nil {
+ t.Fatalf("failed to stat preview png: %v", err)
+ }
+ if fi.Size() == 0 {
+ t.Error("expected non-empty preview file")
+ }
+
+ data, err := os.ReadFile(filepath.Clean(previewPath))
+ if err != nil {
+ t.Fatalf("failed to read preview png: %v", err)
+ }
+ if len(data) < 8 || string(data[:8]) != "\x89PNG\r\n\x1a\n" {
+ t.Errorf("preview file does not have valid PNG header")
+ }
+}
+
+func TestPrintToFile(t *testing.T) {
+ tempDir := t.TempDir()
+ jsonPath := filepath.Join(tempDir, "file_ticket.json")
+ if err := os.WriteFile(jsonPath, []byte(validTicketJSON), 0600); err != nil {
+ t.Fatalf("Failed to write ticket json: %v", err)
+ }
+
+ outPath := filepath.Join(tempDir, "output_receipt.bin")
+ if err := printToFile(jsonPath, outPath); err != nil {
+ t.Fatalf("printToFile failed: %v", err)
+ }
+
+ fi, err := os.Stat(outPath)
+ if err != nil {
+ t.Fatalf("failed to stat output bin: %v", err)
+ }
+ if fi.Size() == 0 {
+ t.Error("expected non-empty bin output file")
+ }
+
+ data, err := os.ReadFile(filepath.Clean(outPath))
+ if err != nil {
+ t.Fatalf("failed to read bin output: %v", err)
+ }
+ if !strings.Contains(string(data), "Receipt Header") {
+ t.Errorf("expected bin output to contain 'Receipt Header', got %q", string(data))
+ }
+}
+
+
diff --git a/cmd/poster/printing.go b/cmd/poster/printing.go
index 3dca4f4..4b159cd 100644
--- a/cmd/poster/printing.go
+++ b/cmd/poster/printing.go
@@ -97,7 +97,6 @@ func createConnection(config *Config) (connection.Connector, error) {
if config.SerialPort == "" {
return nil, fmt.Errorf("serial port required")
}
- // TODO: Implement when available in library
return nil, fmt.Errorf("serial connection not yet implemented")
case "file":
diff --git a/internal/load/loaders_test.go b/internal/load/loaders_test.go
new file mode 100644
index 0000000..60a8850
--- /dev/null
+++ b/internal/load/loaders_test.go
@@ -0,0 +1,175 @@
+package load_test
+
+import (
+ "bytes"
+ "encoding/base64"
+ "image"
+ "image/color"
+ "image/jpeg"
+ "image/png"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/adcondev/poster/internal/load"
+ "golang.org/x/image/bmp"
+)
+
+// createSampleImage returns a simple 8x8 RGBA test image.
+func createSampleImage() image.Image {
+ img := image.NewRGBA(image.Rect(0, 0, 8, 8))
+ for y := 0; y < 8; y++ {
+ for x := 0; x < 8; x++ {
+ img.Set(x, y, color.RGBA{R: 255, G: 0, B: 0, A: 255})
+ }
+ }
+ return img
+}
+
+func TestSecureFilepath(t *testing.T) {
+ tempDir := t.TempDir()
+
+ // Valid relative path
+ validRel := "sub/file.png"
+ abs, err := load.SecureFilepath(tempDir, validRel)
+ if err != nil {
+ t.Fatalf("SecureFilepath() unexpected error = %v", err)
+ }
+ expected := filepath.Join(tempDir, "sub", "file.png")
+ if abs != expected {
+ t.Errorf("SecureFilepath() = %q, want %q", abs, expected)
+ }
+
+ // Traversal attempt with ../
+ _, err = load.SecureFilepath(tempDir, "../escaped.png")
+ if err == nil {
+ t.Fatal("SecureFilepath() expected error for traversal path, got nil")
+ }
+
+ // Deep traversal attempt
+ _, err = load.SecureFilepath(tempDir, "a/b/../../../../escaped.png")
+ if err == nil {
+ t.Fatal("SecureFilepath() expected error for deep traversal path, got nil")
+ }
+}
+
+func TestImgFromFile_Formats(t *testing.T) {
+ tempDir := t.TempDir()
+ sample := createSampleImage()
+
+ formats := []struct {
+ ext string
+ encode func(f *os.File, img image.Image) error
+ }{
+ {
+ ext: "sample.png",
+ encode: func(f *os.File, img image.Image) error {
+ return png.Encode(f, img)
+ },
+ },
+ {
+ ext: "sample.jpg",
+ encode: func(f *os.File, img image.Image) error {
+ return jpeg.Encode(f, img, nil)
+ },
+ },
+ {
+ ext: "sample.bmp",
+ encode: func(f *os.File, img image.Image) error {
+ return bmp.Encode(f, img)
+ },
+ },
+ }
+
+ for _, tt := range formats {
+ t.Run(tt.ext, func(t *testing.T) {
+ path := filepath.Join(tempDir, tt.ext)
+ f, err := os.Create(filepath.Clean(path))
+ if err != nil {
+ t.Fatalf("os.Create() error = %v", err)
+ }
+ if err := tt.encode(f, sample); err != nil {
+ _ = f.Close()
+ t.Fatalf("encode error = %v", err)
+ }
+ _ = f.Close()
+
+ img, err := load.ImgFromFile(tempDir, tt.ext)
+ if err != nil {
+ t.Fatalf("ImgFromFile(%s) error = %v", tt.ext, err)
+ }
+ if img.Bounds().Dx() != 8 || img.Bounds().Dy() != 8 {
+ t.Errorf("ImgFromFile(%s) dimensions = %dx%d, want 8x8",
+ tt.ext, img.Bounds().Dx(), img.Bounds().Dy())
+ }
+ })
+ }
+}
+
+func TestImgFromFile_Errors(t *testing.T) {
+ tempDir := t.TempDir()
+
+ // Path traversal error
+ _, err := load.ImgFromFile(tempDir, "../forbidden.png")
+ if err == nil {
+ t.Fatal("ImgFromFile() expected error on path traversal, got nil")
+ }
+
+ // Non-existent file
+ _, err = load.ImgFromFile(tempDir, "non_existent.png")
+ if err == nil {
+ t.Fatal("ImgFromFile() expected error for non-existent file, got nil")
+ }
+
+ // Corrupt / non-image file
+ corruptPath := filepath.Join(tempDir, "corrupt.png")
+ if err := os.WriteFile(corruptPath, []byte("not an image file"), 0600); err != nil {
+ t.Fatalf("os.WriteFile() error = %v", err)
+ }
+ _, err = load.ImgFromFile(tempDir, "corrupt.png")
+ if err == nil {
+ t.Fatal("ImgFromFile() expected decode error for corrupted image, got nil")
+ }
+}
+
+func TestImgFromBase64_Success(t *testing.T) {
+ sample := createSampleImage()
+
+ var buf bytes.Buffer
+ if err := png.Encode(&buf, sample); err != nil {
+ t.Fatalf("png.Encode() error = %v", err)
+ }
+ encoded := base64.StdEncoding.EncodeToString(buf.Bytes())
+
+ img, format, err := load.ImgFromBase64(encoded)
+ if err != nil {
+ t.Fatalf("ImgFromBase64() error = %v", err)
+ }
+ if format != "png" {
+ t.Errorf("ImgFromBase64() format = %q, want \"png\"", format)
+ }
+ if img.Bounds().Dx() != 8 || img.Bounds().Dy() != 8 {
+ t.Errorf("ImgFromBase64() dimensions = %dx%d, want 8x8", img.Bounds().Dx(), img.Bounds().Dy())
+ }
+}
+
+func TestImgFromBase64_Errors(t *testing.T) {
+ // Invalid base64 encoding
+ _, _, err := load.ImgFromBase64("!!!not-valid-base64###")
+ if err == nil {
+ t.Fatal("ImgFromBase64() expected error for invalid base64, got nil")
+ }
+
+ // Data URI prefix is rejected by raw base64 decoder
+ _, _, err = load.ImgFromBase64("data:image/png;base64,invalid")
+ if err == nil {
+ t.Fatal("ImgFromBase64() expected error for data URI prefix with raw decoder, got nil")
+ }
+
+ // Valid base64 but corrupt image payload
+ corruptBase64 := base64.StdEncoding.EncodeToString([]byte("hello world"))
+ _, _, err = load.ImgFromBase64(corruptBase64)
+ if err == nil {
+ t.Fatal("ImgFromBase64() expected image decode error for invalid payload, got nil")
+ }
+}
diff --git a/internal/testutils/assertions_test.go b/internal/testutils/assertions_test.go
new file mode 100644
index 0000000..5c4f1e0
--- /dev/null
+++ b/internal/testutils/assertions_test.go
@@ -0,0 +1,269 @@
+package testutils
+
+import (
+ "errors"
+ "testing"
+)
+
+func TestAssertions_SuccessCases(t *testing.T) {
+ // AssertBytes
+ AssertBytes(t, []byte{0x01, 0x02}, []byte{0x01, 0x02})
+
+ // AssertError
+ AssertError(t, nil, nil)
+ customErr := errors.New("custom error")
+ AssertError(t, customErr, customErr)
+
+ // AssertErrorOccurred
+ if !AssertErrorOccurred(t, customErr, true, "testMethod") {
+ t.Error("AssertErrorOccurred should return true when error matches expectation")
+ }
+ if !AssertErrorOccurred(t, nil, false, "testMethod") {
+ t.Error("AssertErrorOccurred should return true when no-error matches expectation")
+ }
+
+ // AssertContains
+ AssertContains(t, []byte("abcdef"), []byte("cde"))
+
+ // AssertNotEmpty
+ AssertNotEmpty(t, []byte{0x01}, "test data")
+
+ // AssertLength
+ AssertLength(t, []byte{1, 2, 3}, 3)
+
+ // AssertHasPrefix
+ AssertHasPrefix(t, []byte("prefix_data"), []byte("prefix"))
+
+ // AssertNumeric
+ AssertNumeric(t, []byte("1234567890"))
+
+ // AssertUppercase
+ AssertUppercase(t, []byte("ABCXYZ123"))
+
+ // AssertPrintableASCII
+ AssertPrintableASCII(t, []byte("Hello, World! 123"))
+
+ // AssertHasNullTerminator
+ AssertHasNullTerminator(t, []byte{0x01, 0x02, 0x00})
+
+ // AssertEvenLength
+ AssertEvenLength(t, []byte{0x01, 0x02, 0x03, 0x04})
+
+ // AssertContainsOnly
+ AssertContainsOnly(t, []byte("abca"), []byte("abc"))
+
+ // AssertValidLength
+ AssertValidLength(t, []byte("test"), 2, 6)
+}
+
+func TestAssertions_FailureCases(t *testing.T) {
+ mockT := new(testing.T)
+
+ // AssertBytes failures
+ AssertBytes(mockT, []byte{1}, []byte{2})
+ AssertBytes(mockT, []byte{1}, []byte{2}, "custom msg")
+ AssertBytes(mockT, []byte{1}, []byte{2}, "formatted %s", "msg")
+
+ // AssertError failures
+ AssertError(mockT, errors.New("unexpected"), nil)
+ AssertError(mockT, errors.New("err1"), errors.New("err2"))
+
+ // AssertErrorOccurred failure
+ _ = AssertErrorOccurred(mockT, errors.New("err"), false, "method")
+ _ = AssertErrorOccurred(mockT, nil, true, "method")
+
+ // AssertContains failure
+ AssertContains(mockT, []byte("abc"), []byte("xyz"))
+ AssertContains(mockT, []byte("abc"), []byte("xyz"), "not found")
+ AssertContains(mockT, []byte("abc"), []byte("xyz"), "not found %s", "needle")
+
+ // AssertNotEmpty failure
+ AssertNotEmpty(mockT, nil, "empty")
+
+ // AssertLength failure
+ AssertLength(mockT, []byte{1}, 3)
+ AssertLength(mockT, []byte{1}, 3, "wrong len")
+ AssertLength(mockT, []byte{1}, 3, "wrong len %d", 3)
+
+ // AssertHasPrefix failure
+ AssertHasPrefix(mockT, []byte("abc"), []byte("xyz"))
+ AssertHasPrefix(mockT, []byte("abc"), []byte("xyz"), "no prefix")
+ AssertHasPrefix(mockT, []byte("abc"), []byte("xyz"), "no prefix %s", "xyz")
+
+ // AssertNumeric failure
+ AssertNumeric(mockT, []byte("123a45"))
+
+ // AssertUppercase failure
+ AssertUppercase(mockT, []byte("ABCdEF"))
+
+ // AssertPrintableASCII failure
+ AssertPrintableASCII(mockT, []byte{0x01, 0x02})
+
+ // AssertHasNullTerminator failure
+ AssertHasNullTerminator(mockT, []byte{1, 2})
+ AssertHasNullTerminator(mockT, nil)
+
+ // AssertEvenLength failure
+ AssertEvenLength(mockT, []byte{1, 2, 3})
+
+ // AssertContainsOnly failure
+ AssertContainsOnly(mockT, []byte("abcd"), []byte("abc"))
+
+ // AssertValidLength failure
+ AssertValidLength(mockT, []byte("toolong"), 1, 3)
+
+ if !mockT.Failed() {
+ t.Error("expected mockT to be marked failed")
+ }
+}
+
+func TestFormatMessage(t *testing.T) {
+ // Default message with no args
+ msg1 := formatMessage("default")
+ if msg1 != "default" {
+ t.Errorf("formatMessage() = %q, want \"default\"", msg1)
+ }
+
+ // Single argument message
+ msg2 := formatMessage("default", "custom message")
+ if msg2 != "custom message" {
+ t.Errorf("formatMessage() = %q, want \"custom message\"", msg2)
+ }
+
+ // Formatted message with multiple arguments
+ msg3 := formatMessage("default", "code %d: %s", 404, "not found")
+ if msg3 != "code 404: not found" {
+ t.Errorf("formatMessage() = %q, want \"code 404: not found\"", msg3)
+ }
+}
+
+func TestByteHelpers(t *testing.T) {
+ // RepeatByte
+ repeated := RepeatByte(5, 0xAA)
+ if len(repeated) != 5 {
+ t.Fatalf("RepeatByte length = %d, want 5", len(repeated))
+ }
+ for i, b := range repeated {
+ if b != 0xAA {
+ t.Errorf("repeated[%d] = %#x, want 0xAA", i, b)
+ }
+ }
+
+ // GenerateString
+ str := GenerateString(4, 'Z')
+ if str != "ZZZZ" {
+ t.Errorf("GenerateString = %q, want \"ZZZZ\"", str)
+ }
+
+ // BuildCommand
+ cmd := BuildCommand(0x1B, '@', 0x01, 0x02)
+ wantCmd := []byte{0x1B, '@', 0x01, 0x02}
+ AssertBytes(t, cmd, wantCmd)
+
+ // BufferBuilder
+ builder := &BufferBuilder{}
+ builder.Append([]byte{0x10, 0x20}).Append([]byte{0x30, 0x40})
+ AssertBytes(t, builder.GetBuffer(), []byte{0x10, 0x20, 0x30, 0x40})
+}
+
+func TestFakeCapabilityBase(t *testing.T) {
+ fc := &FakeCapabilityBase{
+ Tracker: &MockTracker{CallCount: make(map[string]int)},
+ StateMap: make(map[string]interface{}),
+ }
+
+ fc.AppendCommand([]byte{0x1B, '@'}, "Initialize")
+ AssertBytes(t, fc.GetBuffer(), []byte{0x1B, '@'})
+ if count := fc.Tracker.GetCallCount("Initialize"); count != 1 {
+ t.Errorf("GetCallCount = %d, want 1", count)
+ }
+
+ fc.SetState("align", "center")
+ state := fc.GetState()
+ if state["align"] != "center" {
+ t.Errorf("GetState[\"align\"] = %v, want \"center\"", state["align"])
+ }
+
+ fc.Reset()
+ if len(fc.GetBuffer()) != 0 {
+ t.Errorf("GetBuffer after Reset = %v, want empty", fc.GetBuffer())
+ }
+ if len(fc.GetState()) != 0 {
+ t.Errorf("GetState after Reset = %v, want empty", fc.GetState())
+ }
+ if fc.Tracker.GetCallCount("Initialize") != 0 {
+ t.Errorf("Tracker call count after Reset = %d, want 0", fc.Tracker.GetCallCount("Initialize"))
+ }
+}
+
+func TestMockTracker(t *testing.T) {
+ mt := &MockTracker{
+ CallCount: make(map[string]int),
+ }
+
+ mt.Track("Print")
+ mt.Track("Print")
+ mt.Track("Feed")
+
+ if count := mt.GetCallCount("Print"); count != 2 {
+ t.Errorf("GetCallCount(Print) = %d, want 2", count)
+ }
+ if count := mt.GetCallCount("Feed"); count != 1 {
+ t.Errorf("GetCallCount(Feed) = %d, want 1", count)
+ }
+ if mt.LastCommand != "Feed" {
+ t.Errorf("LastCommand = %q, want \"Feed\"", mt.LastCommand)
+ }
+ if len(mt.CallHistory) != 3 {
+ t.Errorf("CallHistory length = %d, want 3", len(mt.CallHistory))
+ }
+
+ mt.Reset()
+ if mt.GetCallCount("Print") != 0 {
+ t.Errorf("GetCallCount after reset = %d, want 0", mt.GetCallCount("Print"))
+ }
+ if len(mt.CallHistory) != 0 {
+ t.Errorf("CallHistory length after reset = %d, want 0", len(mt.CallHistory))
+ }
+ if mt.LastCommand != "" {
+ t.Errorf("LastCommand after reset = %q, want empty", mt.LastCommand)
+ }
+}
+
+func TestMockConnector(t *testing.T) {
+ // Default methods
+ mc := &MockConnector{}
+
+ n, err := mc.Write([]byte("hello"))
+ if err != nil || n != 5 {
+ t.Errorf("Write() = (%d, %v), want (5, nil)", n, err)
+ }
+
+ if err := mc.Close(); err != nil {
+ t.Errorf("Close() error = %v, want nil", err)
+ }
+
+ rn, rerr := mc.Read([]byte{0})
+ if rerr != nil || rn != 0 {
+ t.Errorf("Read() = (%d, %v), want (0, nil)", rn, rerr)
+ }
+
+ // Custom WriteFunc and CloseFunc error injection
+ injectedErr := errors.New("injected connection error")
+ mc.WriteFunc = func(_ []byte) (int, error) {
+ return 0, injectedErr
+ }
+ mc.CloseFunc = func() error {
+ return injectedErr
+ }
+
+ _, err = mc.Write([]byte("data"))
+ if !errors.Is(err, injectedErr) {
+ t.Errorf("Write() error = %v, want injectedErr", err)
+ }
+
+ err = mc.Close()
+ if !errors.Is(err, injectedErr) {
+ t.Errorf("Close() error = %v, want injectedErr", err)
+ }
+}
diff --git a/pkg/commands/barcode/barcode_commands.go b/pkg/commands/barcode/barcode_commands.go
index 7c04b5b..edd8dee 100644
--- a/pkg/commands/barcode/barcode_commands.go
+++ b/pkg/commands/barcode/barcode_commands.go
@@ -233,8 +233,6 @@ func (c *Commands) PrintBarcode(symbology Symbology, data []byte) ([]byte, error
return nil, ErrDataTooShort
}
- // TODO: Check if builders are better in composer package
-
// Select construction based on symbology
if symbology <= CODABAR {
// Function A (NUL-terminated)
diff --git a/pkg/commands/bitimage/bitimage.go b/pkg/commands/bitimage/bitimage.go
index f5a3a5b..628062b 100644
--- a/pkg/commands/bitimage/bitimage.go
+++ b/pkg/commands/bitimage/bitimage.go
@@ -61,8 +61,6 @@ type NVBitImageData struct {
Data []byte // Bit image data in column format
}
-// TODO: Check unused constants
-
// Constants for image size limits
const (
// MaxHorizontalDots represents maximum horizontal dots for bit images
@@ -185,8 +183,6 @@ func (c *Commands) DownloadGraphicsCmds() DownloadGraphicsCapability {
// Helper Functions
// ============================================================================
-// TODO: Check if is better to move it to composer package
-
// CalculateDataLength calculates the expected data length for bit image data
func CalculateDataLength(mode Mode, width uint16) int {
switch mode {
@@ -199,8 +195,6 @@ func CalculateDataLength(mode Mode, width uint16) int {
}
}
-// TODO: Check if these helper functions are used, remove if not
-
// CalculateRasterDataLength calculates expected data length for raster format
func CalculateRasterDataLength(widthBytes, heightDots uint16) int {
return int(widthBytes) * int(heightDots)
diff --git a/pkg/commands/bitimage/bitimage_test.go b/pkg/commands/bitimage/bitimage_test.go
index a78b105..3548260 100644
--- a/pkg/commands/bitimage/bitimage_test.go
+++ b/pkg/commands/bitimage/bitimage_test.go
@@ -424,3 +424,189 @@ func TestValidateRasterImageDimensions(t *testing.T) {
})
}
}
+
+func TestCommands_SubCapabilities(t *testing.T) {
+ c := bitimage.NewCommands()
+ if c.GraphicsCmds() == nil {
+ t.Error("GraphicsCmds() returned nil")
+ }
+ if c.NVGraphicsCmds() == nil {
+ t.Error("NVGraphicsCmds() returned nil")
+ }
+ if c.DownloadGraphicsCmds() == nil {
+ t.Error("DownloadGraphicsCmds() returned nil")
+ }
+}
+
+func TestHelperFunctions(t *testing.T) {
+ if got := bitimage.CalculateDataLength(bitimage.Mode(99), 10); got != 0 {
+ t.Errorf("CalculateDataLength(invalid) = %d, want 0", got)
+ }
+ if got := bitimage.CalculateRasterDataLength(10, 20); got != 200 {
+ t.Errorf("CalculateRasterDataLength(10, 20) = %d, want 200", got)
+ }
+ if got := bitimage.CalculateColumnDataLength(15, 4); got != 60 {
+ t.Errorf("CalculateColumnDataLength(15, 4) = %d, want 60", got)
+ }
+}
+
+func TestCommands_PrintNVBitImage(t *testing.T) {
+ c := bitimage.NewCommands()
+
+ // Valid
+ cmd, err := c.PrintNVBitImage(1, bitimage.Normal)
+ if err != nil {
+ t.Fatalf("PrintNVBitImage() error = %v", err)
+ }
+ want := []byte{shared.FS, 'p', 1, 0}
+ testutils.AssertBytes(t, cmd, want)
+
+ // Invalid n
+ if _, err := c.PrintNVBitImage(0, bitimage.Normal); err == nil {
+ t.Error("PrintNVBitImage(0) expected error, got nil")
+ }
+
+ // Invalid mode
+ if _, err := c.PrintNVBitImage(1, bitimage.PrintMode(99)); err == nil {
+ t.Error("PrintNVBitImage(invalid mode) expected error, got nil")
+ }
+}
+
+func TestCommands_DefineNVBitImage(t *testing.T) {
+ c := bitimage.NewCommands()
+
+ imgs := []bitimage.NVBitImageData{
+ {Width: 1, Height: 1, Data: make([]byte, 8)},
+ }
+
+ // Valid
+ cmd, err := c.DefineNVBitImage(1, imgs)
+ if err != nil {
+ t.Fatalf("DefineNVBitImage() error = %v", err)
+ }
+ if len(cmd) == 0 {
+ t.Fatal("DefineNVBitImage() returned empty bytes")
+ }
+
+ // Invalid count 0
+ if _, err := c.DefineNVBitImage(0, imgs); err == nil {
+ t.Error("DefineNVBitImage(0) expected error, got nil")
+ }
+
+ // Count mismatch
+ if _, err := c.DefineNVBitImage(2, imgs); err == nil {
+ t.Error("DefineNVBitImage(count mismatch) expected error, got nil")
+ }
+
+ // Invalid dimensions
+ badDims := []bitimage.NVBitImageData{
+ {Width: 0, Height: 1, Data: make([]byte, 8)},
+ }
+ if _, err := c.DefineNVBitImage(1, badDims); err == nil {
+ t.Error("DefineNVBitImage(bad dims) expected error, got nil")
+ }
+
+ // Data length mismatch
+ badData := []bitimage.NVBitImageData{
+ {Width: 1, Height: 1, Data: make([]byte, 4)},
+ }
+ if _, err := c.DefineNVBitImage(1, badData); err == nil {
+ t.Error("DefineNVBitImage(bad data length) expected error, got nil")
+ }
+}
+
+func TestCommands_DefineDownloadedBitImage(t *testing.T) {
+ c := bitimage.NewCommands()
+
+ // Valid
+ cmd, err := c.DefineDownloadedBitImage(1, 1, make([]byte, 8))
+ if err != nil {
+ t.Fatalf("DefineDownloadedBitImage() error = %v", err)
+ }
+ if len(cmd) == 0 {
+ t.Fatal("DefineDownloadedBitImage() returned empty bytes")
+ }
+
+ // Invalid dimensions
+ if _, err := c.DefineDownloadedBitImage(0, 1, make([]byte, 8)); err == nil {
+ t.Error("DefineDownloadedBitImage(0, 1) expected error, got nil")
+ }
+
+ // Data length mismatch
+ if _, err := c.DefineDownloadedBitImage(1, 1, make([]byte, 4)); err == nil {
+ t.Error("DefineDownloadedBitImage(mismatched data) expected error, got nil")
+ }
+}
+
+func TestCommands_PrintDownloadedBitImage(t *testing.T) {
+ c := bitimage.NewCommands()
+
+ // Valid
+ cmd, err := c.PrintDownloadedBitImage(bitimage.Normal)
+ if err != nil {
+ t.Fatalf("PrintDownloadedBitImage() error = %v", err)
+ }
+ want := []byte{shared.GS, '/', 0}
+ testutils.AssertBytes(t, cmd, want)
+
+ // Invalid mode
+ if _, err := c.PrintDownloadedBitImage(bitimage.PrintMode(99)); err == nil {
+ t.Error("PrintDownloadedBitImage(invalid mode) expected error, got nil")
+ }
+}
+
+func TestCommands_PrintVariableVerticalSizeBitImage(t *testing.T) {
+ c := bitimage.NewCommands()
+
+ // Valid
+ cmd, err := c.PrintVariableVerticalSizeBitImage(bitimage.Normal, 2, 2, make([]byte, 4))
+ if err != nil {
+ t.Fatalf("PrintVariableVerticalSizeBitImage() error = %v", err)
+ }
+ if len(cmd) == 0 {
+ t.Fatal("PrintVariableVerticalSizeBitImage() returned empty bytes")
+ }
+
+ // Invalid mode
+ if _, err := c.PrintVariableVerticalSizeBitImage(bitimage.PrintMode(99), 2, 2, make([]byte, 4)); err == nil {
+ t.Error("PrintVariableVerticalSizeBitImage(invalid mode) expected error, got nil")
+ }
+
+ // Invalid dimensions
+ if _, err := c.PrintVariableVerticalSizeBitImage(bitimage.Normal, 0, 2, make([]byte, 4)); err == nil {
+ t.Error("PrintVariableVerticalSizeBitImage(0 width) expected error, got nil")
+ }
+
+ // Data length mismatch
+ if _, err := c.PrintVariableVerticalSizeBitImage(bitimage.Normal, 2, 2, make([]byte, 2)); err == nil {
+ t.Error("PrintVariableVerticalSizeBitImage(mismatched length) expected error, got nil")
+ }
+}
+
+func TestCommands_PrintRasterBitImage(t *testing.T) {
+ c := bitimage.NewCommands()
+
+ // Valid
+ cmd, err := c.PrintRasterBitImage(bitimage.Normal, 2, 2, make([]byte, 4))
+ if err != nil {
+ t.Fatalf("PrintRasterBitImage() error = %v", err)
+ }
+ if len(cmd) == 0 {
+ t.Fatal("PrintRasterBitImage() returned empty bytes")
+ }
+
+ // Invalid mode
+ if _, err := c.PrintRasterBitImage(bitimage.PrintMode(99), 2, 2, make([]byte, 4)); err == nil {
+ t.Error("PrintRasterBitImage(invalid mode) expected error, got nil")
+ }
+
+ // Invalid dimensions
+ if _, err := c.PrintRasterBitImage(bitimage.Normal, 0, 2, make([]byte, 4)); err == nil {
+ t.Error("PrintRasterBitImage(0 width) expected error, got nil")
+ }
+
+ // Data length mismatch
+ if _, err := c.PrintRasterBitImage(bitimage.Normal, 2, 2, make([]byte, 2)); err == nil {
+ t.Error("PrintRasterBitImage(mismatched length) expected error, got nil")
+ }
+}
diff --git a/pkg/commands/bitimage/download_graphics.go b/pkg/commands/bitimage/download_graphics.go
index 4d264d7..d1c75ed 100644
--- a/pkg/commands/bitimage/download_graphics.go
+++ b/pkg/commands/bitimage/download_graphics.go
@@ -48,8 +48,6 @@ const (
// Error Definitions
// ============================================================================
-// TODO: refine error definitions
-
// Error variables
var (
// ErrInvalidDLFunctionCode indicates an invalid download function code
@@ -101,8 +99,6 @@ func NewDownloadGraphicsCommands() *DownloadGraphicsCommands {
// Helper Functions
// ============================================================================
-// TODO: Check if better move them to composer package
-
// calculateDLRasterDataSize calculates the data size for download raster format graphics
func calculateDLRasterDataSize(width, height uint16) int {
widthBytes := (int(width) + 7) / 8
diff --git a/pkg/commands/bitimage/graphics.go b/pkg/commands/bitimage/graphics.go
index fb5b1a7..629bf31 100644
--- a/pkg/commands/bitimage/graphics.go
+++ b/pkg/commands/bitimage/graphics.go
@@ -161,8 +161,6 @@ func NewGraphicsCommands() *GraphicsCommands {
// Helper Functions
// ============================================================================
-// TODO: Check if is better to have them in composer package
-
// calculateRasterDataSize calculates the data size for raster format graphics
func calculateRasterDataSize(width, height uint16) int {
widthBytes := (int(width) + 7) / 8
diff --git a/pkg/commands/bitimage/nv_graphics.go b/pkg/commands/bitimage/nv_graphics.go
index 9e3ffa4..aed3a6c 100644
--- a/pkg/commands/bitimage/nv_graphics.go
+++ b/pkg/commands/bitimage/nv_graphics.go
@@ -109,8 +109,6 @@ func NewNVGraphicsCommands() *NvGraphicsCommands {
// Helper Functions
// ============================================================================
-// TODO: Check if is better to have them in composer package
-
// calculateNVRasterDataSize calculates the data size for NV raster format graphics
func calculateNVRasterDataSize(width, height uint16) int {
widthBytes := (int(width) + 7) / 8
diff --git a/pkg/commands/character/character.go b/pkg/commands/character/character.go
index ed0a1ac..a81c9b6 100644
--- a/pkg/commands/character/character.go
+++ b/pkg/commands/character/character.go
@@ -490,8 +490,6 @@ func (c *Commands) UserDefinedCmds() UserDefinedCapability {
// Helper Functions
// ============================================================================
-// TODO: Check if is better to have them defined in composer package
-
// NewSize creates a Size value for character width and height magnification.
//
// Format:
diff --git a/pkg/commands/character/code_conversion_test.go b/pkg/commands/character/code_conversion_test.go
index ece553f..9c9f60c 100644
--- a/pkg/commands/character/code_conversion_test.go
+++ b/pkg/commands/character/code_conversion_test.go
@@ -10,11 +10,6 @@ import (
"github.com/adcondev/poster/pkg/commands/shared"
)
-// TODO: Swap out hardcoded bytes and values with constants from the character package
-// TODO: Swap boilerplate assertion code with calls to utils/testutils/assertions.go
-// TODO: Define prefix bytes for commands to reduce repetition
-// TODO: Swap for specific type, the convert to byte. This simulates real usage better.
-
// ============================================================================
// Code Conversion Commands Tests
// ============================================================================
diff --git a/pkg/commands/printposition/print_position.go b/pkg/commands/printposition/print_position.go
index 2153f76..43580ea 100644
--- a/pkg/commands/printposition/print_position.go
+++ b/pkg/commands/printposition/print_position.go
@@ -68,7 +68,6 @@ const (
PrintASCII BeginLine = '1'
)
-// TODO: Check if better to be var and configurable from profile
// Tab position limits
const (
MaxTabPositions = 32
diff --git a/pkg/commands/printposition/print_position_test.go b/pkg/commands/printposition/print_position_test.go
index e16c43b..7823f3b 100644
--- a/pkg/commands/printposition/print_position_test.go
+++ b/pkg/commands/printposition/print_position_test.go
@@ -148,7 +148,6 @@ func TestCommands_SetHorizontalTabPositions(t *testing.T) {
}
return tabs
}(),
- // FIXME: change anonymous func to utils helpers
want: func() []byte {
cmd := []byte{shared.ESC, 'D'}
for i := 1; i <= 32; i++ {
@@ -161,7 +160,6 @@ func TestCommands_SetHorizontalTabPositions(t *testing.T) {
},
{
name: "too many tabs",
- // FIXME: change anonymous func to utils helpers
positions: func() []byte {
tabs := make([]byte, 33)
for i := range tabs {
diff --git a/pkg/commands/qrcode/qr_code.go b/pkg/commands/qrcode/qr_code.go
index 1cebe02..51396c9 100644
--- a/pkg/commands/qrcode/qr_code.go
+++ b/pkg/commands/qrcode/qr_code.go
@@ -115,8 +115,6 @@ func NewCommands() *Commands {
// Helper Functions
// ============================================================================
-// TODO: Check if it's better to move them to composer package or removed
-
// IsNumericData checks if data can be encoded in Numeric mode
func IsNumericData(data []byte) bool {
for _, b := range data {
diff --git a/pkg/commands/shared/shared_test.go b/pkg/commands/shared/shared_test.go
new file mode 100644
index 0000000..60d314f
--- /dev/null
+++ b/pkg/commands/shared/shared_test.go
@@ -0,0 +1,57 @@
+package shared_test
+
+import (
+ "testing"
+
+ "github.com/adcondev/poster/pkg/commands/shared"
+)
+
+func TestToLittleEndian32(t *testing.T) {
+ tests := []struct {
+ number uint32
+ wantL byte
+ wantH byte
+ wantHH byte
+ wantHHH byte
+ }{
+ {0, 0x00, 0x00, 0x00, 0x00},
+ {1, 0x01, 0x00, 0x00, 0x00},
+ {0x12345678, 0x78, 0x56, 0x34, 0x12},
+ {0xFFFFFFFF, 0xFF, 0xFF, 0xFF, 0xFF},
+ }
+
+ for _, tt := range tests {
+ nL, nH, nHH, nHHH := shared.ToLittleEndian32(tt.number)
+ if nL != tt.wantL || nH != tt.wantH || nHH != tt.wantHH || nHHH != tt.wantHHH {
+ t.Errorf("ToLittleEndian32(0x%x) = (%#x, %#x, %#x, %#x); want (%#x, %#x, %#x, %#x)",
+ tt.number, nL, nH, nHH, nHHH, tt.wantL, tt.wantH, tt.wantHH, tt.wantHHH)
+ }
+ }
+}
+
+func TestSharedConstants(t *testing.T) {
+ if shared.SP != 0x20 {
+ t.Errorf("shared.SP = %#x, want 0x20", shared.SP)
+ }
+ if shared.FS != 0x1C {
+ t.Errorf("shared.FS = %#x, want 0x1C", shared.FS)
+ }
+ if shared.NUL != 0x00 {
+ t.Errorf("shared.NUL = %#x, want 0x00", shared.NUL)
+ }
+ if shared.ESC != 0x1B {
+ t.Errorf("shared.ESC = %#x, want 0x1B", shared.ESC)
+ }
+ if shared.GS != 0x1D {
+ t.Errorf("shared.GS = %#x, want 0x1D", shared.GS)
+ }
+ if shared.HT != 0x09 {
+ t.Errorf("shared.HT = %#x, want 0x09", shared.HT)
+ }
+ if shared.Dpl80mm203dpi != 576 {
+ t.Errorf("shared.Dpl80mm203dpi = %d, want 576", shared.Dpl80mm203dpi)
+ }
+ if shared.Dpl58mm203dpi != 384 {
+ t.Errorf("shared.Dpl58mm203dpi = %d, want 384", shared.Dpl58mm203dpi)
+ }
+}
diff --git a/pkg/composer/escpos_composer.go b/pkg/composer/escpos_composer.go
index 3b944da..c7ef51f 100644
--- a/pkg/composer/escpos_composer.go
+++ b/pkg/composer/escpos_composer.go
@@ -28,22 +28,6 @@ type EscposProtocol struct {
Print print.Capability
PrintPosition printposition.Capability
QRCode qrcode.Capability
- // TODO: Implement other capabilities
- // PrintingPaper printingpaper.Capability
- // PaperSensor papersensor.Capability
- // PanelButton panelbutton.Capability
- // Status status.Capability
- // MacroFunctions macrofunctions.Capability
- // Kanji kanji.Capability
- // Miscellaneous miscellaneous.Capability
- // Customize customize.Capability
- // CounterPrinting counterprinting.Capability
- // PDF417 pdf417.Capability
- // MaxiCode maxicode.Capability
- // DataBar databar.Capability
- // CompositeSym compositesym.Capability
- // AztecCode azteccode.Capability
- // DataMatrix datamatrix.Capability
}
// NewEscpos creates a new instance of the ESC/POS protocol
@@ -60,8 +44,6 @@ func NewEscpos() *EscposProtocol {
}
}
-// TODO: Implement other methods to access capabilities related to initialization and state management (miscellaneous)
-
// InitializePrinter provides a reset of the printer to its power-on state for RAM settings.
//
// Format:
diff --git a/pkg/composer/escpos_composer_test.go b/pkg/composer/escpos_composer_test.go
index cddfc8e..aed6309 100644
--- a/pkg/composer/escpos_composer_test.go
+++ b/pkg/composer/escpos_composer_test.go
@@ -9,6 +9,8 @@ import (
"github.com/stretchr/testify/require"
"github.com/adcondev/poster/pkg/commands/barcode"
+ "github.com/adcondev/poster/pkg/commands/character"
+ "github.com/adcondev/poster/pkg/commands/printposition"
"github.com/adcondev/poster/pkg/commands/shared"
"github.com/adcondev/poster/pkg/graphics"
)
@@ -319,3 +321,116 @@ func TestGenerateBarcode(t *testing.T) {
})
}
}
+
+func TestEscposProtocol_InitializePrinter(t *testing.T) {
+ c := NewEscpos()
+ require.NotNil(t, c)
+ assert.Equal(t, []byte{shared.ESC, '@'}, c.InitializePrinter())
+}
+
+func TestEscposProtocol_MarginsAndWidth(t *testing.T) {
+ c := NewEscpos()
+
+ marginCmd := c.LeftMargin(16)
+ expectedMargin := []byte{shared.GS, 'L', 16, 0}
+ assert.Equal(t, expectedMargin, marginCmd)
+
+ widthCmd := c.PrintWidth(384)
+ expectedWidth := []byte{shared.GS, 'W', byte(384 & 0xFF), byte(384 >> 8)}
+ assert.Equal(t, expectedWidth, widthCmd)
+}
+
+func TestEscposProtocol_Alignment(t *testing.T) {
+ c := NewEscpos()
+
+ t.Run("SetAlign valid", func(t *testing.T) {
+ cmd, err := c.SetAlign(printposition.Center)
+ require.NoError(t, err)
+ assert.Equal(t, []byte{shared.ESC, 'a', byte(printposition.Center)}, cmd)
+ })
+
+ t.Run("SetAlign invalid", func(t *testing.T) {
+ cmd, err := c.SetAlign(printposition.Justification(99))
+ require.Error(t, err)
+ assert.Nil(t, cmd)
+ })
+
+ t.Run("LeftAlign", func(t *testing.T) {
+ assert.Equal(t, []byte{shared.ESC, 'a', byte(printposition.Left)}, c.LeftAlign())
+ })
+
+ t.Run("CenterAlign", func(t *testing.T) {
+ assert.Equal(t, []byte{shared.ESC, 'a', byte(printposition.Center)}, c.CenterAlign())
+ })
+
+ t.Run("RightAlign", func(t *testing.T) {
+ assert.Equal(t, []byte{shared.ESC, 'a', byte(printposition.Right)}, c.RightAlign())
+ })
+}
+
+func TestEscposProtocol_TextStyling(t *testing.T) {
+ c := NewEscpos()
+
+ assert.Equal(t, []byte{shared.ESC, 'E', 1}, c.EnableBold())
+ assert.Equal(t, []byte{shared.ESC, 'E', 0}, c.DisableBold())
+
+ assert.Equal(t, []byte{shared.ESC, '-', 1}, c.OneDotUnderline())
+ assert.Equal(t, []byte{shared.ESC, '-', 2}, c.TwoDotUnderline())
+ assert.Equal(t, []byte{shared.ESC, '-', 0}, c.DisableUnderline())
+
+ assert.Equal(t, []byte{shared.GS, 'B', 1}, c.EnableReverseMode())
+ assert.Equal(t, []byte{shared.GS, 'B', 0}, c.DisableReverseMode())
+
+ assert.Equal(t, []byte{shared.ESC, 'M', byte(character.FontA)}, c.SetFontA())
+ assert.Equal(t, []byte{shared.ESC, 'M', byte(character.FontB)}, c.SetFontB())
+}
+
+func TestEscposProtocol_TextSizing(t *testing.T) {
+ c := NewEscpos()
+
+ assert.Equal(t, []byte{shared.GS, '!', 0x00}, c.SingleSizeText())
+ assert.Equal(t, []byte{shared.GS, '!', 0x11}, c.DoubleSizeText())
+ assert.Equal(t, []byte{shared.GS, '!', 0x22}, c.TripleSizeText())
+ assert.Equal(t, []byte{shared.GS, '!', 0x33}, c.QuadraSizeText())
+ assert.Equal(t, []byte{shared.GS, '!', 0x44}, c.PentaSizeText())
+ assert.Equal(t, []byte{shared.GS, '!', 0x55}, c.HexaSizeText())
+ assert.Equal(t, []byte{shared.GS, '!', 0x66}, c.HeptaSizeText())
+ assert.Equal(t, []byte{shared.GS, '!', 0x77}, c.OctaSizeText())
+}
+
+func TestEscposProtocol_CustomSizeText(t *testing.T) {
+ c := NewEscpos()
+
+ t.Run("clamped below 1", func(t *testing.T) {
+ assert.Equal(t, c.SingleSizeText(), c.CustomSizeText(0, 0))
+ })
+
+ t.Run("clamped above 8", func(t *testing.T) {
+ assert.Equal(t, c.OctaSizeText(), c.CustomSizeText(9, 10))
+ })
+
+ t.Run("custom valid size", func(t *testing.T) {
+ expected := []byte{shared.GS, '!', byte((2-1)<<4 | (4 - 1))}
+ assert.Equal(t, expected, c.CustomSizeText(2, 4))
+ })
+}
+
+func TestEscposProtocol_LineSpacing(t *testing.T) {
+ c := NewEscpos()
+
+ assert.Equal(t, []byte{shared.ESC, '3', 30}, c.SetLineSpacing(30))
+ assert.Equal(t, []byte{shared.ESC, '2'}, c.SelectDefaultLineSpacing())
+}
+
+func TestEscposProtocol_MechanismControl(t *testing.T) {
+ c := NewEscpos()
+
+ pulseCmd, err := c.Pulse(0, 10, 10)
+ require.NoError(t, err)
+ assert.NotEmpty(t, pulseCmd)
+
+ beepCmd, err := c.Beep(2, 5)
+ require.NoError(t, err)
+ assert.NotEmpty(t, beepCmd)
+}
+
diff --git a/pkg/connection/connector.go b/pkg/connection/connector.go
index 2c6d99e..ba759cc 100644
--- a/pkg/connection/connector.go
+++ b/pkg/connection/connector.go
@@ -5,9 +5,4 @@ import "io"
// Connector define la interfaz para cualquier tipo de conexión con la impresora
type Connector interface {
io.WriteCloser // Write([]byte) (int, error) y Close() error
-
- // TODO: Agregar más métodos si necesitas:
- // - Read([]byte) (int, error) para status
- // - IsConnected() bool
- // - Reset() error
}
diff --git a/pkg/constants/constants.go b/pkg/constants/constants.go
index 6d6672d..e1e33b7 100644
--- a/pkg/constants/constants.go
+++ b/pkg/constants/constants.go
@@ -89,7 +89,6 @@ const (
Bilinear Scaling = "bilinear"
// Bicubic uses Bicubic Scaling
Bicubic Scaling = "bicubic"
- // TODO: Add more scaling algorithms if needed
)
// ============================================================================
diff --git a/pkg/constants/constants_test.go b/pkg/constants/constants_test.go
new file mode 100644
index 0000000..a5cf2e4
--- /dev/null
+++ b/pkg/constants/constants_test.go
@@ -0,0 +1,230 @@
+package constants_test
+
+import (
+ "testing"
+
+ "github.com/adcondev/poster/pkg/constants"
+)
+
+func TestConstants_StringMethods(t *testing.T) {
+ // Alignment
+ alignments := []struct {
+ val constants.Alignment
+ want string
+ }{
+ {constants.Left, "left"},
+ {constants.Center, "center"},
+ {constants.Right, "right"},
+ }
+ for _, tt := range alignments {
+ if got := tt.val.String(); got != tt.want {
+ t.Errorf("Alignment.String() = %q, want %q", got, tt.want)
+ }
+ }
+
+ // Dithering
+ ditherings := []struct {
+ val constants.Dithering
+ want string
+ }{
+ {constants.Threshold, "threshold"},
+ {constants.Atkinson, "atkinson"},
+ {constants.FloydSteinberg, "floyd_steinberg"},
+ {constants.Ordered, "ordered"},
+ }
+ for _, tt := range ditherings {
+ if got := tt.val.String(); got != tt.want {
+ t.Errorf("Dithering.String() = %q, want %q", got, tt.want)
+ }
+ }
+
+ // Scaling
+ scalings := []struct {
+ val constants.Scaling
+ want string
+ }{
+ {constants.NearestNeighbor, "nearest_neighbor"},
+ {constants.Bilinear, "bilinear"},
+ {constants.Bicubic, "bicubic"},
+ }
+ for _, tt := range scalings {
+ if got := tt.val.String(); got != tt.want {
+ t.Errorf("Scaling.String() = %q, want %q", got, tt.want)
+ }
+ }
+
+ // Size
+ sizes := []struct {
+ val constants.Size
+ want string
+ }{
+ {constants.Normal, "1x1"},
+ {constants.Double, "2x2"},
+ {constants.Triple, "3x3"},
+ {constants.Quad, "4x4"},
+ {constants.Penta, "5x5"},
+ {constants.Hexa, "6x6"},
+ {constants.Hepta, "7x7"},
+ {constants.Octa, "8x8"},
+ }
+ for _, tt := range sizes {
+ if got := tt.val.String(); got != tt.want {
+ t.Errorf("Size.String() = %q, want %q", got, tt.want)
+ }
+ }
+
+ // Underline
+ underlines := []struct {
+ val constants.Underline
+ want string
+ }{
+ {constants.NoDot, "0pt"},
+ {constants.OneDot, "1pt"},
+ {constants.TwoDot, "2pt"},
+ }
+ for _, tt := range underlines {
+ if got := tt.val.String(); got != tt.want {
+ t.Errorf("Underline.String() = %q, want %q", got, tt.want)
+ }
+ }
+
+ // Font
+ fonts := []struct {
+ val constants.Font
+ want string
+ }{
+ {constants.A, "a"},
+ {constants.B, "b"},
+ {constants.C, "c"},
+ {constants.D, "d"},
+ }
+ for _, tt := range fonts {
+ if got := tt.val.String(); got != tt.want {
+ t.Errorf("Font.String() = %q, want %q", got, tt.want)
+ }
+ }
+
+ // Mode (Cut)
+ modes := []struct {
+ val constants.Mode
+ want string
+ }{
+ {constants.Partial, "partial"},
+ {constants.Full, "full"},
+ }
+ for _, tt := range modes {
+ if got := tt.val.String(); got != tt.want {
+ t.Errorf("Mode.String() = %q, want %q", got, tt.want)
+ }
+ }
+
+ // ErrorCorrection
+ errorCorrections := []struct {
+ val constants.ErrorCorrection
+ want string
+ }{
+ {constants.L, "L"},
+ {constants.M, "M"},
+ {constants.Q, "Q"},
+ {constants.H, "H"},
+ }
+ for _, tt := range errorCorrections {
+ if got := tt.val.String(); got != tt.want {
+ t.Errorf("ErrorCorrection.String() = %q, want %q", got, tt.want)
+ }
+ }
+
+ // Symbology
+ symbologies := []struct {
+ val constants.Symbology
+ want string
+ }{
+ {constants.CODE39, "code39"},
+ {constants.CODE128, "code128"},
+ {constants.EAN13, "ean13"},
+ {constants.UPCA, "upca"},
+ {constants.ITF, "itf"},
+ {constants.CODABAR, "codabar"},
+ {constants.EAN8, "ean8"},
+ {constants.UPCE, "upce"},
+ {constants.JAN13, "jan13"},
+ {constants.JAN8, "jan8"},
+ {constants.CODE93, "code93"},
+ {constants.GS1128, "gs1_128"},
+ {constants.CODE128Auto, "code128_auto"},
+ }
+ for _, tt := range symbologies {
+ if got := tt.val.String(); got != tt.want {
+ t.Errorf("Symbology.String() = %q, want %q", got, tt.want)
+ }
+ }
+
+ // HriPosition
+ hriPositions := []struct {
+ val constants.HriPosition
+ want string
+ }{
+ {constants.Below, "below"},
+ {constants.Above, "above"},
+ {constants.Both, "both"},
+ {constants.None, "none"},
+ }
+ for _, tt := range hriPositions {
+ if got := tt.val.String(); got != tt.want {
+ t.Errorf("HriPosition.String() = %q, want %q", got, tt.want)
+ }
+ }
+
+ // Format
+ formats := []struct {
+ val constants.Format
+ want string
+ }{
+ {constants.Hex, "hex"},
+ {constants.Base64, "base64"},
+ }
+ for _, tt := range formats {
+ if got := tt.val.String(); got != tt.want {
+ t.Errorf("Format.String() = %q, want %q", got, tt.want)
+ }
+ }
+}
+
+func TestConversions(t *testing.T) {
+ // PaperWidthFromMm
+ if got := constants.PaperWidthFromMm(80); got != 80*constants.DefaultDotsPerMm {
+ t.Errorf("PaperWidthFromMm(80) = %d, want %d", got, 80*constants.DefaultDotsPerMm)
+ }
+
+ // CharsPerLineForFont
+ if got := constants.CharsPerLineForFont(576, 12); got != 48 {
+ t.Errorf("CharsPerLineForFont(576, 12) = %d, want 48", got)
+ }
+ if got := constants.CharsPerLineForFont(576, 0); got != 0 {
+ t.Errorf("CharsPerLineForFont(576, 0) = %d, want 0", got)
+ }
+ if got := constants.CharsPerLineForFont(576, -5); got != 0 {
+ t.Errorf("CharsPerLineForFont(576, -5) = %d, want 0", got)
+ }
+
+ // MaxCharsForPaper
+ if got := constants.MaxCharsForPaper(384, 12); got != 32 {
+ t.Errorf("MaxCharsForPaper(384, 12) = %d, want 32", got)
+ }
+ if got := constants.MaxCharsForPaper(384, 0); got != 0 {
+ t.Errorf("MaxCharsForPaper(384, 0) = %d, want 0", got)
+ }
+ if got := constants.MaxCharsForPaper(384, -2); got != 0 {
+ t.Errorf("MaxCharsForPaper(384, -2) = %d, want 0", got)
+ }
+
+ // MaxCharsForPaperFontA
+ if got := constants.MaxCharsForPaperFontA(384); got != 384/constants.FontAWidth {
+ t.Errorf("MaxCharsForPaperFontA(384) = %d, want %d", got, 384/constants.FontAWidth)
+ }
+
+ // MaxCharsForPaperFontB
+ if got := constants.MaxCharsForPaperFontB(384); got != 384/constants.FontBWidth {
+ t.Errorf("MaxCharsForPaperFontB(384) = %d, want %d", got, 384/constants.FontBWidth)
+ }
+}
diff --git a/pkg/constants/defaults.go b/pkg/constants/defaults.go
index c61e0c7..c79e2df 100644
--- a/pkg/constants/defaults.go
+++ b/pkg/constants/defaults.go
@@ -2,8 +2,6 @@
// All packages should reference these constants to ensure consistency.
package constants
-// TODO: Add MustCompile validation for some constants (Text Size, etc.)
-
// ============================================================================
// Defaults
// ============================================================================
diff --git a/pkg/document/executor/barcode_handler_test.go b/pkg/document/executor/barcode_handler_test.go
index a9dc26f..935b5f2 100644
--- a/pkg/document/executor/barcode_handler_test.go
+++ b/pkg/document/executor/barcode_handler_test.go
@@ -5,6 +5,7 @@ import (
"testing"
"github.com/adcondev/poster/pkg/constants"
+ "github.com/adcondev/poster/pkg/service"
)
// ============================================================================
@@ -169,3 +170,84 @@ func TestBarcodeCommand_Validation(t *testing.T) {
})
}
}
+
+// ============================================================================
+// Direct Handler Execution Tests
+// ============================================================================
+
+func TestHandleBarcode_Execution(t *testing.T) {
+ mock := service.NewMockPrinter()
+ exec := NewExecutor(mock)
+
+ t.Run("missing symbology returns error", func(t *testing.T) {
+ err := exec.handleBarcode(mock, json.RawMessage(`{"data": "123"}`))
+ if err == nil {
+ t.Error("expected error for missing symbology")
+ }
+ })
+
+ t.Run("missing data returns error", func(t *testing.T) {
+ err := exec.handleBarcode(mock, json.RawMessage(`{"symbology": "code128"}`))
+ if err == nil {
+ t.Error("expected error for missing data")
+ }
+ })
+
+ t.Run("invalid json returns error", func(t *testing.T) {
+ err := exec.handleBarcode(mock, json.RawMessage(`{bad-json`))
+ if err == nil {
+ t.Error("expected error for invalid json")
+ }
+ })
+
+ t.Run("valid barcode with all options and even numeric Set C", func(t *testing.T) {
+ mock.Reset()
+ jsonStr := `{
+ "symbology": "code128",
+ "data": "123456",
+ "width": 3,
+ "height": 100,
+ "hri_position": "below",
+ "hri_font": "B",
+ "align": "center"
+ }`
+ err := exec.handleBarcode(mock, json.RawMessage(jsonStr))
+ if err != nil {
+ t.Fatalf("handleBarcode failed: %v", err)
+ }
+ if mock.CallCount("PrintBarcode") != 1 {
+ t.Errorf("expected 1 PrintBarcode call, got %d", mock.CallCount("PrintBarcode"))
+ }
+ if mock.CallCount("AlignCenter") != 1 {
+ t.Errorf("expected 1 AlignCenter call, got %d", mock.CallCount("AlignCenter"))
+ }
+ })
+
+ t.Run("clamped width and height boundaries", func(t *testing.T) {
+ mock.Reset()
+ jsonLow := `{"symbology": "ean13", "data": "1234567890128", "width": 1, "height": 0, "align": "left"}`
+ if err := exec.handleBarcode(mock, json.RawMessage(jsonLow)); err != nil {
+ t.Fatalf("handleBarcode with low bounds failed: %v", err)
+ }
+
+ mock.Reset()
+ jsonHigh := `{"symbology": "ean13", "data": "1234567890128", "width": 10, "height": 300, "align": "right"}`
+ if err := exec.handleBarcode(mock, json.RawMessage(jsonHigh)); err != nil {
+ t.Fatalf("handleBarcode with high bounds failed: %v", err)
+ }
+ })
+
+ t.Run("various HRI positions and fonts", func(t *testing.T) {
+ positions := []string{"none", "above", "below", "both", "unknown"}
+ fonts := []string{"A", "B", "unknown"}
+ for _, pos := range positions {
+ for _, font := range fonts {
+ mock.Reset()
+ payload := `{"symbology": "code39", "data": "TEST", "hri_position": "` + pos + `", "hri_font": "` + font + `"}`
+ if err := exec.handleBarcode(mock, json.RawMessage(payload)); err != nil {
+ t.Errorf("handleBarcode failed for pos=%s font=%s: %v", pos, font, err)
+ }
+ }
+ }
+ })
+}
diff --git a/pkg/document/executor/basic_handler_test.go b/pkg/document/executor/basic_handler_test.go
index 0673f43..99dce01 100644
--- a/pkg/document/executor/basic_handler_test.go
+++ b/pkg/document/executor/basic_handler_test.go
@@ -1,10 +1,16 @@
package executor
import (
+ "encoding/base64"
"encoding/json"
+ "errors"
+ "strings"
"testing"
"github.com/adcondev/poster/pkg/constants"
+ "github.com/adcondev/poster/pkg/document/schema"
+ "github.com/adcondev/poster/pkg/service"
+ "github.com/adcondev/poster/pkg/tables"
)
// ============================================================================
@@ -266,3 +272,592 @@ func TestFeedCommand_DefaultApplication(t *testing.T) {
t.Errorf("Expected default lines %d, got %d", constants.DefaultFeedLines, cmd.Lines)
}
}
+
+// ============================================================================
+// Direct Handler Execution Tests
+// ============================================================================
+
+func TestHandleSeparator_Execution(t *testing.T) {
+ mock := service.NewMockPrinter()
+ exec := NewExecutor(mock)
+
+ t.Run("default separator with profile dots", func(t *testing.T) {
+ mock.Reset()
+ err := exec.handleSeparator(mock, json.RawMessage(`{}`))
+ if err != nil {
+ t.Fatalf("handleSeparator failed: %v", err)
+ }
+ if mock.CallCount("PrintLine") != 1 {
+ t.Errorf("expected 1 PrintLine call, got %d", mock.CallCount("PrintLine"))
+ }
+ })
+
+ t.Run("custom char and length", func(t *testing.T) {
+ mock.Reset()
+ err := exec.handleSeparator(mock, json.RawMessage(`{"char": "=", "length": 20}`))
+ if err != nil {
+ t.Fatalf("handleSeparator failed: %v", err)
+ }
+ if mock.CallCount("PrintLine") != 1 {
+ t.Errorf("expected 1 PrintLine call, got %d", mock.CallCount("PrintLine"))
+ }
+ })
+
+ t.Run("invalid json", func(t *testing.T) {
+ err := exec.handleSeparator(mock, json.RawMessage(`{invalid`))
+ if err == nil {
+ t.Error("expected error for invalid json")
+ }
+ })
+}
+
+func TestHandleFeed_Execution(t *testing.T) {
+ mock := service.NewMockPrinter()
+ exec := NewExecutor(mock)
+
+ t.Run("custom lines", func(t *testing.T) {
+ mock.Reset()
+ err := exec.handleFeed(mock, json.RawMessage(`{"lines": 4}`))
+ if err != nil {
+ t.Fatalf("handleFeed failed: %v", err)
+ }
+ if mock.CallCount("FeedLines") != 1 {
+ t.Errorf("expected 1 FeedLines call, got %d", mock.CallCount("FeedLines"))
+ }
+ })
+
+ t.Run("default lines when <= 0", func(t *testing.T) {
+ mock.Reset()
+ err := exec.handleFeed(mock, json.RawMessage(`{"lines": 0}`))
+ if err != nil {
+ t.Fatalf("handleFeed failed: %v", err)
+ }
+ if mock.CallCount("FeedLines") != 1 {
+ t.Errorf("expected 1 FeedLines call, got %d", mock.CallCount("FeedLines"))
+ }
+ })
+
+ t.Run("clamped lines when > 255", func(t *testing.T) {
+ mock.Reset()
+ err := exec.handleFeed(mock, json.RawMessage(`{"lines": 300}`))
+ if err != nil {
+ t.Fatalf("handleFeed failed: %v", err)
+ }
+ if mock.CallCount("FeedLines") != 1 {
+ t.Errorf("expected 1 FeedLines call, got %d", mock.CallCount("FeedLines"))
+ }
+ })
+
+ t.Run("invalid json", func(t *testing.T) {
+ err := exec.handleFeed(mock, json.RawMessage(`{bad`))
+ if err == nil {
+ t.Error("expected error for invalid json")
+ }
+ })
+}
+
+func TestHandleCut_Execution(t *testing.T) {
+ mock := service.NewMockPrinter()
+ exec := NewExecutor(mock)
+
+ t.Run("full cut with feed", func(t *testing.T) {
+ mock.Reset()
+ err := exec.handleCut(mock, json.RawMessage(`{"mode": "full", "feed": 3}`))
+ if err != nil {
+ t.Fatalf("handleCut failed: %v", err)
+ }
+ if mock.CallCount("FullFeedAndCut") != 1 {
+ t.Errorf("expected 1 FullFeedAndCut call, got %d", mock.CallCount("FullFeedAndCut"))
+ }
+ if mock.CallCount("FeedLines") != 1 {
+ t.Errorf("expected 1 FeedLines call, got %d", mock.CallCount("FeedLines"))
+ }
+ })
+
+ t.Run("partial cut default", func(t *testing.T) {
+ mock.Reset()
+ err := exec.handleCut(mock, json.RawMessage(`{"mode": "partial", "feed": 0}`))
+ if err != nil {
+ t.Fatalf("handleCut failed: %v", err)
+ }
+ if mock.CallCount("PartialFeedAndCut") != 1 {
+ t.Errorf("expected 1 PartialFeedAndCut call, got %d", mock.CallCount("PartialFeedAndCut"))
+ }
+ })
+
+ t.Run("feed clamped when > 255", func(t *testing.T) {
+ mock.Reset()
+ err := exec.handleCut(mock, json.RawMessage(`{"feed": 500}`))
+ if err != nil {
+ t.Fatalf("handleCut failed: %v", err)
+ }
+ if mock.CallCount("FeedLines") != 1 {
+ t.Errorf("expected 1 FeedLines call, got %d", mock.CallCount("FeedLines"))
+ }
+ })
+
+ t.Run("invalid json", func(t *testing.T) {
+ err := exec.handleCut(mock, json.RawMessage(`{bad`))
+ if err == nil {
+ t.Error("expected error for invalid json")
+ }
+ })
+}
+
+func TestHandlePulse_Execution(t *testing.T) {
+ mock := service.NewMockPrinter()
+ exec := NewExecutor(mock)
+
+ t.Run("default pulse", func(t *testing.T) {
+ mock.Reset()
+ err := exec.handlePulse(mock, json.RawMessage(`{}`))
+ if err != nil {
+ t.Fatalf("handlePulse failed: %v", err)
+ }
+ if mock.CallCount("Pulse") != 1 {
+ t.Errorf("expected 1 Pulse call, got %d", mock.CallCount("Pulse"))
+ }
+ })
+
+ t.Run("custom pulse clamped", func(t *testing.T) {
+ mock.Reset()
+ err := exec.handlePulse(mock, json.RawMessage(`{"pin": 0, "on_time": 600, "off_time": 600}`))
+ if err != nil {
+ t.Fatalf("handlePulse failed: %v", err)
+ }
+ if mock.CallCount("Pulse") != 1 {
+ t.Errorf("expected 1 Pulse call, got %d", mock.CallCount("Pulse"))
+ }
+ })
+
+ t.Run("invalid json", func(t *testing.T) {
+ err := exec.handlePulse(mock, json.RawMessage(`{bad`))
+ if err == nil {
+ t.Error("expected error for invalid json")
+ }
+ })
+}
+
+func TestHandleBeep_Execution(t *testing.T) {
+ mock := service.NewMockPrinter()
+ exec := NewExecutor(mock)
+
+ t.Run("default beep", func(t *testing.T) {
+ mock.Reset()
+ err := exec.handleBeep(mock, json.RawMessage(`{}`))
+ if err != nil {
+ t.Fatalf("handleBeep failed: %v", err)
+ }
+ if mock.CallCount("Beep") != 1 {
+ t.Errorf("expected 1 Beep call, got %d", mock.CallCount("Beep"))
+ }
+ })
+
+ t.Run("custom beep clamped", func(t *testing.T) {
+ mock.Reset()
+ err := exec.handleBeep(mock, json.RawMessage(`{"times": 300, "lapse": 300}`))
+ if err != nil {
+ t.Fatalf("handleBeep failed: %v", err)
+ }
+ if mock.CallCount("Beep") != 1 {
+ t.Errorf("expected 1 Beep call, got %d", mock.CallCount("Beep"))
+ }
+ })
+
+ t.Run("invalid json", func(t *testing.T) {
+ err := exec.handleBeep(mock, json.RawMessage(`{bad`))
+ if err == nil {
+ t.Error("expected error for invalid json")
+ }
+ })
+}
+
+func TestAlignScopeAndUtilities(t *testing.T) {
+ mock := service.NewMockPrinter()
+
+ t.Run("align scope success", func(t *testing.T) {
+ mock.Reset()
+ called := false
+ err := AlignScope(mock, "center", func() error {
+ called = true
+ return nil
+ })
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if !called {
+ t.Error("expected fn to be called")
+ }
+ if mock.CallCount("AlignCenter") != 1 {
+ t.Errorf("expected 1 AlignCenter, got %d", mock.CallCount("AlignCenter"))
+ }
+ if mock.CallCount("AlignLeft") != 1 {
+ t.Errorf("expected 1 AlignLeft for reset, got %d", mock.CallCount("AlignLeft"))
+ }
+ })
+
+ t.Run("align scope fn error", func(t *testing.T) {
+ mock.Reset()
+ expectedErr := errors.New("fn failed")
+ err := AlignScope(mock, "right", func() error {
+ return expectedErr
+ })
+ if !errors.Is(err, expectedErr) {
+ t.Errorf("expected fn error, got %v", err)
+ }
+ })
+
+ t.Run("apply alignment options", func(t *testing.T) {
+ mock.Reset()
+ _ = ApplyAlignment(mock, "center")
+ _ = ApplyAlignment(mock, "right")
+ _ = ApplyAlignment(mock, "left")
+ _ = ApplyAlignment(mock, "unknown")
+ if mock.CallCount("AlignCenter") != 1 {
+ t.Errorf("expected 1 AlignCenter, got %d", mock.CallCount("AlignCenter"))
+ }
+ if mock.CallCount("AlignRight") != 1 {
+ t.Errorf("expected 1 AlignRight, got %d", mock.CallCount("AlignRight"))
+ }
+ if mock.CallCount("AlignLeft") != 2 {
+ t.Errorf("expected 2 AlignLeft, got %d", mock.CallCount("AlignLeft"))
+ }
+ })
+
+ t.Run("resolve alignment", func(t *testing.T) {
+ if got := ResolveAlignment("", constants.Center); got != constants.Center.String() {
+ t.Errorf("expected default center, got %s", got)
+ }
+ if got := ResolveAlignment("RIGHT", constants.Left); got != "right" {
+ t.Errorf("expected lower right, got %s", got)
+ }
+ })
+}
+
+func TestHandleRaw_Execution(t *testing.T) {
+ mock := service.NewMockPrinter()
+ exec := NewExecutor(mock)
+
+ t.Run("hex format", func(t *testing.T) {
+ mock.Reset()
+ payload := `{"format": "hex", "hex": "1B 40", "safe_mode": false}`
+ err := exec.handleRaw(mock, json.RawMessage(payload))
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if mock.CallCount("Write") != 1 {
+ t.Errorf("expected 1 Write call, got %d", mock.CallCount("Write"))
+ }
+ })
+
+ t.Run("base64 format", func(t *testing.T) {
+ mock.Reset()
+ encoded := base64.StdEncoding.EncodeToString([]byte{0x1B, 0x32})
+ payload := `{"format": "base64", "hex": "` + encoded + `"}`
+ err := exec.handleRaw(mock, json.RawMessage(payload))
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if mock.CallCount("Write") != 1 {
+ t.Errorf("expected 1 Write call, got %d", mock.CallCount("Write"))
+ }
+ })
+
+ t.Run("default format is hex", func(t *testing.T) {
+ mock.Reset()
+ payload := `{"hex": "1B 32"}`
+ err := exec.handleRaw(mock, json.RawMessage(payload))
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if mock.CallCount("Write") != 1 {
+ t.Errorf("expected 1 Write call, got %d", mock.CallCount("Write"))
+ }
+ })
+
+ t.Run("unsupported format", func(t *testing.T) {
+ payload := `{"format": "yaml", "hex": "1B"}`
+ err := exec.handleRaw(mock, json.RawMessage(payload))
+ if err == nil || !strings.Contains(err.Error(), "unsupported format") {
+ t.Errorf("expected unsupported format error, got %v", err)
+ }
+ })
+
+ t.Run("invalid hex string", func(t *testing.T) {
+ payload := `{"format": "hex", "hex": "ZZ"}`
+ err := exec.handleRaw(mock, json.RawMessage(payload))
+ if err == nil {
+ t.Error("expected error for invalid hex string")
+ }
+ })
+
+ t.Run("invalid base64 string", func(t *testing.T) {
+ payload := `{"format": "base64", "hex": "!!!"}`
+ err := exec.handleRaw(mock, json.RawMessage(payload))
+ if err == nil {
+ t.Error("expected error for invalid base64")
+ }
+ })
+
+ t.Run("empty raw command", func(t *testing.T) {
+ payload := `{"format": "base64", "hex": ""}`
+ err := exec.handleRaw(mock, json.RawMessage(payload))
+ if err == nil || !strings.Contains(err.Error(), "cannot be empty") {
+ t.Errorf("expected empty error, got %v", err)
+ }
+ })
+
+ t.Run("command too large", func(t *testing.T) {
+ largeHex := strings.Repeat("00 ", constants.RawMaxBytes+1)
+ payload := `{"hex": "` + strings.TrimSpace(largeHex) + `"}`
+ err := exec.handleRaw(mock, json.RawMessage(payload))
+ if err == nil || !strings.Contains(err.Error(), "too large") {
+ t.Errorf("expected too large error, got %v", err)
+ }
+ })
+
+ t.Run("safe mode blocks critical command", func(t *testing.T) {
+ payload := `{"hex": "1B 40", "safe_mode": true}`
+ err := exec.handleRaw(mock, json.RawMessage(payload))
+ if err == nil || !strings.Contains(err.Error(), "unsafe command blocked") {
+ t.Errorf("expected safe mode error, got %v", err)
+ }
+ })
+
+ t.Run("invalid json", func(t *testing.T) {
+ err := exec.handleRaw(mock, json.RawMessage(`{invalid`))
+ if err == nil {
+ t.Error("expected error for invalid json")
+ }
+ })
+}
+
+func TestTableHandlerUtils_Extra(t *testing.T) {
+ t.Run("calculate total width", func(t *testing.T) {
+ width := CalculateTotalWidth(10, 3, 2)
+ if width != 14 {
+ t.Errorf("expected width 14, got %d", width)
+ }
+ widthZero := CalculateTotalWidth(10, 0, 2)
+ if widthZero != 10 {
+ t.Errorf("expected width 10, got %d", widthZero)
+ }
+ })
+
+ t.Run("render table string", func(t *testing.T) {
+ showH := true
+ cmd := &TableCommand{
+ Definition: tables.Definition{
+ Columns: []tables.Column{
+ {Name: "Item", Width: 10},
+ {Name: "Price", Width: 6},
+ },
+ },
+ ShowHeaders: &showH,
+ Rows: [][]string{
+ {"Coffee", "$3.50"},
+ },
+ }
+
+ out, err := RenderTable(cmd, nil)
+ if err != nil {
+ t.Fatalf("RenderTable failed: %v", err)
+ }
+ if !strings.Contains(out, "Coffee") {
+ t.Errorf("expected output to contain Coffee, got %s", out)
+ }
+
+ opts := &tables.Options{ShowHeaders: false}
+ outOpts, err := RenderTable(cmd, opts)
+ if err != nil {
+ t.Fatalf("RenderTable with opts failed: %v", err)
+ }
+ if outOpts == "" {
+ t.Error("expected non-empty output")
+ }
+ })
+}
+
+func TestHandlerExecutor_Extra(t *testing.T) {
+ mock := service.NewMockPrinter()
+ exec := NewExecutor(mock)
+
+ t.Run("register custom handler", func(t *testing.T) {
+ customCalled := false
+ exec.RegisterHandler("my_custom_cmd", func(_ service.PrinterActions, _ json.RawMessage) error {
+ customCalled = true
+ return nil
+ })
+
+ doc := &schema.Document{
+ Version: constants.DefaultVersion,
+ Profile: schema.ProfileConfig{Model: "TestModel"},
+ Commands: []schema.Command{
+ {Type: "my_custom_cmd", Data: json.RawMessage(`{}`)},
+ },
+ }
+ if err := exec.Execute(doc); err != nil {
+ t.Fatalf("Execute failed: %v", err)
+ }
+ if !customCalled {
+ t.Error("expected custom handler to be called")
+ }
+ })
+
+ t.Run("execute json valid and invalid", func(t *testing.T) {
+ validJSON := []byte(`{
+ "version": "1.0",
+ "profile": {"model": "Generic", "paper_width": 58, "dpi": 203, "has_qr": true},
+ "commands": [
+ {"type": "feed", "data": {"lines": 1}}
+ ]
+ }`)
+ if err := exec.ExecuteJSON(validJSON); err != nil {
+ t.Fatalf("ExecuteJSON failed: %v", err)
+ }
+
+ invalidJSON := []byte(`{not valid json}`)
+ if err := exec.ExecuteJSON(invalidJSON); err == nil {
+ t.Error("expected error for invalid json in ExecuteJSON")
+ }
+ })
+
+ t.Run("apply profile document variations", func(t *testing.T) {
+ doc80 := &schema.Document{
+ Version: constants.DefaultVersion,
+ Profile: schema.ProfileConfig{Model: "Generic", PaperWidth: 80, DPI: 203, CodeTable: "PC850"},
+ Commands: []schema.Command{
+ {Type: "feed", Data: json.RawMessage(`{"lines": 1}`)},
+ },
+ }
+ if err := exec.Execute(doc80); err != nil {
+ t.Fatalf("Execute 80mm failed: %v", err)
+ }
+ if mock.GetProfile().DotsPerLine != constants.PaperPxWidth80mm {
+ t.Errorf("expected %d dots per line, got %d", constants.PaperPxWidth80mm, mock.GetProfile().DotsPerLine)
+ }
+
+ docCustom := &schema.Document{
+ Version: constants.DefaultVersion,
+ Profile: schema.ProfileConfig{Model: "Generic", PaperWidth: 72, DPI: 300},
+ Commands: []schema.Command{
+ {Type: "feed", Data: json.RawMessage(`{"lines": 1}`)},
+ },
+ }
+ if err := exec.Execute(docCustom); err != nil {
+ t.Fatalf("Execute custom paper failed: %v", err)
+ }
+
+ docPreset := &schema.Document{
+ Version: constants.DefaultVersion,
+ Profile: schema.ProfileConfig{Model: "TM-T88VI"},
+ Commands: []schema.Command{
+ {Type: "feed", Data: json.RawMessage(`{"lines": 1}`)},
+ },
+ }
+ if err := exec.Execute(docPreset); err != nil {
+ t.Fatalf("Execute preset failed: %v", err)
+ }
+
+ docNoModel := &schema.Document{
+ Version: constants.DefaultVersion,
+ Commands: []schema.Command{
+ {Type: "feed", Data: json.RawMessage(`{"lines": 1}`)},
+ },
+ }
+ if err := exec.Execute(docNoModel); err == nil {
+ t.Error("expected error for doc without model")
+ }
+
+ if err := exec.Execute(nil); err == nil {
+ t.Error("expected error for nil doc")
+ }
+ })
+}
+
+func TestHandleSeparator_Extra(t *testing.T) {
+ mock := service.NewMockPrinter()
+ exec := NewExecutor(mock)
+
+ t.Run("default char and profile dots per line", func(t *testing.T) {
+ mock.Reset()
+ prof := mock.GetProfile()
+ prof.DotsPerLine = 384
+ err := exec.handleSeparator(mock, json.RawMessage(`{}`))
+ if err != nil {
+ t.Fatalf("handleSeparator failed: %v", err)
+ }
+ if mock.CallCount("PrintLine") != 1 {
+ t.Errorf("expected 1 PrintLine call, got %d", mock.CallCount("PrintLine"))
+ }
+ })
+
+ t.Run("profile dots per line zero fallback to default length", func(t *testing.T) {
+ mock.Reset()
+ prof := mock.GetProfile()
+ prof.DotsPerLine = 0
+ err := exec.handleSeparator(mock, json.RawMessage(`{}`))
+ if err != nil {
+ t.Fatalf("handleSeparator failed: %v", err)
+ }
+ if mock.CallCount("PrintLine") != 1 {
+ t.Errorf("expected 1 PrintLine call, got %d", mock.CallCount("PrintLine"))
+ }
+ })
+
+ t.Run("rune truncation with multibyte char", func(t *testing.T) {
+ mock.Reset()
+ err := exec.handleSeparator(mock, json.RawMessage(`{"char": "==", "length": 5}`))
+ if err != nil {
+ t.Fatalf("handleSeparator failed: %v", err)
+ }
+ if mock.CallCount("PrintLine") != 1 {
+ t.Errorf("expected 1 PrintLine call, got %d", mock.CallCount("PrintLine"))
+ }
+ })
+}
+
+func TestHandleTable_Branches(t *testing.T) {
+ mock := service.NewMockPrinter()
+ exec := NewExecutor(mock)
+
+ t.Run("empty columns error", func(t *testing.T) {
+ payload := `{"definition": {"columns": []}, "rows": []}`
+ err := exec.handleTable(mock, json.RawMessage(payload))
+ if err == nil || !strings.Contains(err.Error(), "at least one column") {
+ t.Errorf("expected empty columns error, got %v", err)
+ }
+ })
+
+ t.Run("negative column spacing clamped and font B and align center", func(t *testing.T) {
+ mock.Reset()
+ payload := `{
+ "definition": {
+ "columns": [
+ {"name": "Item", "width": 10},
+ {"name": "Price", "width": 8}
+ ]
+ },
+ "options": {
+ "column_spacing": -5,
+ "font": "B",
+ "align": "center"
+ },
+ "rows": [
+ ["Coffee", "$3.00"]
+ ]
+ }`
+ err := exec.handleTable(mock, json.RawMessage(payload))
+ if err != nil {
+ t.Fatalf("handleTable failed: %v", err)
+ }
+ if mock.CallCount("FontB") != 1 {
+ t.Errorf("expected 1 FontB call, got %d", mock.CallCount("FontB"))
+ }
+ if mock.CallCount("AlignCenter") != 1 {
+ t.Errorf("expected 1 AlignCenter call, got %d", mock.CallCount("AlignCenter"))
+ }
+ })
+}
+
+
diff --git a/pkg/document/executor/image_handler_test.go b/pkg/document/executor/image_handler_test.go
index 5254308..4948282 100644
--- a/pkg/document/executor/image_handler_test.go
+++ b/pkg/document/executor/image_handler_test.go
@@ -5,6 +5,7 @@ import (
"testing"
"github.com/adcondev/poster/pkg/constants"
+ "github.com/adcondev/poster/pkg/service"
)
// ============================================================================
@@ -113,3 +114,77 @@ func TestImageCommand_Validation(t *testing.T) {
})
}
}
+
+// ============================================================================
+// Direct Handler Execution Tests
+// ============================================================================
+
+func TestHandleImage_Execution(t *testing.T) {
+ mock := service.NewMockPrinter()
+ exec := NewExecutor(mock)
+
+ // Valid 1x1 transparent PNG in base64
+ const validPNG1x1 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
+
+ t.Run("invalid json returns error", func(t *testing.T) {
+ err := exec.handleImage(mock, json.RawMessage(`{bad-json`))
+ if err == nil {
+ t.Error("expected error for invalid json")
+ }
+ })
+
+ t.Run("invalid base64 image data returns error", func(t *testing.T) {
+ err := exec.handleImage(mock, json.RawMessage(`{"code": "not-valid-base64-image"}`))
+ if err == nil {
+ t.Error("expected error for invalid image data")
+ }
+ })
+
+ t.Run("valid image with defaults", func(t *testing.T) {
+ mock.Reset()
+ payload := `{"code": "` + validPNG1x1 + `"}`
+ err := exec.handleImage(mock, json.RawMessage(payload))
+ if err != nil {
+ t.Fatalf("handleImage failed: %v", err)
+ }
+ if mock.CallCount("PrintBitmap") != 1 {
+ t.Errorf("expected 1 PrintBitmap call, got %d", mock.CallCount("PrintBitmap"))
+ }
+ })
+
+ t.Run("dithering modes, scaling, and alignments", func(t *testing.T) {
+ ditherings := []string{"atkinson", "threshold", "floyd_steinberg", "ordered", "bayer", "unknown_default"}
+ scalings := []string{"nns", "nearest_neighbor", "bilinear", "unknown_default"}
+ alignments := []string{"left", "center", "right", "default"}
+
+ for _, dither := range ditherings {
+ for _, scale := range scalings {
+ for _, align := range alignments {
+ mock.Reset()
+ payload := `{
+ "code": "` + validPNG1x1 + `",
+ "pixel_width": 64,
+ "threshold": 100,
+ "dithering": "` + dither + `",
+ "scaling": "` + scale + `",
+ "align": "` + align + `"
+ }`
+ err := exec.handleImage(mock, json.RawMessage(payload))
+ if err != nil {
+ t.Errorf("handleImage failed for dither=%s scale=%s align=%s: %v", dither, scale, align, err)
+ }
+ }
+ }
+ }
+ })
+
+ t.Run("pixel width clamped to profile dots per line", func(t *testing.T) {
+ mock.Reset()
+ mock.GetProfile().DotsPerLine = 384
+ payload := `{"code": "` + validPNG1x1 + `", "pixel_width": 1000}`
+ err := exec.handleImage(mock, json.RawMessage(payload))
+ if err != nil {
+ t.Fatalf("handleImage failed: %v", err)
+ }
+ })
+}
diff --git a/pkg/document/executor/qr_handler_test.go b/pkg/document/executor/qr_handler_test.go
index ff582b2..6ef9611 100644
--- a/pkg/document/executor/qr_handler_test.go
+++ b/pkg/document/executor/qr_handler_test.go
@@ -5,6 +5,7 @@ import (
"testing"
"github.com/adcondev/poster/pkg/constants"
+ "github.com/adcondev/poster/pkg/service"
)
// ============================================================================
@@ -131,3 +132,73 @@ func TestQRCommand_Validation(t *testing.T) {
})
}
}
+
+// ============================================================================
+// Direct Handler Execution Tests
+// ============================================================================
+
+func TestHandleQR_Execution(t *testing.T) {
+ mock := service.NewMockPrinter()
+ exec := NewExecutor(mock)
+
+ t.Run("empty data returns error", func(t *testing.T) {
+ err := exec.handleQR(mock, json.RawMessage(`{"data": ""}`))
+ if err == nil {
+ t.Error("expected error for empty QR data")
+ }
+ })
+
+ t.Run("invalid json returns error", func(t *testing.T) {
+ err := exec.handleQR(mock, json.RawMessage(`{bad-json`))
+ if err == nil {
+ t.Error("expected error for invalid json")
+ }
+ })
+
+ t.Run("invalid correction level returns error", func(t *testing.T) {
+ err := exec.handleQR(mock, json.RawMessage(`{"data": "test", "correction": "X"}`))
+ if err == nil {
+ t.Error("expected error for invalid correction level")
+ }
+ })
+
+ t.Run("valid QR with all options, human text, circle shape, logo", func(t *testing.T) {
+ mock.Reset()
+ jsonStr := `{
+ "data": "https://example.com",
+ "human_text": "Scan me",
+ "pixel_width": 300,
+ "correction": "H",
+ "align": "right",
+ "logo": "dGVzdA==",
+ "circle_shape": true
+ }`
+ err := exec.handleQR(mock, json.RawMessage(jsonStr))
+ if err != nil {
+ t.Fatalf("handleQR failed: %v", err)
+ }
+ if mock.CallCount("PrintQR") != 1 {
+ t.Errorf("expected 1 PrintQR call, got %d", mock.CallCount("PrintQR"))
+ }
+ if mock.CallCount("PrintLine") != 1 {
+ t.Errorf("expected 1 PrintLine call for human text, got %d", mock.CallCount("PrintLine"))
+ }
+ if mock.CallCount("AlignRight") != 1 {
+ t.Errorf("expected 1 AlignRight call, got %d", mock.CallCount("AlignRight"))
+ }
+ })
+
+ t.Run("various correction levels and alignments", func(t *testing.T) {
+ corrections := []string{"L", "M", "Q", "H"}
+ alignments := []string{"left", "center", "right", "default"}
+ for _, corr := range corrections {
+ for _, align := range alignments {
+ mock.Reset()
+ payload := `{"data": "test", "correction": "` + corr + `", "align": "` + align + `", "pixel_width": 50}`
+ if err := exec.handleQR(mock, json.RawMessage(payload)); err != nil {
+ t.Errorf("handleQR failed for corr=%s align=%s: %v", corr, align, err)
+ }
+ }
+ }
+ })
+}
diff --git a/pkg/document/executor/text_handler_test.go b/pkg/document/executor/text_handler_test.go
index a2602a8..42b8f70 100644
--- a/pkg/document/executor/text_handler_test.go
+++ b/pkg/document/executor/text_handler_test.go
@@ -6,6 +6,7 @@ import (
"github.com/adcondev/poster/pkg/constants"
"github.com/adcondev/poster/pkg/document/schema"
+ "github.com/adcondev/poster/pkg/service"
)
// ============================================================================
@@ -230,3 +231,428 @@ func TestParseDocument_UnicodeContent(t *testing.T) {
t.Errorf("Expected text '%s', got '%s'", expected, textCmd.Content.Text)
}
}
+
+// ============================================================================
+// Direct Handler Execution Tests
+// ============================================================================
+
+func TestHandleText_BasicAndStyles(t *testing.T) {
+ mock := service.NewMockPrinter()
+ exec := NewExecutor(mock)
+
+ t.Run("simple text print and printline", func(t *testing.T) {
+ mock.Reset()
+ payload := `{"content": {"text": "Line 1"}}`
+ if err := exec.handleText(mock, json.RawMessage(payload)); err != nil {
+ t.Fatalf("handleText failed: %v", err)
+ }
+ if mock.CallCount("PrintLine") != 1 {
+ t.Errorf("expected 1 PrintLine call, got %d", mock.CallCount("PrintLine"))
+ }
+
+ mock.Reset()
+ payloadNoNL := `{"content": {"text": "No newline"}, "new_line": false}`
+ if err := exec.handleText(mock, json.RawMessage(payloadNoNL)); err != nil {
+ t.Fatalf("handleText failed: %v", err)
+ }
+ if mock.CallCount("Print") != 1 {
+ t.Errorf("expected 1 Print call, got %d", mock.CallCount("Print"))
+ }
+ })
+
+ t.Run("bold, inverse, underline styles", func(t *testing.T) {
+ mock.Reset()
+ payload := `{
+ "content": {
+ "text": "Styled",
+ "content_style": {
+ "bold": true,
+ "inverse": true,
+ "underline": "1pt"
+ },
+ "align": "center"
+ }
+ }`
+ if err := exec.handleText(mock, json.RawMessage(payload)); err != nil {
+ t.Fatalf("handleText failed: %v", err)
+ }
+ if mock.CallCount("EnableBold") != 1 {
+ t.Errorf("expected 1 EnableBold call, got %d", mock.CallCount("EnableBold"))
+ }
+ if mock.CallCount("DisableBold") != 1 {
+ t.Errorf("expected 1 DisableBold call on reset, got %d", mock.CallCount("DisableBold"))
+ }
+ if mock.CallCount("InverseOn") != 1 {
+ t.Errorf("expected 1 InverseOn call, got %d", mock.CallCount("InverseOn"))
+ }
+ if mock.CallCount("InverseOff") != 1 {
+ t.Errorf("expected 1 InverseOff call on reset, got %d", mock.CallCount("InverseOff"))
+ }
+ if mock.CallCount("OneDot") != 1 {
+ t.Errorf("expected 1 OneDot call, got %d", mock.CallCount("OneDot"))
+ }
+ if mock.CallCount("NoDot") != 1 {
+ t.Errorf("expected 1 NoDot call on reset, got %d", mock.CallCount("NoDot"))
+ }
+ })
+}
+
+func TestHandleText_SizesAndFonts(t *testing.T) {
+ mock := service.NewMockPrinter()
+ exec := NewExecutor(mock)
+
+ sizes := []string{
+ "normal", "double", "triple", "quad", "penta", "hexa", "hepta", "octa",
+ "2x2", "3x4", "8x8", "invalid_size",
+ }
+ for _, size := range sizes {
+ mock.Reset()
+ payload := `{"content": {"text": "SizeTest", "content_style": {"size": "` + size + `"}}}`
+ if err := exec.handleText(mock, json.RawMessage(payload)); err != nil {
+ t.Errorf("handleText failed for size=%s: %v", size, err)
+ }
+ }
+
+ underlines := []string{"0", "none", "1", "2"}
+ for _, ul := range underlines {
+ mock.Reset()
+ payload := `{"content": {"text": "ULTest", "content_style": {"underline": "` + ul + `"}}}`
+ if err := exec.handleText(mock, json.RawMessage(payload)); err != nil {
+ t.Errorf("handleText failed for underline=%s: %v", ul, err)
+ }
+ }
+
+ fonts := []string{"a", "b", "A", "unknown"}
+ for _, font := range fonts {
+ mock.Reset()
+ payload := `{"content": {"text": "FontTest", "content_style": {"font": "` + font + `"}}}`
+ if err := exec.handleText(mock, json.RawMessage(payload)); err != nil {
+ t.Errorf("handleText failed for font=%s: %v", font, err)
+ }
+ }
+}
+
+func TestHandleText_LabelsAndDifferingStyles(t *testing.T) {
+ mock := service.NewMockPrinter()
+ exec := NewExecutor(mock)
+
+ t.Run("label with different align prints on separate lines", func(t *testing.T) {
+ mock.Reset()
+ payload := `{
+ "label": {
+ "text": "Item",
+ "separator": ": ",
+ "align": "left",
+ "label_style": {"bold": true}
+ },
+ "content": {
+ "text": "$10.00",
+ "align": "right",
+ "content_style": {"bold": false}
+ }
+ }`
+ if err := exec.handleText(mock, json.RawMessage(payload)); err != nil {
+ t.Fatalf("handleText failed: %v", err)
+ }
+ if mock.CallCount("PrintLine") != 2 {
+ t.Errorf("expected 2 PrintLine calls for separate alignments, got %d", mock.CallCount("PrintLine"))
+ }
+ })
+
+ t.Run("label with same align inline and differing styles", func(t *testing.T) {
+ mock.Reset()
+ payload := `{
+ "label": {
+ "text": "Status",
+ "align": "left",
+ "label_style": {"bold": true, "size": "double"}
+ },
+ "content": {
+ "text": "OK",
+ "align": "left",
+ "content_style": {"bold": false, "size": "normal"}
+ }
+ }`
+ if err := exec.handleText(mock, json.RawMessage(payload)); err != nil {
+ t.Fatalf("handleText failed: %v", err)
+ }
+ if mock.CallCount("Print") != 1 {
+ t.Errorf("expected 1 Print call for inline label, got %d", mock.CallCount("Print"))
+ }
+ if mock.CallCount("PrintLine") != 1 {
+ t.Errorf("expected 1 PrintLine call for content, got %d", mock.CallCount("PrintLine"))
+ }
+ })
+}
+
+func TestHandleText_Errors(t *testing.T) {
+ mock := service.NewMockPrinter()
+ exec := NewExecutor(mock)
+
+ t.Run("invalid json returns error", func(t *testing.T) {
+ err := exec.handleText(mock, json.RawMessage(`{not-json`))
+ if err == nil {
+ t.Error("expected error for invalid json, got nil")
+ }
+ })
+
+ t.Run("nil printer in applyTextStyle returns error", func(t *testing.T) {
+ b := true
+ style := &TextStyle{Bold: &b}
+ if err := exec.applyTextStyle(nil, style); err == nil {
+ t.Error("expected error for nil printer in applyTextStyle")
+ }
+ if err := exec.resetTextStyle(nil, style); err == nil {
+ t.Error("expected error for nil printer in resetTextStyle")
+ }
+ })
+}
+
+func TestHandleText_LabelCustomSeparatorAndEmptyContent(t *testing.T) {
+ mock := service.NewMockPrinter()
+ exec := NewExecutor(mock)
+
+ t.Run("label with custom separator and no content", func(t *testing.T) {
+ mock.Reset()
+ payload := `{
+ "label": {
+ "text": "Item",
+ "separator": " -> "
+ },
+ "content": {
+ "text": ""
+ }
+ }`
+ if err := exec.handleText(mock, json.RawMessage(payload)); err != nil {
+ t.Fatalf("handleText failed: %v", err)
+ }
+ if mock.CallCount("Print") != 1 {
+ t.Errorf("expected 1 Print call for label without content, got %d", mock.CallCount("Print"))
+ }
+ })
+
+ t.Run("content without newline", func(t *testing.T) {
+ mock.Reset()
+ payload := `{
+ "content": {
+ "text": "Inline content"
+ },
+ "new_line": false
+ }`
+ if err := exec.handleText(mock, json.RawMessage(payload)); err != nil {
+ t.Fatalf("handleText failed: %v", err)
+ }
+ if mock.CallCount("Print") != 1 {
+ t.Errorf("expected 1 Print call for new_line false, got %d", mock.CallCount("Print"))
+ }
+ })
+
+ t.Run("content with style", func(t *testing.T) {
+ mock.Reset()
+ payload := `{
+ "content": {
+ "text": "Styled text",
+ "content_style": {"bold": true, "underline": "1pt"}
+ }
+ }`
+ if err := exec.handleText(mock, json.RawMessage(payload)); err != nil {
+ t.Fatalf("handleText failed: %v", err)
+ }
+ if mock.CallCount("EnableBold") != 1 {
+ t.Errorf("expected 1 EnableBold, got %d", mock.CallCount("EnableBold"))
+ }
+ if mock.CallCount("DisableBold") != 1 {
+ t.Errorf("expected 1 DisableBold, got %d", mock.CallCount("DisableBold"))
+ }
+ })
+}
+
+func TestApplyTextStyle_Sizes(t *testing.T) {
+ mock := service.NewMockPrinter()
+ exec := NewExecutor(mock)
+
+ sizes := []string{
+ constants.Normal.String(),
+ constants.Double.String(),
+ constants.Triple.String(),
+ constants.Quad.String(),
+ constants.Penta.String(),
+ constants.Hexa.String(),
+ constants.Hepta.String(),
+ constants.Octa.String(),
+ "2x3",
+ "9x9",
+ "invalid",
+ }
+
+ for _, sz := range sizes {
+ t.Run(sz, func(t *testing.T) {
+ mock.Reset()
+ style := &TextStyle{Size: &sz}
+ if err := exec.applyTextStyle(mock, style); err != nil {
+ t.Fatalf("applyTextStyle failed for size %s: %v", sz, err)
+ }
+ })
+ }
+}
+
+func TestApplyTextStyle_UnderlineFontAlignInverse(t *testing.T) {
+ mock := service.NewMockPrinter()
+ exec := NewExecutor(mock)
+
+ t.Run("underlines", func(t *testing.T) {
+ for _, u := range []string{constants.NoDot.String(), constants.OneDot.String(), constants.TwoDot.String(), "unknown"} {
+ mock.Reset()
+ style := &TextStyle{Underline: &u}
+ if err := exec.applyTextStyle(mock, style); err != nil {
+ t.Fatalf("applyTextStyle underline %s failed: %v", u, err)
+ }
+ }
+ })
+
+ t.Run("fonts", func(t *testing.T) {
+ for _, f := range []string{"", "a", "b", "c"} {
+ mock.Reset()
+ style := &TextStyle{Font: &f}
+ if err := exec.applyTextStyle(mock, style); err != nil {
+ t.Fatalf("applyTextStyle font %s failed: %v", f, err)
+ }
+ }
+ })
+
+ t.Run("inverses", func(t *testing.T) {
+ for _, inv := range []bool{true, false} {
+ mock.Reset()
+ style := &TextStyle{Inverse: &inv}
+ if err := exec.applyTextStyle(mock, style); err != nil {
+ t.Fatalf("applyTextStyle inverse %v failed: %v", inv, err)
+ }
+ }
+ })
+
+ t.Run("aligns", func(t *testing.T) {
+ for _, a := range []*string{nil, strPtr("left"), strPtr("center"), strPtr("right"), strPtr("other")} {
+ mock.Reset()
+ if err := exec.applyAlign(mock, a); err != nil {
+ t.Fatalf("applyAlign failed: %v", err)
+ }
+ }
+ })
+}
+
+func TestResetDifferingStyles_AllDifferences(t *testing.T) {
+ mock := service.NewMockPrinter()
+ exec := NewExecutor(mock)
+
+ t.Run("nil label style", func(t *testing.T) {
+ if err := exec.resetDifferingStyles(mock, nil, nil); err != nil {
+ t.Errorf("unexpected error: %v", err)
+ }
+ })
+
+ t.Run("nil content style delegates to resetTextStyle", func(t *testing.T) {
+ mock.Reset()
+ b := true
+ labelStyle := &TextStyle{Bold: &b}
+ if err := exec.resetDifferingStyles(mock, labelStyle, nil); err != nil {
+ t.Errorf("unexpected error: %v", err)
+ }
+ if mock.CallCount("DisableBold") != 1 {
+ t.Errorf("expected 1 DisableBold, got %d", mock.CallCount("DisableBold"))
+ }
+ })
+
+ t.Run("all differing fields", func(t *testing.T) {
+ mock.Reset()
+ bTrue := true
+ bFalse := false
+ szDouble := "double"
+ szNormal := "normal"
+ u1 := "1pt"
+ uNone := "none"
+ invTrue := true
+ invFalse := false
+ fontB := "B"
+ fontA := "A"
+
+ label := &TextStyle{
+ Bold: &bTrue,
+ Size: &szDouble,
+ Underline: &u1,
+ Inverse: &invTrue,
+ Font: &fontB,
+ }
+ content := &TextStyle{
+ Bold: &bFalse,
+ Size: &szNormal,
+ Underline: &uNone,
+ Inverse: &invFalse,
+ Font: &fontA,
+ }
+
+ if err := exec.resetDifferingStyles(mock, label, content); err != nil {
+ t.Fatalf("resetDifferingStyles failed: %v", err)
+ }
+ if mock.CallCount("DisableBold") != 1 {
+ t.Errorf("expected 1 DisableBold, got %d", mock.CallCount("DisableBold"))
+ }
+ if mock.CallCount("SingleSize") != 1 {
+ t.Errorf("expected 1 SingleSize, got %d", mock.CallCount("SingleSize"))
+ }
+ if mock.CallCount("NoDot") != 1 {
+ t.Errorf("expected 1 NoDot, got %d", mock.CallCount("NoDot"))
+ }
+ if mock.CallCount("InverseOff") != 1 {
+ t.Errorf("expected 1 InverseOff, got %d", mock.CallCount("InverseOff"))
+ }
+ if mock.CallCount("FontA") != 1 {
+ t.Errorf("expected 1 FontA, got %d", mock.CallCount("FontA"))
+ }
+ })
+}
+
+func TestResetTextStyle_FullReset(t *testing.T) {
+ mock := service.NewMockPrinter()
+ exec := NewExecutor(mock)
+
+ t.Run("nil style", func(t *testing.T) {
+ if err := exec.resetTextStyle(mock, nil); err != nil {
+ t.Errorf("unexpected error: %v", err)
+ }
+ })
+
+ t.Run("all fields populated", func(t *testing.T) {
+ mock.Reset()
+ b := true
+ sz := "double"
+ u := "1pt"
+ inv := true
+ f := "B"
+ style := &TextStyle{
+ Bold: &b,
+ Size: &sz,
+ Underline: &u,
+ Inverse: &inv,
+ Font: &f,
+ }
+
+ if err := exec.resetTextStyle(mock, style); err != nil {
+ t.Fatalf("resetTextStyle failed: %v", err)
+ }
+ if mock.CallCount("DisableBold") != 1 {
+ t.Errorf("expected 1 DisableBold, got %d", mock.CallCount("DisableBold"))
+ }
+ if mock.CallCount("SingleSize") != 1 {
+ t.Errorf("expected 1 SingleSize, got %d", mock.CallCount("SingleSize"))
+ }
+ if mock.CallCount("NoDot") != 1 {
+ t.Errorf("expected 1 NoDot, got %d", mock.CallCount("NoDot"))
+ }
+ if mock.CallCount("InverseOff") != 1 {
+ t.Errorf("expected 1 InverseOff, got %d", mock.CallCount("InverseOff"))
+ }
+ if mock.CallCount("FontA") != 1 {
+ t.Errorf("expected 1 FontA, got %d", mock.CallCount("FontA"))
+ }
+ })
+}
diff --git a/pkg/document/schema/schema.go b/pkg/document/schema/schema.go
index ae0ecf7..eb980ef 100644
--- a/pkg/document/schema/schema.go
+++ b/pkg/document/schema/schema.go
@@ -9,8 +9,6 @@ import (
"github.com/adcondev/poster/pkg/constants"
)
-// TODO: Define all_mayus y all_bold options for commands
-
// Document representa un documento de impresión completo
type Document struct {
Version string `json:"version"` // Requerido: >1.0
@@ -33,8 +31,6 @@ type ProfileConfig struct {
HasQR bool `json:"has_qr,omitempty"` // Default: false
}
-// TODO: Define an order field for reordering or grouping commands. Check if it's worth it.
-
// Command represents a single command in the document
type Command struct {
Type string `json:"type"` // Tipo de comando
@@ -102,7 +98,6 @@ func ParseDocument(data []byte) (*Document, error) {
// Validación básica
if doc.Version == "" {
- // TODO: Review an smart way to handle versioning
doc.Version = constants.DefaultVersion
}
diff --git a/pkg/emulator/emulator_engine.go b/pkg/emulator/emulator_engine.go
index 3a9e1bc..34fec47 100644
--- a/pkg/emulator/emulator_engine.go
+++ b/pkg/emulator/emulator_engine.go
@@ -46,9 +46,6 @@ func NewEngine(config Config) (*Engine, error) {
// Create canvas
canvas := NewDynamicCanvas(config.PaperPxWidth)
- // TODO: Remove later - for debugging font embedding issues
- // emfonts.DiagnoseEmbedding()
-
// Create font manager and load fonts
fonts := NewFontManager()
diff --git a/pkg/emulator/fonts/embed_test.go b/pkg/emulator/fonts/embed_test.go
new file mode 100644
index 0000000..907abf9
--- /dev/null
+++ b/pkg/emulator/fonts/embed_test.go
@@ -0,0 +1,49 @@
+package fonts_test
+
+import (
+ "testing"
+
+ "github.com/adcondev/poster/pkg/emulator/fonts"
+)
+
+func TestFonts_Embedding(t *testing.T) {
+ // HasEmbeddedFonts
+ if !fonts.HasEmbeddedFonts() {
+ t.Fatal("HasEmbeddedFonts() returned false, expected true")
+ }
+
+ // ListFonts
+ fontList := fonts.ListFonts()
+ if len(fontList) == 0 {
+ t.Fatal("ListFonts() returned empty list")
+ }
+
+ foundJetBrains := false
+ for _, f := range fontList {
+ if f == "JetBrainsMono-Bold.ttf" {
+ foundJetBrains = true
+ break
+ }
+ }
+ if !foundJetBrains {
+ t.Errorf("ListFonts() = %v, expected to contain \"JetBrainsMono-Bold.ttf\"", fontList)
+ }
+
+ // LoadFontData valid
+ data, err := fonts.LoadFontData("JetBrainsMono-Bold.ttf")
+ if err != nil {
+ t.Fatalf("LoadFontData() unexpected error = %v", err)
+ }
+ if len(data) == 0 {
+ t.Fatal("LoadFontData() returned empty data")
+ }
+
+ // LoadFontData non-existent
+ _, err = fonts.LoadFontData("NonExistentFont.ttf")
+ if err == nil {
+ t.Fatal("LoadFontData() expected error for non-existent font, got nil")
+ }
+
+ // DiagnoseEmbedding
+ fonts.DiagnoseEmbedding()
+}
diff --git a/pkg/emulator/printer_adapter_test.go b/pkg/emulator/printer_adapter_test.go
index 5cafcc8..c2db911 100644
--- a/pkg/emulator/printer_adapter_test.go
+++ b/pkg/emulator/printer_adapter_test.go
@@ -378,3 +378,226 @@ func TestPrinter_RenderPNGAndSavePNG(t *testing.T) {
t.Error("saved file bytes do not match RenderPNG bytes")
}
}
+
+func TestPrinter_CustomSizes(t *testing.T) {
+ p, err := NewPrinter(nil)
+ if err != nil {
+ t.Fatalf("NewPrinter failed: %v", err)
+ }
+
+ // CustomSize normal
+ if err := p.CustomSize(3, 5); err != nil {
+ t.Errorf("CustomSize(3, 5) error = %v", err)
+ }
+ if st := p.Engine().State(); st.ScaleW != 3.0 || st.ScaleH != 5.0 {
+ t.Errorf("CustomSize scale = (%v, %v), want (3.0, 5.0)", st.ScaleW, st.ScaleH)
+ }
+
+ // CustomSize clamping below 1
+ if err := p.CustomSize(0, 0); err != nil {
+ t.Errorf("CustomSize(0, 0) error = %v", err)
+ }
+ if st := p.Engine().State(); st.ScaleW != 1.0 || st.ScaleH != 1.0 {
+ t.Errorf("CustomSize(0, 0) scale = (%v, %v), want (1.0, 1.0)", st.ScaleW, st.ScaleH)
+ }
+
+ // CustomSize clamping above 8
+ if err := p.CustomSize(12, 12); err != nil {
+ t.Errorf("CustomSize(12, 12) error = %v", err)
+ }
+ if st := p.Engine().State(); st.ScaleW != 8.0 || st.ScaleH != 8.0 {
+ t.Errorf("CustomSize(12, 12) scale = (%v, %v), want (8.0, 8.0)", st.ScaleW, st.ScaleH)
+ }
+}
+
+func TestPrinter_UnderlineAndInverse(t *testing.T) {
+ p, err := NewPrinter(nil)
+ if err != nil {
+ t.Fatalf("NewPrinter failed: %v", err)
+ }
+
+ if err := p.OneDot(); err != nil {
+ t.Errorf("OneDot() error = %v", err)
+ }
+ if p.Engine().State().IsUnderline != 1 {
+ t.Errorf("IsUnderline = %d, want 1", p.Engine().State().IsUnderline)
+ }
+
+ if err := p.TwoDot(); err != nil {
+ t.Errorf("TwoDot() error = %v", err)
+ }
+ if p.Engine().State().IsUnderline != 2 {
+ t.Errorf("IsUnderline = %d, want 2", p.Engine().State().IsUnderline)
+ }
+
+ if err := p.NoDot(); err != nil {
+ t.Errorf("NoDot() error = %v", err)
+ }
+ if p.Engine().State().IsUnderline != 0 {
+ t.Errorf("IsUnderline = %d, want 0", p.Engine().State().IsUnderline)
+ }
+
+ if err := p.InverseOn(); err != nil {
+ t.Errorf("InverseOn() error = %v", err)
+ }
+ if !p.Engine().State().IsInverse {
+ t.Error("IsInverse = false, want true")
+ }
+
+ if err := p.InverseOff(); err != nil {
+ t.Errorf("InverseOff() error = %v", err)
+ }
+ if p.Engine().State().IsInverse {
+ t.Error("IsInverse = true, want false")
+ }
+}
+
+func TestPrinter_AlignmentAndCuts(t *testing.T) {
+ p, err := NewPrinter(nil)
+ if err != nil {
+ t.Fatalf("NewPrinter failed: %v", err)
+ }
+
+ alignments := []struct {
+ input string
+ want string
+ }{
+ {"left", "left"},
+ {"center", "center"},
+ {"right", "right"},
+ {" CENTER ", "center"},
+ }
+ for _, tt := range alignments {
+ if err := p.SetAlignment(tt.input); err != nil {
+ t.Errorf("SetAlignment(%q) error = %v", tt.input, err)
+ }
+ if got := p.Engine().State().Align; got != tt.want {
+ t.Errorf("Align = %q, want %q", got, tt.want)
+ }
+ }
+ if err := p.SetAlignment("unknown"); err == nil {
+ t.Error("SetAlignment(\"unknown\") expected error, got nil")
+ }
+
+ if err := p.PartialFeedAndCut(2); err != nil {
+ t.Errorf("PartialFeedAndCut(2) error = %v", err)
+ }
+ if err := p.PartialFeedAndCut(0); err != nil {
+ t.Errorf("PartialFeedAndCut(0) error = %v", err)
+ }
+ if err := p.FullFeedAndCut(0); err != nil {
+ t.Errorf("FullFeedAndCut(0) error = %v", err)
+ }
+}
+
+func TestPrinter_MiscAndProfile(t *testing.T) {
+ prof := &profile.Escpos{
+ DotsPerLine: 0, // tests default fallback
+ DPI: 0, // tests default fallback
+ }
+ p, err := NewPrinter(prof)
+ if err != nil {
+ t.Fatalf("NewPrinter(prof) error = %v", err)
+ }
+
+ if p.Engine() == nil {
+ t.Fatal("p.Engine() returned nil")
+ }
+ if p.GetProfile() == nil {
+ t.Fatal("p.GetProfile() returned nil")
+ }
+
+ if err := p.Pulse(0, 0, 0); err != nil {
+ t.Errorf("Pulse() error = %v", err)
+ }
+ if err := p.Beep(0, 0); err != nil {
+ t.Errorf("Beep() error = %v", err)
+ }
+ if err := p.SetLineSpacing(30); err != nil {
+ t.Errorf("SetLineSpacing() error = %v", err)
+ }
+ if err := p.SelectDefaultLineSpacing(); err != nil {
+ t.Errorf("SelectDefaultLineSpacing() error = %v", err)
+ }
+
+ if err := p.SetCodeTable(character.WPC1252); err != nil {
+ t.Errorf("SetCodeTable() error = %v", err)
+ }
+ if p.GetProfile().CodeTable != character.WPC1252 {
+ t.Errorf("CodeTable = %v, want WPC1252", p.GetProfile().CodeTable)
+ }
+}
+
+func TestPrinter_GraphicsAndErrors(t *testing.T) {
+ p, err := NewPrinter(nil)
+ if err != nil {
+ t.Fatalf("NewPrinter failed: %v", err)
+ }
+
+ // PrintBitmap success
+ bmp := graphics.NewMonochromeBitmap(16, 16)
+ if err := p.PrintBitmap(bmp); err != nil {
+ t.Errorf("PrintBitmap() error = %v", err)
+ }
+
+ // PrintBitmap nil error
+ if err := p.PrintBitmap(nil); err == nil {
+ t.Error("PrintBitmap(nil) expected error, got nil")
+ }
+
+ // PrintBarcode empty error
+ if err := p.PrintBarcode(graphics.BarcodeConfig{}, nil); err == nil {
+ t.Error("PrintBarcode(nil) expected error, got nil")
+ }
+
+ // PrintQR success
+ if err := p.PrintQR("https://example.com", nil); err != nil {
+ t.Errorf("PrintQR() error = %v", err)
+ }
+}
+
+func TestEngine_AdditionalCoverage(t *testing.T) {
+ eng, err := NewDefaultEngine()
+ if err != nil {
+ t.Fatalf("NewDefaultEngine failed: %v", err)
+ }
+
+ // PrintWrapped
+ eng.PrintWrapped("Short line")
+ eng.PrintWrapped("This is a much longer line of text designed to wrap across lines on the receipt paper width.")
+ eng.PrintWrapped("")
+
+ // HorizontalLine
+ eng.HorizontalLine(2)
+
+ // EnableDebug
+ eng.EnableDebug()
+
+ // DefaultTextStyle
+ style := DefaultTextStyle()
+ if style.ScaleW != 1.0 || style.ScaleH != 1.0 {
+ t.Errorf("DefaultTextStyle Scale = (%v, %v), want (1.0, 1.0)", style.ScaleW, style.ScaleH)
+ }
+
+ // DynamicCanvas methods
+ if w := eng.canvas.Width(); w <= 0 {
+ t.Errorf("canvas.Width() = %d, want > 0", w)
+ }
+
+ // State methods
+ if w := eng.state.GetCharWidth(12.0); w <= 0 {
+ t.Errorf("GetCharWidth(12.0) = %v, want > 0", w)
+ }
+ if h := eng.state.GetCharHeight(24.0); h <= 0 {
+ t.Errorf("GetCharHeight(24.0) = %v, want > 0", h)
+ }
+ if cpl := eng.state.CharsPerLine(0); cpl != 0 {
+ t.Errorf("CharsPerLine(0) = %d, want 0", cpl)
+ }
+
+ // State NewLine
+ eng.state.NewLine(FontMetrics{LineHeight: 24})
+
+ // TextRenderer Feed
+ eng.textRenderer.Feed(2)
+}
diff --git a/pkg/emulator/render_text.go b/pkg/emulator/render_text.go
index a540821..09f0a13 100644
--- a/pkg/emulator/render_text.go
+++ b/pkg/emulator/render_text.go
@@ -98,11 +98,6 @@ func (tr *TextRenderer) RenderLine(text string) {
tr.NewLine()
}
-// FIXME: The NewLine method now directly manipulates cursor position instead of delegating to PrinterState.NewLine(metrics).
-// This duplicates line height calculation logic.
-// Consider whether the PrinterState.NewLine method should also be updated to use GetScaledMetrics,
-// or if this logic should remain centralized in one place.
-
// NewLine moves to the beginning of the next line
func (tr *TextRenderer) NewLine() {
metrics := tr.fonts.GetScaledMetrics(tr.state.FontName, tr.state.ScaleW, tr.state.ScaleH)
@@ -190,8 +185,6 @@ func (tr *TextRenderer) drawChar(char rune, x, y float64, col color.Color) {
)
}
-// FIXME: The WrapText method now calculates charsPerLine directly instead of using state.CharsPerLine(charWidth).
-
// WrapText wraps text to fit within paper width and renders each line
func (tr *TextRenderer) WrapText(text string) {
metrics := tr.fonts.GetScaledMetrics(tr.state.FontName, tr.state.ScaleW, tr.state.ScaleH)
diff --git a/pkg/graphics/barcode_test.go b/pkg/graphics/barcode_test.go
new file mode 100644
index 0000000..1352046
--- /dev/null
+++ b/pkg/graphics/barcode_test.go
@@ -0,0 +1,191 @@
+package graphics_test
+
+import (
+ "testing"
+
+ "github.com/adcondev/poster/pkg/commands/barcode"
+ "github.com/adcondev/poster/pkg/constants"
+ "github.com/adcondev/poster/pkg/graphics"
+)
+
+func TestMapSymbology(t *testing.T) {
+ tests := []struct {
+ input string
+ expected barcode.Symbology
+ wantErr bool
+ }{
+ {"upca", barcode.UPCA, false},
+ {"UPC-A", barcode.UPCA, false},
+ {"upce", barcode.UPCE, false},
+ {"UPC-E", barcode.UPCE, false},
+ {"ean13", barcode.EAN13, false},
+ {"EAN-13", barcode.EAN13, false},
+ {"ean8", barcode.EAN8, false},
+ {"EAN-8", barcode.EAN8, false},
+ {"code39", barcode.CODE39, false},
+ {"CODE-39", barcode.CODE39, false},
+ {"itf", barcode.ITF, false},
+ {"codabar", barcode.CODABAR, false},
+ {"code128", barcode.CODE128, false},
+ {"CODE-128", barcode.CODE128, false},
+ {"jan13", barcode.EAN13, false},
+ {"JAN-13", barcode.EAN13, false},
+ {"jan8", barcode.EAN8, false},
+ {"JAN-8", barcode.EAN8, false},
+ {"code93", barcode.CODE93, false},
+ {"code-93", barcode.CODE93, false},
+ {"CODE_93", barcode.CODE93, false},
+ {"gs1_128", barcode.GS1128, false},
+ {"gs1-128", barcode.GS1128, false},
+ {"gs1128", barcode.GS1128, false},
+ {"code128_auto", barcode.CODE128Auto, false},
+ {"code128-auto", barcode.CODE128Auto, false},
+ {"code128auto", barcode.CODE128Auto, false},
+ // Invalid / unsupported
+ {"unsupported_sym", 0, true},
+ {"", 0, true},
+ {"qr_code", 0, true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.input, func(t *testing.T) {
+ got, err := graphics.MapSymbology(tt.input)
+ if (err != nil) != tt.wantErr {
+ t.Fatalf("MapSymbology(%q) error = %v, wantErr %v", tt.input, err, tt.wantErr)
+ }
+ if !tt.wantErr && got != tt.expected {
+ t.Errorf("MapSymbology(%q) = %v, want %v", tt.input, got, tt.expected)
+ }
+ })
+ }
+}
+
+func TestMapHriPosition(t *testing.T) {
+ tests := []struct {
+ input string
+ expected barcode.HRIPosition
+ wantErr bool
+ }{
+ {"none", barcode.HRINotPrinted, false},
+ {"NONE", barcode.HRINotPrinted, false},
+ {"above", barcode.HRIAbove, false},
+ {"ABOVE", barcode.HRIAbove, false},
+ {"below", barcode.HRIBelow, false},
+ {"BELOW", barcode.HRIBelow, false},
+ {"both", barcode.HRIBoth, false},
+ {"BOTH", barcode.HRIBoth, false},
+ {"invalid", 0, true},
+ {"", 0, true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.input, func(t *testing.T) {
+ got, err := graphics.MapHriPosition(tt.input)
+ if (err != nil) != tt.wantErr {
+ t.Fatalf("MapHriPosition(%q) error = %v, wantErr %v", tt.input, err, tt.wantErr)
+ }
+ if !tt.wantErr && got != tt.expected {
+ t.Errorf("MapHriPosition(%q) = %v, want %v", tt.input, got, tt.expected)
+ }
+ })
+ }
+}
+
+func TestMapHriFont(t *testing.T) {
+ tests := []struct {
+ input string
+ expected barcode.HRIFont
+ wantErr bool
+ }{
+ {"A", barcode.HRIFontA, false},
+ {"a", barcode.HRIFontA, false},
+ {"B", barcode.HRIFontB, false},
+ {"b", barcode.HRIFontB, false},
+ {"C", 0, true},
+ {"", 0, true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.input, func(t *testing.T) {
+ got, err := graphics.MapHriFont(tt.input)
+ if (err != nil) != tt.wantErr {
+ t.Fatalf("MapHriFont(%q) error = %v, wantErr %v", tt.input, err, tt.wantErr)
+ }
+ if !tt.wantErr && got != tt.expected {
+ t.Errorf("MapHriFont(%q) = %v, want %v", tt.input, got, tt.expected)
+ }
+ })
+ }
+}
+
+func TestIntToBarcodeModuleWidth(t *testing.T) {
+ tests := []struct {
+ name string
+ input int
+ expected barcode.Width
+ }{
+ {"below min", 0, barcode.MinWidth},
+ {"negative", -5, barcode.MinWidth},
+ {"min bound", constants.MinBarcodeModuleWidth, barcode.MinWidth},
+ {"in range 3", 3, barcode.Width(3)},
+ {"in range 4", 4, barcode.Width(4)},
+ {"max bound", constants.MaxBarcodeModuleWidth, barcode.MaxWidth},
+ {"above max", 10, barcode.MaxWidth},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := graphics.IntToBarcodeModuleWidth(tt.input)
+ if got != tt.expected {
+ t.Errorf("IntToBarcodeModuleWidth(%d) = %v, want %v", tt.input, got, tt.expected)
+ }
+ })
+ }
+}
+
+func TestIntToBarcodeHeight(t *testing.T) {
+ tests := []struct {
+ name string
+ input int
+ expected barcode.Height
+ }{
+ {"below min", 0, barcode.MinHeight},
+ {"negative", -10, barcode.MinHeight},
+ {"min bound", constants.MinBarcodeHeight, barcode.MinHeight},
+ {"in range 80", 80, barcode.Height(80)},
+ {"in range 162", 162, barcode.Height(162)},
+ {"max bound", constants.MaxBarcodeHeight, barcode.MaxHeight},
+ {"above max", 300, barcode.MaxHeight},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := graphics.IntToBarcodeHeight(tt.input)
+ if got != tt.expected {
+ t.Errorf("IntToBarcodeHeight(%d) = %v, want %v", tt.input, got, tt.expected)
+ }
+ })
+ }
+}
+
+func TestDefaultBarcodeConfig(t *testing.T) {
+ cfg := graphics.DefaultBarcodeConfig()
+ if cfg.Symbology != barcode.CODE128 {
+ t.Errorf("expected default symbology CODE128, got %v", cfg.Symbology)
+ }
+ if cfg.Width != barcode.Width(constants.DefaultBarcodeModuleWidth) {
+ t.Errorf("expected default width %d, got %v", constants.DefaultBarcodeModuleWidth, cfg.Width)
+ }
+ if cfg.Height != barcode.Height(constants.DefaultBarcodeHeight) {
+ t.Errorf("expected default height %d, got %v", constants.DefaultBarcodeHeight, cfg.Height)
+ }
+ if cfg.HRIPosition != barcode.HRIBelow {
+ t.Errorf("expected default HRIPosition HRIBelow, got %v", cfg.HRIPosition)
+ }
+ if cfg.HRIFont != barcode.HRIFontA {
+ t.Errorf("expected default HRIFont HRIFontA, got %v", cfg.HRIFont)
+ }
+ if cfg.CodeSet != barcode.Code128SetB {
+ t.Errorf("expected default CodeSet Code128SetB, got %v", cfg.CodeSet)
+ }
+}
diff --git a/pkg/graphics/graph_engine.go b/pkg/graphics/graph_engine.go
index 4785757..2f2f1af 100644
--- a/pkg/graphics/graph_engine.go
+++ b/pkg/graphics/graph_engine.go
@@ -117,8 +117,6 @@ func (p *Pipeline) Process(img image.Image) (*MonochromeBitmap, error) {
return mono, nil
}
-// TODO: Consider supporting other scaling algorithms (e.g., NN, Lanczos, Catmull-Rom) for even better quality or performance tuning.
-
// resize scales (up or down) the image to target width maintaining aspect ratio
func (p *Pipeline) resize(img image.Image) image.Image {
maxWidth := p.opts.MaxWidth
diff --git a/pkg/graphics/loaders_test.go b/pkg/graphics/loaders_test.go
new file mode 100644
index 0000000..90aab43
--- /dev/null
+++ b/pkg/graphics/loaders_test.go
@@ -0,0 +1,115 @@
+package graphics_test
+
+import (
+ "bytes"
+ "encoding/base64"
+ "image"
+ "image/color"
+ "image/png"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/adcondev/poster/pkg/graphics"
+)
+
+func createSamplePNGBytes(t *testing.T) []byte {
+ t.Helper()
+ img := image.NewRGBA(image.Rect(0, 0, 10, 10))
+ for y := 0; y < 10; y++ {
+ for x := 0; x < 10; x++ {
+ img.Set(x, y, color.RGBA{R: 255, G: 0, B: 0, A: 255})
+ }
+ }
+ var buf bytes.Buffer
+ if err := png.Encode(&buf, img); err != nil {
+ t.Fatalf("failed to encode sample png: %v", err)
+ }
+ return buf.Bytes()
+}
+
+func TestLoadImageFromFile(t *testing.T) {
+ tempDir := t.TempDir()
+ pngData := createSamplePNGBytes(t)
+ fileName := "sample.png"
+ fullPath := filepath.Join(tempDir, fileName)
+
+ if err := os.WriteFile(fullPath, pngData, 0600); err != nil {
+ t.Fatalf("failed to write sample png: %v", err)
+ }
+
+ t.Run("valid file", func(t *testing.T) {
+ img, _, err := graphics.LoadImageFromFile(tempDir, fileName)
+ if err != nil {
+ t.Fatalf("LoadImageFromFile failed: %v", err)
+ }
+ if img == nil {
+ t.Fatal("expected non-nil image")
+ }
+ if img.Bounds().Dx() != 10 || img.Bounds().Dy() != 10 {
+ t.Errorf("image dimensions = %dx%d, want 10x10", img.Bounds().Dx(), img.Bounds().Dy())
+ }
+ })
+
+ t.Run("non-existent file", func(t *testing.T) {
+ _, _, err := graphics.LoadImageFromFile(tempDir, "missing.png")
+ if err == nil {
+ t.Error("expected error for missing file, got nil")
+ }
+ })
+
+ t.Run("directory traversal attempt", func(t *testing.T) {
+ _, _, err := graphics.LoadImageFromFile(tempDir, "../../../etc/passwd")
+ if err == nil {
+ t.Error("expected error for path traversal, got nil")
+ }
+ })
+}
+
+func TestLoadImageFromBase64(t *testing.T) {
+ pngData := createSamplePNGBytes(t)
+ rawB64 := base64.StdEncoding.EncodeToString(pngData)
+ dataURIB64 := "data:image/png;base64," + rawB64
+
+ t.Run("raw base64 string", func(t *testing.T) {
+ img, format, err := graphics.LoadImageFromBase64(rawB64)
+ if err != nil {
+ t.Fatalf("LoadImageFromBase64 failed: %v", err)
+ }
+ if img == nil {
+ t.Fatal("expected non-nil image")
+ }
+ if format != "png" {
+ t.Errorf("format = %q, want png", format)
+ }
+ })
+
+ t.Run("data URI base64 string rejected", func(t *testing.T) {
+ _, _, err := graphics.LoadImageFromBase64(dataURIB64)
+ if err == nil {
+ t.Error("expected error for data URI prefix in LoadImageFromBase64, got nil")
+ }
+ })
+
+ t.Run("empty string error", func(t *testing.T) {
+ _, _, err := graphics.LoadImageFromBase64("")
+ if err == nil {
+ t.Error("expected error for empty base64 string, got nil")
+ }
+ })
+
+ t.Run("invalid base64 content error", func(t *testing.T) {
+ _, _, err := graphics.LoadImageFromBase64("this-is-not-valid-base64!@#$")
+ if err == nil {
+ t.Error("expected error for corrupt base64 string, got nil")
+ }
+ })
+
+ t.Run("corrupt image payload error", func(t *testing.T) {
+ corrupt := base64.StdEncoding.EncodeToString([]byte("not an image"))
+ _, _, err := graphics.LoadImageFromBase64(corrupt)
+ if err == nil {
+ t.Error("expected error for corrupt image payload, got nil")
+ }
+ })
+}
diff --git a/pkg/graphics/qr.go b/pkg/graphics/qr.go
index 6ed9328..6e86c20 100644
--- a/pkg/graphics/qr.go
+++ b/pkg/graphics/qr.go
@@ -28,11 +28,7 @@ const (
maxSizeMulti = 5
)
-// TODO: Check if /internals fits better for custom WriteCloser
-
// WriteCloser wraps bytes.Buffer to implement io.WriteCloser
-// FIXME: /internals fits better for custom WriteCloser?
-// TODO: Consider naming this BufferWriteCloser or similar for clarity.
type WriteCloser struct {
buffer *bytes.Buffer
}
@@ -54,7 +50,6 @@ func (wc *WriteCloser) Close() error {
// NO hacer Reset() aquí porque perdemos los datos antes de leerlos
// El defer en ProcessQRImage llama a Close() DESPUÉS de usar Save()
// pero ANTES de leer los bytes con Bytes()
- // FIXME: Empty Close method might indicate a design smell or need for better abstraction.
return nil
}
@@ -134,8 +129,6 @@ func (qo *QrOptions) GetModuleSize() posqr.ModuleSize {
}
// GenerateQR calcula y establece el tamaño del módulo basado en PixelWidth y el tamaño de la cuadrícula del QR
-// TODO: GenerateQR modifies QrOptions struct (side effects). Consider returning a result struct or modified copy.
-// TODO: Break down complex methods further if possible.
func (qo *QrOptions) GenerateQR(data string) (*qrcode.QRCode, error) {
if data == "" {
return nil, fmt.Errorf("QR data cannot be empty")
@@ -145,9 +138,6 @@ func (qo *QrOptions) GenerateQR(data string) (*qrcode.QRCode, error) {
len(data), posqr.MaxDataLength)
}
- // FIXME: === Check if encoding affects QR Code whether is printed as image or natively ===
-
- // TODO: Validate/clamp PixelWidth explicitly returning errors instead of silent adjustment?
qo.validateAndAdjustPixelWidth()
if qo.ErrorCorrection < posqr.LevelL || qo.ErrorCorrection > posqr.LevelH {
@@ -246,8 +236,6 @@ func (qo *QrOptions) calculateFinalDimensions() {
func (qo *QrOptions) loadLogo() {
if qo.LogoData != "" {
// Load images if base64 strings are provided
- // FIXME: Define a single place where to load images from base64
- // TODO: Optimize Base64 handling? Decoding images here might be slow if repeated.
logoImg, format, err := load.ImgFromBase64(qo.LogoData)
if err != nil {
qo.LogoData = ""
@@ -275,7 +263,6 @@ func ProcessQRImage(data string, opts *QrOptions) (image.Image, error) {
// grande que el solicitado, preferir generado y no escalar hacia abajo.
// Generar QR y calcular tamaño del módulo
- // TODO: Error Handling: GenerateQR modifies opts. If it fails partially, opts might be inconsistent.
qrc, err := opts.GenerateQR(data)
if err != nil {
return nil, fmt.Errorf("set module size: %w", err)
@@ -309,7 +296,6 @@ func ProcessQRImage(data string, opts *QrOptions) (image.Image, error) {
}
// mapLogoSize calcula el tamaño óptimo del Logo basado en corrección
-// TODO: Avoid magic numbers (7, 6, 5, 4). Define constants for these ratios.
func mapLogoSize(errorCorrection posqr.ErrorCorrection) int {
switch errorCorrection {
case posqr.LevelL:
@@ -423,13 +409,3 @@ func ScaleImageToWidth(img image.Image, targetWidth int) image.Image {
return dst
}
-/*
-var ecMap = map[string]posqr.ErrorCorrection{
- constants.L.String(): posqr.LevelL,
- constants.M.String(): posqr.LevelM,
- constants.Q.String(): posqr.LevelQ,
- constants.H.String(): posqr.LevelH,
-}
-*/
-
-// TODO: Add error correction mapping
diff --git a/pkg/graphics/qr_test.go b/pkg/graphics/qr_test.go
new file mode 100644
index 0000000..afd44b3
--- /dev/null
+++ b/pkg/graphics/qr_test.go
@@ -0,0 +1,579 @@
+package graphics
+
+import (
+ "bytes"
+ "encoding/base64"
+ "image"
+ "image/color"
+ "image/jpeg"
+ "image/png"
+ "strings"
+ "testing"
+
+ posqr "github.com/adcondev/poster/pkg/commands/qrcode"
+ "github.com/adcondev/poster/pkg/constants"
+)
+
+func createTestPNG(t *testing.T, w, h int) (image.Image, string) {
+ t.Helper()
+ img := image.NewRGBA(image.Rect(0, 0, w, h))
+ for y := 0; y < h; y++ {
+ for x := 0; x < w; x++ {
+ img.Set(x, y, color.RGBA{R: 200, G: 100, B: 50, A: 255})
+ }
+ }
+ var buf bytes.Buffer
+ if err := png.Encode(&buf, img); err != nil {
+ t.Fatalf("png encode failed: %v", err)
+ }
+ return img, base64.StdEncoding.EncodeToString(buf.Bytes())
+}
+
+func createTestJPEG(t *testing.T, w, h int) (image.Image, string) {
+ t.Helper()
+ img := image.NewRGBA(image.Rect(0, 0, w, h))
+ for y := 0; y < h; y++ {
+ for x := 0; x < w; x++ {
+ img.Set(x, y, color.RGBA{R: 50, G: 100, B: 200, A: 255})
+ }
+ }
+ var buf bytes.Buffer
+ if err := jpeg.Encode(&buf, img, nil); err != nil {
+ t.Fatalf("jpeg encode failed: %v", err)
+ }
+ return img, base64.StdEncoding.EncodeToString(buf.Bytes())
+}
+
+func TestWriteCloser(t *testing.T) {
+ wc := NewWriteCloser()
+ if wc == nil {
+ t.Fatal("NewWriteCloser returned nil")
+ }
+
+ testData := []byte("hello qr world")
+ n, err := wc.Write(testData)
+ if err != nil {
+ t.Fatalf("Write returned error: %v", err)
+ }
+ if n != len(testData) {
+ t.Errorf("Write n = %d, want %d", n, len(testData))
+ }
+
+ if !bytes.Equal(wc.Bytes(), testData) {
+ t.Errorf("Bytes() = %s, want %s", wc.Bytes(), testData)
+ }
+
+ if err := wc.Close(); err != nil {
+ t.Errorf("Close() returned error: %v", err)
+ }
+
+ // Close must not reset buffer
+ if !bytes.Equal(wc.Bytes(), testData) {
+ t.Errorf("Bytes() after Close() = %s, want %s", wc.Bytes(), testData)
+ }
+
+ wc.Reset()
+ if len(wc.Bytes()) != 0 {
+ t.Errorf("Bytes() after Reset() = %d bytes, want 0", len(wc.Bytes()))
+ }
+}
+
+func TestDefaultQROptions(t *testing.T) {
+ opts := DefaultQROptions()
+ if opts == nil {
+ t.Fatal("DefaultQROptions returned nil")
+ }
+ if opts.Model != posqr.Model2 {
+ t.Errorf("Model = %v, want %v", opts.Model, posqr.Model2)
+ }
+ if opts.ErrorCorrection != posqr.LevelM {
+ t.Errorf("ErrorCorrection = %v, want %v", opts.ErrorCorrection, posqr.LevelM)
+ }
+ if opts.PixelWidth != 128 {
+ t.Errorf("PixelWidth = %d, want 128", opts.PixelWidth)
+ }
+ if opts.MaxPixelWidth != constants.PaperPxWidth80mm {
+ t.Errorf("MaxPixelWidth = %d, want %d", opts.MaxPixelWidth, constants.PaperPxWidth80mm)
+ }
+ if opts.CircleShape {
+ t.Error("CircleShape = true, want false")
+ }
+ if opts.LogoData != "" {
+ t.Errorf("LogoData = %q, want empty", opts.LogoData)
+ }
+}
+
+func TestQrOptions_GetModuleSize(t *testing.T) {
+ opts := DefaultQROptions()
+ opts.Qr.moduleSize = posqr.ModuleSize(6)
+ if got := opts.GetModuleSize(); got != posqr.ModuleSize(6) {
+ t.Errorf("GetModuleSize() = %v, want 6", got)
+ }
+}
+
+func TestQrOptions_GenerateQR(t *testing.T) {
+ t.Run("empty data error", func(t *testing.T) {
+ opts := DefaultQROptions()
+ _, err := opts.GenerateQR("")
+ if err == nil {
+ t.Error("expected error on empty data, got nil")
+ }
+ })
+
+ t.Run("data too long error", func(t *testing.T) {
+ opts := DefaultQROptions()
+ tooLong := strings.Repeat("A", posqr.MaxDataLength+1)
+ _, err := opts.GenerateQR(tooLong)
+ if err == nil {
+ t.Error("expected error on data too long, got nil")
+ }
+ })
+
+ t.Run("valid QR generation with out-of-range error correction reset", func(t *testing.T) {
+ opts := DefaultQROptions()
+ opts.ErrorCorrection = posqr.ErrorCorrection(99)
+ qrc, err := opts.GenerateQR("https://example.com/poster")
+ if err != nil {
+ t.Fatalf("GenerateQR failed: %v", err)
+ }
+ if qrc == nil {
+ t.Fatal("expected non-nil QRCode")
+ }
+ if opts.ErrorCorrection != posqr.LevelM {
+ t.Errorf("ErrorCorrection = %v, want fallback LevelM", opts.ErrorCorrection)
+ }
+ if opts.Qr.gridSize < minGridSize {
+ t.Errorf("gridSize = %d, want >= %d", opts.Qr.gridSize, minGridSize)
+ }
+ })
+
+ t.Run("valid QR generation with logo data", func(t *testing.T) {
+ _, b64 := createTestPNG(t, 16, 16)
+ opts := DefaultQROptions()
+ opts.LogoData = b64
+ qrc, err := opts.GenerateQR("https://example.com/poster/logo")
+ if err != nil {
+ t.Fatalf("GenerateQR with logo failed: %v", err)
+ }
+ if qrc == nil {
+ t.Fatal("expected non-nil QRCode")
+ }
+ if opts.Logo.Image == nil {
+ t.Fatal("expected non-nil Logo.Image")
+ }
+ if opts.Logo.format != "png" {
+ t.Errorf("Logo format = %q, want png", opts.Logo.format)
+ }
+ })
+}
+
+func TestQrOptions_ValidateAndAdjustPixelWidth(t *testing.T) {
+ t.Run("below minPixelWidth", func(t *testing.T) {
+ opts := DefaultQROptions()
+ opts.PixelWidth = minPixelWidth - 20
+ opts.validateAndAdjustPixelWidth()
+ if opts.PixelWidth != minPixelWidth {
+ t.Errorf("PixelWidth = %d, want %d", opts.PixelWidth, minPixelWidth)
+ }
+ if opts.Qr.requestedWidth != minPixelWidth {
+ t.Errorf("requestedWidth = %d, want %d", opts.Qr.requestedWidth, minPixelWidth)
+ }
+ })
+
+ t.Run("above custom MaxPixelWidth", func(t *testing.T) {
+ opts := DefaultQROptions()
+ opts.MaxPixelWidth = 250
+ opts.PixelWidth = 350
+ opts.validateAndAdjustPixelWidth()
+ if opts.PixelWidth != 250 {
+ t.Errorf("PixelWidth = %d, want 250", opts.PixelWidth)
+ }
+ if opts.Qr.requestedWidth != 250 {
+ t.Errorf("requestedWidth = %d, want 250", opts.Qr.requestedWidth)
+ }
+ })
+
+ t.Run("above default MaxPixelWidth when MaxPixelWidth is 0", func(t *testing.T) {
+ opts := DefaultQROptions()
+ opts.MaxPixelWidth = 0
+ opts.PixelWidth = constants.PaperPxWidth80mm + 100
+ opts.validateAndAdjustPixelWidth()
+ if opts.PixelWidth != constants.PaperPxWidth80mm {
+ t.Errorf("PixelWidth = %d, want %d", opts.PixelWidth, constants.PaperPxWidth80mm)
+ }
+ })
+
+ t.Run("within valid bounds", func(t *testing.T) {
+ opts := DefaultQROptions()
+ opts.PixelWidth = 200
+ opts.validateAndAdjustPixelWidth()
+ if opts.PixelWidth != 200 {
+ t.Errorf("PixelWidth = %d, want 200", opts.PixelWidth)
+ }
+ })
+}
+
+func TestQrOptions_ValidateGridSize(t *testing.T) {
+ opts := DefaultQROptions()
+ opts.Qr.gridSize = minGridSize - 1
+ if err := opts.validateGridSize(); err == nil {
+ t.Error("expected error for gridSize < minGridSize, got nil")
+ }
+
+ opts.Qr.gridSize = minGridSize
+ if err := opts.validateGridSize(); err != nil {
+ t.Errorf("unexpected error for minGridSize: %v", err)
+ }
+}
+
+func TestQrOptions_CalculateModuleSize(t *testing.T) {
+ t.Run("totalModules <= 0 fallback", func(t *testing.T) {
+ opts := DefaultQROptions()
+ opts.Qr.gridSize = -10 // totalModules = -10 + 8 = -2
+ opts.calculateModuleSize()
+ if opts.Qr.moduleSize != posqr.DefaultModuleSize {
+ t.Errorf("moduleSize = %v, want DefaultModuleSize", opts.Qr.moduleSize)
+ }
+ })
+
+ t.Run("rawModSize < DefaultModuleSize", func(t *testing.T) {
+ opts := DefaultQROptions()
+ opts.Qr.gridSize = 177
+ opts.Qr.requestedWidth = minPixelWidth // 87 / (177 + 8) = 0
+ opts.calculateModuleSize()
+ if opts.Qr.moduleSize != posqr.DefaultModuleSize {
+ t.Errorf("moduleSize = %v, want DefaultModuleSize", opts.Qr.moduleSize)
+ }
+ })
+
+ t.Run("rawModSize > MaxModuleSize", func(t *testing.T) {
+ opts := DefaultQROptions()
+ opts.Qr.gridSize = 21
+ opts.Qr.requestedWidth = 1000 // 1000 / 29 = 34 > 16
+ opts.calculateModuleSize()
+ if opts.Qr.moduleSize != posqr.MaxModuleSize {
+ t.Errorf("moduleSize = %v, want MaxModuleSize", opts.Qr.moduleSize)
+ }
+ })
+
+ t.Run("normal rawModSize", func(t *testing.T) {
+ opts := DefaultQROptions()
+ opts.Qr.gridSize = 21
+ opts.Qr.requestedWidth = 200 // 200 / 29 = 6
+ opts.calculateModuleSize()
+ if opts.Qr.moduleSize != posqr.ModuleSize(6) {
+ t.Errorf("moduleSize = %v, want 6", opts.Qr.moduleSize)
+ }
+ })
+}
+
+func TestQrOptions_CalculateFinalDimensions(t *testing.T) {
+ opts := DefaultQROptions()
+ opts.Qr.gridSize = 21
+ opts.Qr.moduleSize = posqr.ModuleSize(4)
+ // totalModules = 21 + 8 = 29; totalWidth = 29 * 4 = 116
+
+ t.Run("scaled_up mode", func(t *testing.T) {
+ opts.Qr.requestedWidth = 100
+ opts.calculateFinalDimensions()
+ if opts.Qr.scaleMode != "scaled_up" {
+ t.Errorf("scaleMode = %q, want scaled_up", opts.Qr.scaleMode)
+ }
+ if opts.Qr.diff != 16 {
+ t.Errorf("diff = %d, want 16", opts.Qr.diff)
+ }
+ })
+
+ t.Run("scaled_down mode", func(t *testing.T) {
+ opts.Qr.requestedWidth = 120
+ opts.calculateFinalDimensions()
+ if opts.Qr.scaleMode != "scaled_down" {
+ t.Errorf("scaleMode = %q, want scaled_down", opts.Qr.scaleMode)
+ }
+ if opts.Qr.diff != -4 {
+ t.Errorf("diff = %d, want -4", opts.Qr.diff)
+ }
+ })
+
+ t.Run("exact mode", func(t *testing.T) {
+ opts.Qr.requestedWidth = 116
+ opts.calculateFinalDimensions()
+ // diff is 0, scaleMode remains unchanged or exact
+ if opts.Qr.totalWidth != 116 {
+ t.Errorf("totalWidth = %d, want 116", opts.Qr.totalWidth)
+ }
+ })
+}
+
+func TestQrOptions_LoadLogo(t *testing.T) {
+ t.Run("empty LogoData", func(t *testing.T) {
+ opts := DefaultQROptions()
+ opts.LogoData = ""
+ opts.loadLogo()
+ if opts.Logo.Image != nil {
+ t.Error("expected Logo.Image to be nil")
+ }
+ })
+
+ t.Run("corrupt LogoData resets to empty", func(t *testing.T) {
+ opts := DefaultQROptions()
+ opts.LogoData = "not-a-valid-base64"
+ opts.loadLogo()
+ if opts.LogoData != "" {
+ t.Errorf("LogoData = %q, want empty after error", opts.LogoData)
+ }
+ if opts.Logo.Image != nil {
+ t.Error("expected Logo.Image to be nil")
+ }
+ })
+
+ t.Run("valid base64 png loads successfully", func(t *testing.T) {
+ _, b64 := createTestPNG(t, 24, 24)
+ opts := DefaultQROptions()
+ opts.LogoData = b64
+ opts.loadLogo()
+ if opts.Logo.Image == nil {
+ t.Fatal("expected Logo.Image to be non-nil")
+ }
+ if opts.Logo.format != "png" {
+ t.Errorf("format = %q, want png", opts.Logo.format)
+ }
+ if opts.Logo.width != 24 || opts.Logo.height != 24 {
+ t.Errorf("dimensions = %dx%d, want 24x24", opts.Logo.width, opts.Logo.height)
+ }
+ })
+}
+
+func TestMapLogoSize(t *testing.T) {
+ tests := []struct {
+ ecl posqr.ErrorCorrection
+ want int
+ }{
+ {posqr.LevelL, 7},
+ {posqr.LevelM, 6},
+ {posqr.LevelQ, 5},
+ {posqr.LevelH, 4},
+ {posqr.ErrorCorrection(99), 5},
+ }
+
+ for _, tt := range tests {
+ if got := mapLogoSize(tt.ecl); got != tt.want {
+ t.Errorf("mapLogoSize(%v) = %d, want %d", tt.ecl, got, tt.want)
+ }
+ }
+}
+
+func TestMapEclOption(t *testing.T) {
+ levels := []posqr.ErrorCorrection{
+ posqr.LevelL,
+ posqr.LevelM,
+ posqr.LevelQ,
+ posqr.LevelH,
+ posqr.ErrorCorrection(100), // default
+ }
+
+ for _, lvl := range levels {
+ opt := mapEclOption(lvl)
+ if opt == nil {
+ t.Errorf("mapEclOption(%v) returned nil", lvl)
+ }
+ }
+}
+
+func TestBuildImageOptions(t *testing.T) {
+ t.Run("without logo, without circle", func(t *testing.T) {
+ opts := DefaultQROptions()
+ opts.Qr.moduleSize = posqr.ModuleSize(4)
+ imgOpts := buildImageOptions(opts)
+ if len(imgOpts) != 2 {
+ t.Errorf("len(imgOpts) = %d, want 2", len(imgOpts))
+ }
+ })
+
+ t.Run("with circle shape", func(t *testing.T) {
+ opts := DefaultQROptions()
+ opts.Qr.moduleSize = posqr.ModuleSize(4)
+ opts.CircleShape = true
+ imgOpts := buildImageOptions(opts)
+ if len(imgOpts) != 3 {
+ t.Errorf("len(imgOpts) = %d, want 3", len(imgOpts))
+ }
+ })
+
+ t.Run("with PNG logo and safe zone", func(t *testing.T) {
+ img, b64 := createTestPNG(t, 20, 20)
+ opts := DefaultQROptions()
+ opts.Qr.moduleSize = posqr.ModuleSize(4)
+ opts.Qr.dataWidth = 84
+ opts.LogoData = b64
+ opts.Logo.Image = img
+ opts.Logo.format = "png"
+ opts.Logo.sizeMulti = 2
+ opts.ErrorCorrection = posqr.LevelM
+
+ imgOpts := buildImageOptions(opts)
+ if len(imgOpts) == 0 {
+ t.Error("expected non-empty image options")
+ }
+ })
+
+ t.Run("with sizeMulti 0 falls back to no logo", func(t *testing.T) {
+ img, b64 := createTestPNG(t, 20, 20)
+ opts := DefaultQROptions()
+ opts.Qr.moduleSize = posqr.ModuleSize(4)
+ opts.Qr.dataWidth = 84
+ opts.LogoData = b64
+ opts.Logo.Image = img
+ opts.Logo.format = "png"
+ opts.Logo.sizeMulti = 0
+
+ imgOpts := buildImageOptions(opts)
+ if opts.LogoData != "" || opts.Logo.Image != nil {
+ t.Error("expected LogoData and Logo.Image to be cleared when sizeMulti is 0")
+ }
+ if len(imgOpts) != 2 {
+ t.Errorf("len(imgOpts) = %d, want 2 (only qr width and border)", len(imgOpts))
+ }
+ })
+
+ t.Run("with JPEG logo and max sizeMulti clamping", func(t *testing.T) {
+ img, b64 := createTestJPEG(t, 30, 30)
+ opts := DefaultQROptions()
+ opts.Qr.moduleSize = posqr.ModuleSize(4)
+ opts.Qr.dataWidth = 100
+ opts.LogoData = b64
+ opts.Logo.Image = img
+ opts.Logo.format = "jpeg"
+ opts.Logo.sizeMulti = 10 // above maxSizeMulti -> clamped to 5
+ opts.ErrorCorrection = posqr.LevelH
+
+ imgOpts := buildImageOptions(opts)
+ if opts.Logo.sizeMulti != maxSizeMulti {
+ t.Errorf("sizeMulti = %d, want %d", opts.Logo.sizeMulti, maxSizeMulti)
+ }
+ if len(imgOpts) == 0 {
+ t.Error("expected non-empty image options")
+ }
+ })
+}
+
+func TestProcessQRImage(t *testing.T) {
+ t.Run("empty data error", func(t *testing.T) {
+ _, err := ProcessQRImage("", nil)
+ if err == nil {
+ t.Error("expected error on empty data, got nil")
+ }
+ })
+
+ t.Run("nil options uses defaults", func(t *testing.T) {
+ img, err := ProcessQRImage("https://example.com/test", nil)
+ if err != nil {
+ t.Fatalf("ProcessQRImage failed with nil options: %v", err)
+ }
+ if img == nil {
+ t.Fatal("expected non-nil image")
+ }
+ if img.Bounds().Dx() == 0 || img.Bounds().Dy() == 0 {
+ t.Errorf("empty image dimensions: %v", img.Bounds())
+ }
+ })
+
+ t.Run("with CircleShape", func(t *testing.T) {
+ opts := DefaultQROptions()
+ opts.CircleShape = true
+ img, err := ProcessQRImage("https://example.com/circle", opts)
+ if err != nil {
+ t.Fatalf("ProcessQRImage with CircleShape failed: %v", err)
+ }
+ if img == nil {
+ t.Fatal("expected non-nil image")
+ }
+ })
+
+ t.Run("with PNG logo", func(t *testing.T) {
+ _, b64 := createTestPNG(t, 16, 16)
+ opts := DefaultQROptions()
+ opts.LogoData = b64
+ opts.ErrorCorrection = posqr.LevelQ
+ img, err := ProcessQRImage("https://example.com/with-logo", opts)
+ if err != nil {
+ t.Fatalf("ProcessQRImage with logo failed: %v", err)
+ }
+ if img == nil {
+ t.Fatal("expected non-nil image")
+ }
+ })
+
+ t.Run("with all error correction levels", func(t *testing.T) {
+ levels := []posqr.ErrorCorrection{
+ posqr.LevelL,
+ posqr.LevelM,
+ posqr.LevelQ,
+ posqr.LevelH,
+ }
+ for _, lvl := range levels {
+ opts := DefaultQROptions()
+ opts.ErrorCorrection = lvl
+ img, err := ProcessQRImage("https://example.com/ecl", opts)
+ if err != nil {
+ t.Fatalf("ProcessQRImage failed for ECL %v: %v", lvl, err)
+ }
+ if img == nil {
+ t.Fatalf("expected non-nil image for ECL %v", lvl)
+ }
+ }
+ })
+}
+
+func TestScaleImageToWidth(t *testing.T) {
+ t.Run("nil image returns nil", func(t *testing.T) {
+ if got := ScaleImageToWidth(nil, 100); got != nil {
+ t.Errorf("ScaleImageToWidth(nil, 100) = %v, want nil", got)
+ }
+ })
+
+ t.Run("targetWidth <= 0 returns original image", func(t *testing.T) {
+ img, _ := createTestPNG(t, 20, 10)
+ if got := ScaleImageToWidth(img, 0); got != img {
+ t.Error("expected original image when targetWidth <= 0")
+ }
+ if got := ScaleImageToWidth(img, -10); got != img {
+ t.Error("expected original image when targetWidth < 0")
+ }
+ })
+
+ t.Run("targetWidth == originalWidth returns original image", func(t *testing.T) {
+ img, _ := createTestPNG(t, 20, 10)
+ if got := ScaleImageToWidth(img, 20); got != img {
+ t.Error("expected original image when targetWidth == originalWidth")
+ }
+ })
+
+ t.Run("scales down proportionally", func(t *testing.T) {
+ img, _ := createTestPNG(t, 40, 20)
+ scaled := ScaleImageToWidth(img, 20)
+ if scaled == nil {
+ t.Fatal("expected non-nil scaled image")
+ }
+ if scaled.Bounds().Dx() != 20 {
+ t.Errorf("scaled width = %d, want 20", scaled.Bounds().Dx())
+ }
+ if scaled.Bounds().Dy() != 10 {
+ t.Errorf("scaled height = %d, want 10", scaled.Bounds().Dy())
+ }
+ })
+
+ t.Run("scales up proportionally", func(t *testing.T) {
+ img, _ := createTestPNG(t, 20, 10)
+ scaled := ScaleImageToWidth(img, 40)
+ if scaled == nil {
+ t.Fatal("expected non-nil scaled image")
+ }
+ if scaled.Bounds().Dx() != 40 {
+ t.Errorf("scaled width = %d, want 40", scaled.Bounds().Dx())
+ }
+ if scaled.Bounds().Dy() != 20 {
+ t.Errorf("scaled height = %d, want 20", scaled.Bounds().Dy())
+ }
+ })
+}
diff --git a/pkg/service/printer_service.go b/pkg/service/printer_service.go
index b308a0e..f922e91 100644
--- a/pkg/service/printer_service.go
+++ b/pkg/service/printer_service.go
@@ -94,7 +94,6 @@ func NewPrinterWithOptions(conn connection.Connector, opts ...PrinterOption) (*P
// Initialize resets the printer to default settings
func (p *Printer) Initialize() error {
- // TODO: Add profile-specific initialization if needed
var ct []byte
var err error
if p.Profile.IsSupported(p.Profile.CodeTable) {
@@ -107,11 +106,6 @@ func (p *Printer) Initialize() error {
}
init := append(p.Protocol.InitializePrinter(), ct...)
- // TODO: Make beep configurable in composer, not hardcoded here
- // Add beep to library
- // IMPORTANT: The idea is to notify the user that the printer is ready
- // but it can be annoying for my other dev colleagues :)
- // FIXME: init = append(init, []byte{0x1B, 0x42, 0x01, 0x05}...) // Beep!
return p.Write(init)
}
@@ -145,11 +139,11 @@ func (p *Printer) Print(text string) error {
// PrintLine sends text with line feed
func (p *Printer) PrintLine(text string) error {
- encText, err := p.Profile.EncodeString(text)
+ encoded, err := p.Profile.EncodeBytesSafe(text)
if err != nil {
- return err
+ return fmt.Errorf("encode text: %w", err)
}
- cmd, err := p.Protocol.PrintLn(encText)
+ cmd, err := p.Protocol.PrintLn(string(encoded))
if err != nil {
return err
}
diff --git a/pkg/service/printer_service_test.go b/pkg/service/printer_service_test.go
new file mode 100644
index 0000000..109fe34
--- /dev/null
+++ b/pkg/service/printer_service_test.go
@@ -0,0 +1,451 @@
+package service
+
+import (
+ "errors"
+ "testing"
+
+ "github.com/adcondev/poster/pkg/commands/character"
+ "github.com/adcondev/poster/pkg/composer"
+ "github.com/adcondev/poster/pkg/connection"
+ "github.com/adcondev/poster/pkg/constants"
+ "github.com/adcondev/poster/pkg/graphics"
+ "github.com/adcondev/poster/pkg/profile"
+)
+
+func TestNewPrinter_Validation(t *testing.T) {
+ conn := connection.NewBufferConnector()
+ proto := composer.NewEscpos()
+ prof := profile.CreateProfile80mm()
+
+ t.Run("nil proto", func(t *testing.T) {
+ _, err := NewPrinter(nil, prof, conn)
+ if err == nil {
+ t.Fatal("expected error for nil proto, got nil")
+ }
+ })
+
+ t.Run("nil prof", func(t *testing.T) {
+ _, err := NewPrinter(proto, nil, conn)
+ if err == nil {
+ t.Fatal("expected error for nil prof, got nil")
+ }
+ })
+
+ t.Run("nil conn", func(t *testing.T) {
+ _, err := NewPrinter(proto, prof, nil)
+ if err == nil {
+ t.Fatal("expected error for nil conn, got nil")
+ }
+ })
+
+ t.Run("valid parameters", func(t *testing.T) {
+ p, err := NewPrinter(proto, prof, conn)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if p == nil {
+ t.Fatal("expected printer instance, got nil")
+ }
+ })
+}
+
+func TestPrinterOptions(t *testing.T) {
+ t.Run("nil connection returns error", func(t *testing.T) {
+ _, err := NewPrinterWithOptions(nil)
+ if err == nil {
+ t.Fatal("expected error when connection is nil, got nil")
+ }
+ })
+
+ t.Run("WithProfile nil returns error", func(t *testing.T) {
+ conn := connection.NewBufferConnector()
+ _, err := NewPrinterWithOptions(conn, WithProfile(nil))
+ if err == nil {
+ t.Fatal("expected error with nil profile, got nil")
+ }
+ })
+
+ t.Run("WithProtocol nil returns error", func(t *testing.T) {
+ conn := connection.NewBufferConnector()
+ _, err := NewPrinterWithOptions(conn, WithProtocol(nil))
+ if err == nil {
+ t.Fatal("expected error with nil protocol, got nil")
+ }
+ })
+
+ t.Run("with custom options success", func(t *testing.T) {
+ conn := connection.NewBufferConnector()
+ customProfile := profile.CreateProfile58mm()
+ customProtocol := composer.NewEscpos()
+
+ p, err := NewPrinterWithOptions(
+ conn,
+ WithProfile(customProfile),
+ WithProtocol(customProtocol),
+ )
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if p.Profile.PaperWidth != customProfile.PaperWidth {
+ t.Errorf("expected custom profile paper width %v, got %v", customProfile.PaperWidth, p.Profile.PaperWidth)
+ }
+ })
+}
+
+func TestPrinter_BasicControl(t *testing.T) {
+ conn := connection.NewBufferConnector()
+ p, err := NewPrinterWithOptions(conn)
+ if err != nil {
+ t.Fatalf("NewPrinterWithOptions failed: %v", err)
+ }
+
+ t.Run("GetProfile", func(t *testing.T) {
+ prof := p.GetProfile()
+ if prof == nil {
+ t.Fatal("expected non-nil profile")
+ }
+ })
+
+ t.Run("Initialize with supported code table", func(t *testing.T) {
+ p.Profile.CodeTable = character.WPC1252
+ if err := p.Initialize(); err != nil {
+ t.Fatalf("Initialize failed: %v", err)
+ }
+ if conn.Len() == 0 {
+ t.Error("expected bytes written on initialize")
+ }
+ })
+
+ t.Run("Initialize with unsupported code table fallback", func(t *testing.T) {
+ conn.Reset()
+ p.Profile.CodeTable = character.CodeTable(250)
+ if err := p.Initialize(); err != nil {
+ t.Fatalf("Initialize failed: %v", err)
+ }
+ if conn.Len() == 0 {
+ t.Error("expected bytes written on initialize fallback")
+ }
+ })
+
+ t.Run("Write empty and non-empty", func(t *testing.T) {
+ conn.Reset()
+ if err := p.Write([]byte{}); err != nil {
+ t.Errorf("empty Write failed: %v", err)
+ }
+ if conn.Len() != 0 {
+ t.Errorf("expected 0 bytes written, got %d", conn.Len())
+ }
+
+ if err := p.Write([]byte{0x1B, 0x40}); err != nil {
+ t.Errorf("Write failed: %v", err)
+ }
+ if conn.Len() != 2 {
+ t.Errorf("expected 2 bytes written, got %d", conn.Len())
+ }
+ })
+
+ t.Run("Close", func(t *testing.T) {
+ if err := p.Close(); err != nil {
+ t.Errorf("Close failed: %v", err)
+ }
+ // Subsequent write on closed connection should error
+ if err := p.Write([]byte{0x01}); err == nil {
+ t.Error("expected error writing to closed connection")
+ }
+ })
+}
+
+func TestPrinter_TextPrintingAndFormatting(t *testing.T) {
+ conn := connection.NewBufferConnector()
+ p, err := NewPrinterWithOptions(conn)
+ if err != nil {
+ t.Fatalf("NewPrinterWithOptions failed: %v", err)
+ }
+
+ t.Run("Print and PrintLine and FeedLines", func(t *testing.T) {
+ if err := p.Print("Hello"); err != nil {
+ t.Errorf("Print failed: %v", err)
+ }
+ if err := p.PrintLine(" World"); err != nil {
+ t.Errorf("PrintLine failed: %v", err)
+ }
+ if err := p.FeedLines(2); err != nil {
+ t.Errorf("FeedLines failed: %v", err)
+ }
+ })
+
+ t.Run("Fonts and Bold", func(t *testing.T) {
+ if err := p.FontA(); err != nil {
+ t.Errorf("FontA failed: %v", err)
+ }
+ if err := p.FontB(); err != nil {
+ t.Errorf("FontB failed: %v", err)
+ }
+ if err := p.EnableBold(); err != nil {
+ t.Errorf("EnableBold failed: %v", err)
+ }
+ if err := p.DisableBold(); err != nil {
+ t.Errorf("DisableBold failed: %v", err)
+ }
+ })
+
+ t.Run("Alignments", func(t *testing.T) {
+ if err := p.AlignLeft(); err != nil {
+ t.Errorf("AlignLeft failed: %v", err)
+ }
+ if err := p.AlignCenter(); err != nil {
+ t.Errorf("AlignCenter failed: %v", err)
+ }
+ if err := p.AlignRight(); err != nil {
+ t.Errorf("AlignRight failed: %v", err)
+ }
+ alignments := []string{"left", "center", "right", "unknown_default"}
+ for _, align := range alignments {
+ if err := p.SetAlignment(align); err != nil {
+ t.Errorf("SetAlignment(%s) failed: %v", align, err)
+ }
+ }
+ })
+
+ t.Run("Sizes", func(t *testing.T) {
+ sizes := []func() error{
+ p.SingleSize,
+ p.DoubleSize,
+ p.TripleSize,
+ p.QuadraSize,
+ p.PentaSize,
+ p.HexaSize,
+ p.HeptaSize,
+ p.OctaSize,
+ }
+ for _, sizeFunc := range sizes {
+ if err := sizeFunc(); err != nil {
+ t.Errorf("size function failed: %v", err)
+ }
+ }
+ if err := p.CustomSize(2, 3); err != nil {
+ t.Errorf("CustomSize failed: %v", err)
+ }
+ })
+
+ t.Run("Underline and Inverse", func(t *testing.T) {
+ if err := p.NoDot(); err != nil {
+ t.Errorf("NoDot failed: %v", err)
+ }
+ if err := p.OneDot(); err != nil {
+ t.Errorf("OneDot failed: %v", err)
+ }
+ if err := p.TwoDot(); err != nil {
+ t.Errorf("TwoDot failed: %v", err)
+ }
+ if err := p.InverseOn(); err != nil {
+ t.Errorf("InverseOn failed: %v", err)
+ }
+ if err := p.InverseOff(); err != nil {
+ t.Errorf("InverseOff failed: %v", err)
+ }
+ })
+
+ t.Run("Feed and Cut, Pulse, Beep, Spacing", func(t *testing.T) {
+ if err := p.FullFeedAndCut(3); err != nil {
+ t.Errorf("FullFeedAndCut failed: %v", err)
+ }
+ if err := p.PartialFeedAndCut(3); err != nil {
+ t.Errorf("PartialFeedAndCut failed: %v", err)
+ }
+ if err := p.Pulse(0, 50, 50); err != nil {
+ t.Errorf("Pulse failed: %v", err)
+ }
+ if err := p.Beep(2, 10); err != nil {
+ t.Errorf("Beep failed: %v", err)
+ }
+ if err := p.SetLineSpacing(30); err != nil {
+ t.Errorf("SetLineSpacing failed: %v", err)
+ }
+ if err := p.SelectDefaultLineSpacing(); err != nil {
+ t.Errorf("SelectDefaultLineSpacing failed: %v", err)
+ }
+ })
+}
+
+func TestPrinter_CodeTable(t *testing.T) {
+ conn := connection.NewBufferConnector()
+ p, err := NewPrinterWithOptions(conn)
+ if err != nil {
+ t.Fatalf("NewPrinterWithOptions failed: %v", err)
+ }
+
+ t.Run("supported code table", func(t *testing.T) {
+ if err := p.SetCodeTable(character.PC437); err != nil {
+ t.Errorf("SetCodeTable(PC437) failed: %v", err)
+ }
+ })
+
+ t.Run("unsupported code table falls back to WPC1252", func(t *testing.T) {
+ if err := p.SetCodeTable(character.CodeTable(250)); err != nil {
+ t.Errorf("SetCodeTable(250) failed: %v", err)
+ }
+ })
+}
+
+func TestPrinter_PrintBitmap(t *testing.T) {
+ conn := connection.NewBufferConnector()
+ p, err := NewPrinterWithOptions(conn)
+ if err != nil {
+ t.Fatalf("NewPrinterWithOptions failed: %v", err)
+ }
+
+ t.Run("nil bitmap returns error", func(t *testing.T) {
+ if err := p.PrintBitmap(nil); err == nil {
+ t.Fatal("expected error for nil bitmap, got nil")
+ }
+ })
+
+ t.Run("standard non-banded bitmap", func(t *testing.T) {
+ bm := graphics.NewMonochromeBitmap(8, 4)
+ if err := p.PrintBitmap(bm); err != nil {
+ t.Fatalf("PrintBitmap failed: %v", err)
+ }
+ })
+
+ t.Run("banded bitmap", func(t *testing.T) {
+ p.Profile.MaxBandHeight = 4
+ bm := graphics.NewMonochromeBitmap(8, 10)
+ if err := p.PrintBitmap(bm); err != nil {
+ t.Fatalf("PrintBitmap banded failed: %v", err)
+ }
+ })
+}
+
+func TestPrinter_PrintBarcode(t *testing.T) {
+ conn := connection.NewBufferConnector()
+ p, err := NewPrinterWithOptions(conn)
+ if err != nil {
+ t.Fatalf("NewPrinterWithOptions failed: %v", err)
+ }
+
+ t.Run("empty data returns error", func(t *testing.T) {
+ cfg := graphics.DefaultBarcodeConfig()
+ if err := p.PrintBarcode(cfg, nil); err == nil {
+ t.Fatal("expected error for empty barcode data, got nil")
+ }
+ })
+
+ t.Run("valid barcode", func(t *testing.T) {
+ cfg := graphics.DefaultBarcodeConfig()
+ if err := p.PrintBarcode(cfg, []byte("12345678")); err != nil {
+ t.Fatalf("PrintBarcode failed: %v", err)
+ }
+ })
+}
+
+func TestMockPrinter_BasicAndText(t *testing.T) {
+ mock := NewMockPrinter()
+
+ if prof := mock.GetProfile(); prof == nil {
+ t.Error("expected non-nil profile")
+ }
+ if err := mock.Initialize(); err != nil {
+ t.Errorf("Initialize failed: %v", err)
+ }
+ if err := mock.Close(); err != nil {
+ t.Errorf("Close failed: %v", err)
+ }
+ if err := mock.Write([]byte{0x01}); err != nil {
+ t.Errorf("Write failed: %v", err)
+ }
+ if err := mock.Print("test"); err != nil {
+ t.Errorf("Print failed: %v", err)
+ }
+ if err := mock.PrintLine("line"); err != nil {
+ t.Errorf("PrintLine failed: %v", err)
+ }
+ if err := mock.FeedLines(1); err != nil {
+ t.Errorf("FeedLines failed: %v", err)
+ }
+ if mock.CallCount("Print") != 1 {
+ t.Errorf("expected 1 Print call, got %d", mock.CallCount("Print"))
+ }
+}
+
+func TestMockPrinter_FormattingAndSizes(t *testing.T) {
+ mock := NewMockPrinter()
+
+ methods := []func() error{
+ mock.FontA, mock.FontB, mock.EnableBold, mock.DisableBold,
+ mock.AlignLeft, mock.AlignCenter, mock.AlignRight,
+ mock.SingleSize, mock.DoubleSize, mock.TripleSize, mock.QuadraSize,
+ mock.PentaSize, mock.HexaSize, mock.HeptaSize, mock.OctaSize,
+ mock.NoDot, mock.OneDot, mock.TwoDot,
+ mock.InverseOn, mock.InverseOff,
+ }
+ for _, m := range methods {
+ if err := m(); err != nil {
+ t.Errorf("method failed: %v", err)
+ }
+ }
+ if err := mock.SetAlignment("center"); err != nil {
+ t.Errorf("SetAlignment failed: %v", err)
+ }
+ if err := mock.CustomSize(2, 2); err != nil {
+ t.Errorf("CustomSize failed: %v", err)
+ }
+}
+
+func TestMockPrinter_AdvancedAndControl(t *testing.T) {
+ mock := NewMockPrinter()
+
+ if err := mock.FullFeedAndCut(3); err != nil {
+ t.Errorf("FullFeedAndCut failed: %v", err)
+ }
+ if err := mock.PartialFeedAndCut(3); err != nil {
+ t.Errorf("PartialFeedAndCut failed: %v", err)
+ }
+ if err := mock.Pulse(0, 10, 10); err != nil {
+ t.Errorf("Pulse failed: %v", err)
+ }
+ if err := mock.Beep(1, 1); err != nil {
+ t.Errorf("Beep failed: %v", err)
+ }
+ if err := mock.SetLineSpacing(30); err != nil {
+ t.Errorf("SetLineSpacing failed: %v", err)
+ }
+ if err := mock.SelectDefaultLineSpacing(); err != nil {
+ t.Errorf("SelectDefaultLineSpacing failed: %v", err)
+ }
+ if err := mock.PrintBitmap(graphics.NewMonochromeBitmap(8, 8)); err != nil {
+ t.Errorf("PrintBitmap failed: %v", err)
+ }
+ if err := mock.SetCodeTable(character.WPC1252); err != nil {
+ t.Errorf("SetCodeTable failed: %v", err)
+ }
+ if err := mock.PrintQR("data", graphics.DefaultQROptions()); err != nil {
+ t.Errorf("PrintQR failed: %v", err)
+ }
+ if err := mock.PrintBarcode(graphics.DefaultBarcodeConfig(), []byte("123")); err != nil {
+ t.Errorf("PrintBarcode failed: %v", err)
+ }
+
+ last := mock.LastCall()
+ if last == nil || last.Method != "PrintBarcode" {
+ t.Errorf("expected last call PrintBarcode, got %v", last)
+ }
+
+ // Test FailOn error injection
+ mock.FailOn["Write"] = errors.New("injected error")
+ if err := mock.Write([]byte{0x00}); err == nil {
+ t.Error("expected injected error from Write, got nil")
+ }
+
+ // Test Reset
+ mock.Reset()
+ if len(mock.Calls) != 0 {
+ t.Errorf("expected 0 calls after Reset, got %d", len(mock.Calls))
+ }
+ if mock.LastCall() != nil {
+ t.Errorf("expected nil LastCall after Reset, got %v", mock.LastCall())
+ }
+ if mock.CurrentAlignment != constants.Left.String() {
+ t.Errorf("expected reset alignment 'left', got %s", mock.CurrentAlignment)
+ }
+}
diff --git a/pkg/tables/table_text_test.go b/pkg/tables/table_text_test.go
index 4367f41..53ad68b 100644
--- a/pkg/tables/table_text_test.go
+++ b/pkg/tables/table_text_test.go
@@ -401,7 +401,6 @@ func TestData_Validate(t *testing.T) {
}
}
-// TODO: Use string.Contains from strings package when available
func Contains(s, substr string) bool {
return len(s) >= len(substr) && (s == substr || len(substr) == 0 ||
(len(s) > 0 && len(substr) > 0 && SearchSubstring(s, substr)))