Files
uberbringer/internal/pkg/modules/note_test.go
T
57_WolveandClaude Opus 5.5 1335ed0687
Security / Vulnerability check (push) Successful in 41s
Test / Lint and test (push) Successful in 1m57s
Add the notify and ntfy modules and scoped tokens
Breaking: a job with a raw element prints only with a token issued with
uberbringer token --raw. Every other token, every existing one included,
gets 403 token_scope for it, with the raw elements in details, and keeps
every other route.

The notify module prints a notification card from a title, message,
priority and tags, with topic, click, up to three actions, image,
markdown and time as options; it decodes strictly and refuses a payload
over its length caps. The ntfy module takes one ntfy message as ntfy
sends it, such as the ntfy client's $NTFY_RAW, ignores fields it does
not know, cuts text over the caps, and answers 204 for other events and
binary bodies. Both print every message plain: one message cannot tell
the first of a sequence from a replacement, since a publisher may choose
the sequence ID. internal/pkg/ntfy holds ntfy's message types.

Both print the same card. The priority picks the form: a dark URGENT
rule and a double box, a double box headed HIGH, a single box with the
title in its border, or a rule with no box. Tags print as markers in
front of the title, the rest on a Tags row; links print as QR codes with
their labels; attached PNG, JPEG, GIF and WebP images print after the
card. A line-level markdown subset is laid out without a dependency,
keeping marks inside code spans and URLs, and emoji are removed after a
few typed ones become markers. A card that cannot be laid out prints as
a plain receipt, and the server logs the fault once at ERROR and reports
it to Sentry once. [ntfy.format] and [ntfy.markers] shape the cards; the
markers table is a setting with the user's own keys, also settable as
UBERBRINGER_NTFY_MARKERS=name=value,...

uberbringer token --modules issues a token limited to those modules'
print and preview routes, job status and the module list; each route in
the table says which tokens it takes, and a scope claim that could read
as absent makes the token invalid. image elements take optional, which
also shrinks a too-wide image to the paper; a QR code that could be too
wide for the paper prints with smaller modules; box takes title_bold.
Submit takes a Meta whose source shows in job status and, with a copy
of the request ID, in every worker log line of the job.

The four ntfy cards passed on the TM-T88IV, posted as the client recipe
posts them, and their bytes are pinned in TestPaperReceipts. docs/api.md
describes the modules, the card and the client recipe, with tokens read
from a header file; docs/swagger.json is regenerated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:57:08 -06:00

245 lines
8.1 KiB
Go

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 the golden previews in testdata/*/*.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)
}
})
}
}
// TestNoteShoppingList pins the preview of a titled note with a checklist.
func TestNoteShoppingList(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)
}
}
}