Add the list block and the module layer with the note module
Security / Vulnerability check (push) Successful in 41s
Test / Lint and test (push) Successful in 1m50s

The list block prints items with a dot, dash, number or checkbox bullet,
wrapping a long item with a hanging indent; a checkbox list ticks its
done items as [√], or [x] on code pages without √. It stands alone or
inside a box, and its items, bullet and done fields carry their enums
and limits as jsonschema tags.

internal/pkg/modules holds modules that build ordinary jobs from their
own payloads: a registry by name, an Env with the clock, time zone and
time layout, strict payload decoding that reports every problem, ErrSkip
and PayloadError. The note module prints a boxed note with an optional
checklist and a time stamp in the footer.

Three routes join the route table: POST /api/v1/print/{module} and
POST /api/v1/preview/{module}, which take ?copies and a reserved
?printer, and GET /api/v1/modules. Print and the module route share one
submit path, and preview shares one too. New error codes:
invalid_payload, invalid_query, unknown_printer, module_not_found and
module_failed; a module that builds an invalid receipt is logged and
reported to Sentry once. [format] gains timezone and time_layout, the
binary embeds the time zone database, and uberbringer preview takes
--module.

The note receipt passed on the TM-T88IV, and its bytes are pinned in
TestPaperReceipts. docs/api.md describes the list block, the module
routes and the note payload; docs/swagger.json is regenerated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
57_WolveandClaude Opus 5.5 committed 2026-11-30 10:55:50 -06:00
1 parent 6b2e402f1a
commit 3e9779f71a
69 files changed
+3092 -262

No files matched your search

+128
View File
@@ -0,0 +1,128 @@
package modules
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"maps"
"reflect"
"slices"
"strconv"
"strings"
)
// maxNameInProblem caps how much of an unknown field's name a problem
// repeats.
const maxNameInProblem = 64
// DecodeStrict decodes body, which must be one JSON object, into the struct
// v points to. A name must match a field's json tag exactly, so a name in
// another case is unknown. Every problem is reported at once, in a
// *PayloadError: a body that is not one JSON object, each unknown field and
// each field of the wrong type. A field that is null counts as absent.
func DecodeStrict(body []byte, v any) error {
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Pointer || rv.Elem().Kind() != reflect.Struct {
panic("modules.DecodeStrict: v must point to a struct")
}
var object map[string]json.RawMessage
dec := json.NewDecoder(bytes.NewReader(body))
if err := dec.Decode(&object); err != nil {
return &PayloadError{Problems: []string{bodyProblem(err)}}
}
if object == nil {
return &PayloadError{Problems: []string{"body: expected a JSON object, got null"}}
}
if _, err := dec.Token(); !errors.Is(err, io.EOF) {
return &PayloadError{Problems: []string{"body: trailing data after the payload"}}
}
target := rv.Elem()
fields := jsonFields(target.Type())
var problems []string
for _, name := range slices.Sorted(maps.Keys(object)) {
index, ok := fields[name]
if !ok {
problems = append(problems, fieldName(name)+": unknown field")
continue
}
field := target.Field(index)
if err := json.Unmarshal(object[name], field.Addr().Interface()); err != nil {
problems = append(problems, fmt.Sprintf("%s: expected %s", name, describe(field.Type())))
}
}
if len(problems) > 0 {
return &PayloadError{Problems: problems}
}
return nil
}
// bodyProblem describes why a body is not a JSON object.
func bodyProblem(err error) string {
var typeErr *json.UnmarshalTypeError
switch {
case errors.Is(err, io.EOF):
return "body: empty; expected a JSON object"
case errors.As(err, &typeErr):
return "body: expected a JSON object, got " + typeErr.Value
}
return "body: not valid JSON: " + err.Error()
}
// jsonFields maps the json name of each exported field of the struct type t
// to its index.
func jsonFields(t reflect.Type) map[string]int {
fields := make(map[string]int, t.NumField())
for i := range t.NumField() {
f := t.Field(i)
name, _, _ := strings.Cut(f.Tag.Get("json"), ",")
if !f.IsExported() || name == "-" {
continue
}
if name == "" {
name = f.Name
}
fields[name] = i
}
return fields
}
// fieldName shows a field name from a payload in a problem: as written when
// it is a plain name, quoted otherwise, and cut when it is long.
func fieldName(name string) string {
plain := name != "" && strings.Trim(name, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-") == ""
if r := []rune(name); len(r) > maxNameInProblem {
name = string(r[:maxNameInProblem]) + "..."
}
if plain {
return name
}
return strconv.Quote(name)
}
// describe names the JSON a field of type t takes.
func describe(t reflect.Type) string {
switch t.Kind() {
case reflect.Pointer:
return describe(t.Elem())
case reflect.String:
return "a string"
case reflect.Bool:
return "true or false"
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return "a whole number"
case reflect.Slice:
switch t.Elem().Kind() {
case reflect.String:
return "an array of strings"
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return "an array of whole numbers"
}
return "an array"
}
return t.String()
}
+88
View File
@@ -0,0 +1,88 @@
package modules_test
import (
"errors"
"strings"
"testing"
"uberbringer/internal/pkg/modules"
)
type decodeTarget struct {
Name string `json:"name"`
Count int `json:"count"`
On *bool `json:"on"`
Tags []string `json:"tags"`
Marks []int `json:"marks"`
Skip string `json:"-"`
}
func TestDecodeStrict(t *testing.T) {
var got decodeTarget
body := `{"name":"n","count":3,"on":false,"tags":["a","b"],"marks":[1,2],"count":4}`
if err := modules.DecodeStrict([]byte(body), &got); err != nil {
t.Fatal(err)
}
if got.Name != "n" || got.Count != 4 || got.On == nil || *got.On || strings.Join(got.Tags, ",") != "a,b" || len(got.Marks) != 2 {
t.Errorf("decoded %+v", got)
}
var empty decodeTarget
if err := modules.DecodeStrict([]byte(` {"name": null} `), &empty); err != nil || empty.Name != "" {
t.Errorf("a null field: %v, %+v; want it treated as absent", err, empty)
}
}
func TestDecodeStrictProblems(t *testing.T) {
tests := []struct {
name, body string
want []string // the complete list of problems
}{
{"empty body", "", []string{"body: empty; expected a JSON object"}},
{"blank body", " \n", []string{"body: empty; expected a JSON object"}},
{"array", `[1]`, []string{"body: expected a JSON object, got array"}},
{"string", `"x"`, []string{"body: expected a JSON object, got string"}},
{"null", `null`, []string{"body: expected a JSON object, got null"}},
{"syntax error", `{"name":`, []string{"body: not valid JSON: unexpected EOF"}},
{"trailing data", `{} {}`, []string{"body: trailing data after the payload"}},
{"every problem at once", `{"Name":"x","colour":1,"count":"3","on":"yes","tags":[1],"marks":[1.5],"hidden":"h","Skip":"s","-":1}`, []string{
"-: unknown field",
"Name: unknown field",
"Skip: unknown field",
"colour: unknown field",
"count: expected a whole number",
"hidden: unknown field",
"marks: expected an array of whole numbers",
"on: expected true or false",
"tags: expected an array of strings",
}},
{"number too large", `{"count":1e400}`, []string{"count: expected a whole number"}},
{"odd field names are quoted and cut", `{"a b":1,"` + strings.Repeat("x", 70) + `":2}`, []string{
`"a b": unknown field`,
strings.Repeat("x", 64) + "...: unknown field",
}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var v decodeTarget
err := modules.DecodeStrict([]byte(tt.body), &v)
var pe *modules.PayloadError
if !errors.As(err, &pe) {
t.Fatalf("err = %v, want *PayloadError", err)
}
if strings.Join(pe.Problems, "\n") != strings.Join(tt.want, "\n") {
t.Errorf("problems:\n%s\nwant:\n%s", strings.Join(pe.Problems, "\n"), strings.Join(tt.want, "\n"))
}
})
}
}
func TestDecodeStrictNeedsAStruct(t *testing.T) {
defer func() {
if recover() == nil {
t.Error("DecodeStrict into a map did not panic")
}
}()
var m map[string]any
_ = modules.DecodeStrict([]byte(`{}`), &m)
}
+108
View File
@@ -0,0 +1,108 @@
package modules
import (
"context"
"fmt"
"strings"
"uberbringer/internal/pkg/receipt"
)
// noteStyles are the box styles a note may ask for.
var noteStyles = []string{"single", "double", "double-h", "double-v"}
// Note returns the note module: a box with an optional title, the text and
// an optional checklist, stamped with the time in its bottom border.
func Note() Module {
return note{}
}
type note struct{}
// notePayload is the body of a note.
type notePayload struct {
Title string `json:"title"`
Text string `json:"text"`
Items []string `json:"items"`
Done []int `json:"done"`
Style string `json:"style"`
Footer string `json:"footer"`
Stamp *bool `json:"stamp"`
}
func (note) Name() string { return "note" }
func (note) Description() string { return "Boxed note with an optional checklist" }
// Build lays the note out as a box: the text, then, when there are items,
// an empty line and a checklist. The footer is the payload's, or the build
// time unless stamp is false.
func (note) Build(_ context.Context, body []byte, env Env) (receipt.Job, error) {
var p notePayload
if err := DecodeStrict(body, &p); err != nil {
return receipt.Job{}, err
}
if problems := p.problems(); len(problems) > 0 {
return receipt.Job{}, &PayloadError{Problems: problems}
}
children := []receipt.Element{{Type: receipt.TypeText, Text: p.Text}}
if len(p.Items) > 0 {
children = append(children,
receipt.Element{Type: receipt.TypeFeed},
receipt.Element{Type: receipt.TypeList, Bullet: "checkbox", Items: p.Items, Done: p.Done},
)
}
footer := p.Footer
if footer == "" && (p.Stamp == nil || *p.Stamp) {
footer = env.Stamp()
}
box := receipt.Element{
Type: receipt.TypeBox,
Title: p.Title,
Style: strings.ToLower(p.Style),
Footer: footer,
Children: children,
}
return receipt.Job{Elements: []receipt.Element{box}}, nil
}
// problems checks what the box and its list would refuse, in the payload's
// own terms.
func (p notePayload) problems() []string {
var problems []string
if strings.TrimSpace(p.Text) == "" {
problems = append(problems, "text: required")
}
if p.Style != "" && !containsFold(noteStyles, p.Style) {
problems = append(problems, "style: must be "+strings.Join(noteStyles[:len(noteStyles)-1], ", ")+" or "+noteStyles[len(noteStyles)-1])
}
if n := len(p.Items); n > receipt.MaxItems {
problems = append(problems, fmt.Sprintf("items: %d items, limit is %d", n, receipt.MaxItems))
}
for i, item := range p.Items {
if item == "" {
problems = append(problems, fmt.Sprintf("items[%d]: must not be empty", i))
}
}
seen := make(map[int]bool, len(p.Done))
for i, index := range p.Done {
switch {
case index < 0 || index >= len(p.Items):
problems = append(problems, fmt.Sprintf("done[%d]: index %d is out of range", i, index))
case seen[index]:
problems = append(problems, fmt.Sprintf("done[%d]: index %d is repeated", i, index))
}
seen[index] = true
}
return problems
}
func containsFold(list []string, s string) bool {
for _, item := range list {
if strings.EqualFold(item, s) {
return true
}
}
return false
}
+244
View File
@@ -0,0 +1,244 @@
package modules_test
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
// Embeds the zone database, so that Europe/London loads on any host.
_ "time/tzdata"
"uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/modules"
"uberbringer/internal/pkg/receipt"
)
var update = flag.Bool("update", false, "rewrite testdata/note/*.txt from the current output")
// fixedEnv is 29 Nov 2026 21:04:05 UTC in Europe/London, which is on GMT
// then.
func fixedEnv(t *testing.T) modules.Env {
t.Helper()
london, err := time.LoadLocation("Europe/London")
if err != nil {
t.Fatal(err)
}
return modules.Env{
Now: time.Date(2026, 11, 29, 21, 4, 5, 0, time.UTC),
Location: london,
TimeLayout: "02 Jan 15:04",
}
}
// previewText previews job on a TM-T88 in CP437: its lines, then its
// warnings.
func previewText(t *testing.T, job receipt.Job) string {
t.Helper()
profile, err := escpos.LookupProfile("tm-t88")
if err != nil {
t.Fatal(err)
}
r := receipt.NewRenderer(receipt.Options{
Profile: profile, CodePage: escpos.CodePage437, MaxPixels: 1000, MaxHeight: 1000, MaxLines: 2000,
}, noFetch{})
p, err := r.Preview(context.Background(), job)
if err != nil {
t.Fatalf("Preview: %v", err)
}
var b strings.Builder
for _, l := range p.Lines {
b.WriteString(l.Text)
b.WriteByte('\n')
}
if len(p.Warnings) > 0 {
b.WriteString("=== warnings\n")
for _, w := range p.Warnings {
b.WriteString(w)
b.WriteByte('\n')
}
}
return b.String()
}
type noFetch struct{}
func (noFetch) Fetch(context.Context, string) ([]byte, error) {
return nil, errors.New("previews do not fetch")
}
// TestNoteGoldens builds each testdata/note/*.json payload with a fixed
// clock and compares its preview with NAME.txt. Run with -update to rewrite
// the .txt files, then review the diff.
func TestNoteGoldens(t *testing.T) {
paths, err := filepath.Glob(filepath.Join("testdata", "note", "*.json"))
if err != nil {
t.Fatal(err)
}
if len(paths) == 0 {
t.Fatal("no payloads in testdata/note")
}
for _, path := range paths {
name := strings.TrimSuffix(filepath.Base(path), ".json")
t.Run(name, func(t *testing.T) {
body, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
job, err := modules.Note().Build(context.Background(), body, fixedEnv(t))
if err != nil {
t.Fatalf("Build: %v", err)
}
if err := job.Validate(); err != nil {
t.Fatalf("the note built an invalid job: %v", err)
}
got := previewText(t, job)
golden := filepath.Join("testdata", "note", name+".txt")
if *update {
if err := os.WriteFile(golden, []byte(got), 0o644); err != nil {
t.Fatal(err)
}
return
}
want, err := os.ReadFile(golden)
if err != nil {
t.Fatalf("%v (run go test -run TestNoteGoldens -update)", err)
}
if got != string(want) {
t.Errorf("preview differs from %s:\ngot:\n%s\nwant:\n%s", golden, got, want)
}
})
}
}
// TestNoteMockup pins the note the formatters plan shows as mockup 5.
func TestNoteMockup(t *testing.T) {
body := `{"title":"Shopping","text":"Milk, eggs and the good bread from the bakery on Elm St.","items":["Milk","Eggs","Bread"],"done":[2]}`
job, err := modules.Note().Build(context.Background(), []byte(body), fixedEnv(t))
if err != nil {
t.Fatal(err)
}
want := "" +
"┌─ Shopping ─────────────────────────────┐\n" +
"│ Milk, eggs and the good bread from the │\n" +
"│ bakery on Elm St. │\n" +
"│ │\n" +
"│ [ ] Milk │\n" +
"│ [ ] Eggs │\n" +
"│ [√] Bread │\n" +
"└──────────────────────── 29 Nov 21:04 ──┘\n" +
" - - - - - - - partial cut - - - - - - - -\n"
if got := previewText(t, job); got != want {
t.Errorf("preview:\n%s\nwant:\n%s", got, want)
}
}
// TestNoteBuildsThePaperJob checks that the note still builds the job whose
// printed result was checked on the TM-T88IV, and whose bytes the receipt
// package pins: the shopping note, built at 08:56 on a host at UTC-6.
func TestNoteBuildsThePaperJob(t *testing.T) {
env := modules.Env{
Now: time.Date(2026, 11, 30, 14, 56, 39, 0, time.UTC),
Location: time.FixedZone("UTC-6", -6*60*60),
TimeLayout: "02 Jan 15:04",
}
body := `{"title":"Shopping","text":"Milk, eggs and the good bread from the bakery on Elm St.","items":["Milk","Eggs","Bread"],"done":[2]}`
job, err := modules.Note().Build(context.Background(), []byte(body), env)
if err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(filepath.Join("..", "receipt", "testdata", "paper", "note.json"))
if err != nil {
t.Fatal(err)
}
paper, err := receipt.DecodeJob(data)
if err != nil {
t.Fatal(err)
}
got, err := json.Marshal(job)
if err != nil {
t.Fatal(err)
}
want, err := json.Marshal(paper)
if err != nil {
t.Fatal(err)
}
if string(got) != string(want) {
t.Errorf("the note builds\n%s\nbut the job checked on paper is\n%s", got, want)
}
}
func TestNotePayloadProblems(t *testing.T) {
items := make([]string, receipt.MaxItems+1)
for i := range items {
items[i] = fmt.Sprintf("%q", "item")
}
tests := []struct {
name, body string
want []string // the complete list of problems
}{
{"unknown field", `{"text":"x","colour":"red"}`, []string{"colour: unknown field"}},
{"field in another case", `{"Text":"x"}`, []string{"Text: unknown field"}},
{"wrong type", `{"text":"x","items":"Milk","stamp":"no"}`, []string{"items: expected an array of strings", "stamp: expected true or false"}},
{"missing text", `{"title":"Shopping"}`, []string{"text: required"}},
{"blank text", `{"text":" \n "}`, []string{"text: required"}},
{"done index out of range", `{"text":"x","items":["Milk","Eggs"],"done":[5,-1]}`,
[]string{"done[0]: index 5 is out of range", "done[1]: index -1 is out of range"}},
{"done without items", `{"text":"x","done":[0]}`, []string{"done[0]: index 0 is out of range"}},
{"done repeated", `{"text":"x","items":["a","b"],"done":[1,1]}`, []string{"done[1]: index 1 is repeated"}},
{"more than 200 items", `{"text":"x","items":[` + strings.Join(items, ",") + `]}`, []string{"items: 201 items, limit is 200"}},
{"empty item", `{"text":"x","items":["a",""]}`, []string{"items[1]: must not be empty"}},
{"style", `{"text":"x","style":"ascii"}`, []string{"style: must be single, double, double-h or double-v"}},
{"every problem at once", `{"style":"bold","items":[""],"done":[3]}`, []string{
"text: required",
"style: must be single, double, double-h or double-v",
"items[0]: must not be empty",
"done[0]: index 3 is out of range",
}},
{"not an object", `["text"]`, []string{"body: expected a JSON object, got array"}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := modules.Note().Build(context.Background(), []byte(tt.body), fixedEnv(t))
var pe *modules.PayloadError
if !errors.As(err, &pe) {
t.Fatalf("err = %v, want *PayloadError", err)
}
if strings.Join(pe.Problems, "\n") != strings.Join(tt.want, "\n") {
t.Errorf("problems:\n%s\nwant:\n%s", strings.Join(pe.Problems, "\n"), strings.Join(tt.want, "\n"))
}
})
}
}
// TestNoteBuildsValidJobs checks that a payload the note accepts always
// builds a job that passes validation, at the limits too.
func TestNoteBuildsValidJobs(t *testing.T) {
items := make([]string, receipt.MaxItems)
for i := range items {
items[i] = fmt.Sprintf("%q", fmt.Sprint("item ", i))
}
bodies := []string{
`{"text":"x"}`,
`{"text":"x","items":[],"done":[]}`,
`{"text":"x","style":"DOUBLE-V","stamp":false}`,
`{"text":"x","items":[` + strings.Join(items, ",") + `],"done":[0,199]}`,
`{"title":"\u001b@","text":"\u0007","footer":"\t","items":["\u001bd"]}`,
}
for _, body := range bodies {
job, err := modules.Note().Build(context.Background(), []byte(body), fixedEnv(t))
if err != nil {
t.Errorf("%s: %v", body, err)
continue
}
if err := job.Validate(); err != nil {
t.Errorf("%s: built an invalid job: %v", body, err)
}
}
}
+119
View File
@@ -0,0 +1,119 @@
// Package modules turns plain payloads, such as a note's title, text and
// items, into receipt jobs built from the layout blocks. Each module owns
// its payload format; the HTTP routes and the command line look modules up
// by name in a Registry.
package modules
import (
"context"
"errors"
"fmt"
"maps"
"regexp"
"slices"
"strings"
"time"
"uberbringer/internal/pkg/receipt"
)
// ErrSkip is returned by Build when the payload asks for nothing to be
// printed.
var ErrSkip = errors.New("nothing to print")
// PayloadError lists every problem with a payload, each prefixed with the
// field it concerns, e.g. "done[0]: index 5 is out of range".
type PayloadError struct {
Problems []string
}
// Error implements error.
func (e *PayloadError) Error() string {
return "invalid payload: " + strings.Join(e.Problems, "; ")
}
// Env is what a module may know about the time a receipt is built at. A
// module never reads the clock itself, so that its output is reproducible.
type Env struct {
// Now is the time the receipt is built at.
Now time.Time
// Location is the time zone times are printed in. Nil means local time.
Location *time.Location
// TimeLayout is the Go time layout times are printed in, e.g.
// "02 Jan 15:04".
TimeLayout string
}
// Stamp returns Now in Location, formatted with TimeLayout.
func (e Env) Stamp() string {
loc := e.Location
if loc == nil {
loc = time.Local
}
return e.Now.In(loc).Format(e.TimeLayout)
}
// Module builds a receipt from its own payload format.
type Module interface {
// Name is the module's name in routes, e.g. "note" in
// /api/v1/print/note.
Name() string
// Description says in one line what the module prints.
Description() string
// Build turns body into a job. It returns a *PayloadError for a body
// that is not a valid payload, and ErrSkip for one that asks for
// nothing to be printed. The job it returns is expected to pass
// Job.Validate; one that does not is a bug in the module.
Build(ctx context.Context, body []byte, env Env) (receipt.Job, error)
}
// Info describes a module for listings.
type Info struct {
Name string
Description string
}
// validName is the form of a module name: it appears as a path segment.
var validName = regexp.MustCompile(`^[a-z][a-z0-9-]{0,31}$`)
// Registry holds the modules by name. It is safe for concurrent use once
// built.
type Registry struct {
modules map[string]Module
}
// NewRegistry returns a registry of mods. Each name must be unique and made
// of lowercase letters, digits and dashes, starting with a letter.
func NewRegistry(mods ...Module) (*Registry, error) {
r := &Registry{modules: make(map[string]Module, len(mods))}
for _, m := range mods {
name := m.Name()
if !validName.MatchString(name) {
return nil, fmt.Errorf("module name %q: want lowercase letters, digits and dashes, starting with a letter", name)
}
if _, ok := r.modules[name]; ok {
return nil, fmt.Errorf("module %q is registered twice", name)
}
r.modules[name] = m
}
return r, nil
}
// Get returns the module called name.
func (r *Registry) Get(name string) (Module, bool) {
m, ok := r.modules[name]
return m, ok
}
// List describes every module, sorted by name.
func (r *Registry) List() []Info {
infos := make([]Info, 0, len(r.modules))
for _, name := range slices.Sorted(maps.Keys(r.modules)) {
infos = append(infos, Info{Name: name, Description: r.modules[name].Description()})
}
return infos
}
+105
View File
@@ -0,0 +1,105 @@
package modules_test
import (
"context"
"strings"
"testing"
"time"
"uberbringer/internal/pkg/modules"
"uberbringer/internal/pkg/receipt"
)
// stubModule is a module that prints one line of text.
type stubModule struct{ name, description string }
func (m stubModule) Name() string { return m.name }
func (m stubModule) Description() string { return m.description }
func (m stubModule) Build(context.Context, []byte, modules.Env) (receipt.Job, error) {
return receipt.Job{Elements: []receipt.Element{{Type: "text", Text: m.name}}}, nil
}
func TestRegistryLookup(t *testing.T) {
r, err := modules.NewRegistry(stubModule{"b", "B"}, modules.Note(), stubModule{"a-2", "A"})
if err != nil {
t.Fatal(err)
}
m, ok := r.Get("note")
if !ok || m.Name() != "note" {
t.Errorf("Get(note) = %v, %v", m, ok)
}
for _, name := range []string{"Note", "nope", ""} {
if _, ok := r.Get(name); ok {
t.Errorf("Get(%q) found a module", name)
}
}
got := r.List()
want := []modules.Info{{"a-2", "A"}, {"b", "B"}, {"note", "Boxed note with an optional checklist"}}
if len(got) != len(want) {
t.Fatalf("List() = %v, want %v", got, want)
}
for i := range want {
if got[i] != want[i] {
t.Errorf("List()[%d] = %v, want %v", i, got[i], want[i])
}
}
}
func TestRegistryListIsNeverNil(t *testing.T) {
r, err := modules.NewRegistry()
if err != nil {
t.Fatal(err)
}
if got := r.List(); got == nil || len(got) != 0 {
t.Errorf("List() = %#v, want an empty list", got)
}
}
func TestRegistryRefusals(t *testing.T) {
tests := []struct {
name string
mods []modules.Module
wantErr string
}{
{"duplicate name", []modules.Module{stubModule{"note", ""}, modules.Note()}, `module "note" is registered twice`},
{"upper case", []modules.Module{stubModule{"Note", ""}}, `module name "Note"`},
{"empty", []modules.Module{stubModule{"", ""}}, `module name ""`},
{"slash", []modules.Module{stubModule{"a/b", ""}}, `module name "a/b"`},
{"leading digit", []modules.Module{stubModule{"1a", ""}}, `module name "1a"`},
{"too long", []modules.Module{stubModule{strings.Repeat("a", 33), ""}}, "module name"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := modules.NewRegistry(tt.mods...)
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Errorf("err = %v, want it to contain %q", err, tt.wantErr)
}
})
}
}
func TestEnvStamp(t *testing.T) {
london, err := time.LoadLocation("Europe/London")
if err != nil {
t.Fatal(err)
}
summer := time.Date(2026, 7, 14, 20, 4, 5, 0, time.UTC)
tests := []struct {
env modules.Env
want string
}{
{modules.Env{Now: summer, Location: london, TimeLayout: "02 Jan 15:04"}, "14 Jul 21:04"},
{modules.Env{Now: summer, Location: time.UTC, TimeLayout: "02 Jan 15:04"}, "14 Jul 20:04"},
{modules.Env{Now: summer, Location: london, TimeLayout: "2006-01-02 15:04 MST"}, "2026-07-14 21:04 BST"},
}
for _, tt := range tests {
if got := tt.env.Stamp(); got != tt.want {
t.Errorf("Stamp() in %v with %q = %q, want %q", tt.env.Location, tt.env.TimeLayout, got, tt.want)
}
}
local := modules.Env{Now: summer, TimeLayout: time.RFC3339}
if got, want := local.Stamp(), summer.In(time.Local).Format(time.RFC3339); got != want {
t.Errorf("Stamp() without a location = %q, want local time %q", got, want)
}
}
+1
View File
@@ -0,0 +1 @@
{"title": "Packing", "text": "All done.", "items": ["Passport", "Charger", "Tickets"], "done": [0, 1, 2]}
+8
View File
@@ -0,0 +1,8 @@
┌─ Packing ──────────────────────────────┐
│ All done. │
│ │
│ [√] Passport │
│ [√] Charger │
│ [√] Tickets │
└──────────────────────── 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"title": "Footer", "text": "A footer replaces the time.", "footer": "from the kitchen"}
+4
View File
@@ -0,0 +1,4 @@
┌─ Footer ───────────────────────────────┐
│ A footer replaces the time. │
└──────────────────── from the kitchen ──┘
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1 @@
{"text": "No title, but a checklist.", "items": ["One", "Two"]}
+7
View File
@@ -0,0 +1,7 @@
┌────────────────────────────────────────┐
│ No title, but a checklist. │
│ │
│ [ ] One │
│ [ ] Two │
└──────────────────────── 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"title": "A title that is far too long to fit into the top border of the box", "text": "First paragraph.\nSecond paragraph, which is long enough to wrap inside the box.", "items": ["An item that is long enough to wrap onto a second line with a hanging indent", "“Curly quotes” — and an emoji 🎉"], "done": [1]}
+13
View File
@@ -0,0 +1,13 @@
┌─ A title that is far too long to f... ─┐
│ First paragraph. │
│ Second paragraph, which is long enough │
│ to wrap inside the box. │
│ │
│ [ ] An item that is long enough to │
│ wrap onto a second line with a │
│ hanging indent │
│ [√] "Curly quotes" -- and an emoji ? │
└──────────────────────── 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
=== warnings
elements[0]: 1 character not in cp437 printed as ?
+1
View File
@@ -0,0 +1 @@
{"title": "Shopping", "text": "Milk, eggs and the good bread from the bakery on Elm St.", "items": ["Milk", "Eggs", "Bread"], "done": [2]}
+9
View File
@@ -0,0 +1,9 @@
┌─ Shopping ─────────────────────────────┐
│ Milk, eggs and the good bread from the │
│ bakery on Elm St. │
│ │
│ [ ] Milk │
│ [ ] Eggs │
│ [√] Bread │
└──────────────────────── 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"title": "No stamp", "text": "stamp false leaves the bottom border plain.", "stamp": false}
+5
View File
@@ -0,0 +1,5 @@
┌─ No stamp ─────────────────────────────┐
│ stamp false leaves the bottom border │
│ plain. │
└────────────────────────────────────────┘
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1 @@
{"title": "Double-h", "text": "style double-h", "style": "double-h", "items": ["a"]}
+6
View File
@@ -0,0 +1,6 @@
╒═ Double-h ═════════════════════════════╕
│ style double-h │
│ │
│ [ ] a │
╘════════════════════════ 29 Nov 21:04 ══╛
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1 @@
{"title": "Double-v", "text": "style double-v", "style": "double-v", "items": ["a"]}
+6
View File
@@ -0,0 +1,6 @@
╓─ Double-v ─────────────────────────────╖
║ style double-v ║
║ ║
║ [ ] a ║
╙──────────────────────── 29 Nov 21:04 ──╜
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"title": "Double", "text": "style double", "style": "double", "items": ["a"], "done": [0]}
+6
View File
@@ -0,0 +1,6 @@
╔═ Double ═══════════════════════════════╗
║ style double ║
║ ║
║ [√] a ║
╚════════════════════════ 29 Nov 21:04 ══╝
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"title": "Single", "text": "style single, written in capitals", "style": "SINGLE"}
+4
View File
@@ -0,0 +1,4 @@
┌─ Single ───────────────────────────────┐
│ style single, written in capitals │
└──────────────────────── 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"text": "Back at 3."}
+4
View File
@@ -0,0 +1,4 @@
┌────────────────────────────────────────┐
│ Back at 3. │
└──────────────────────── 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1 @@
{"title": "Reminder", "text": "Call the plumber about the kitchen tap before Friday."}
+5
View File
@@ -0,0 +1,5 @@
┌─ Reminder ─────────────────────────────┐
│ Call the plumber about the kitchen tap │
│ before Friday. │
└──────────────────────── 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -