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>
287 lines
11 KiB
Go
287 lines
11 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/gofiber/fiber/v3"
|
|
|
|
"uberbringer/internal/pkg/modules"
|
|
"uberbringer/internal/pkg/printqueue"
|
|
"uberbringer/internal/pkg/receipt"
|
|
)
|
|
|
|
// fakeModule answers according to its body: "skip", "payload", "invalid"
|
|
// and "fail" give those outcomes, and any other body prints as one line of
|
|
// text with the build time.
|
|
type fakeModule struct{}
|
|
|
|
func (fakeModule) Name() string { return "fake" }
|
|
func (fakeModule) Description() string { return "Prints its body" }
|
|
|
|
func (fakeModule) Build(_ context.Context, body []byte, env modules.Env) (receipt.Job, error) {
|
|
switch string(body) {
|
|
case "skip":
|
|
return receipt.Job{}, modules.ErrSkip
|
|
case "payload":
|
|
return receipt.Job{}, &modules.PayloadError{Problems: []string{"text: required", "done[0]: index 5 is out of range"}}
|
|
case "invalid":
|
|
return receipt.Job{Elements: []receipt.Element{{Type: "box"}, {Type: "kv"}}}, nil
|
|
case "fail":
|
|
return receipt.Job{}, errors.New("module broke")
|
|
}
|
|
return receipt.Job{Elements: []receipt.Element{{Type: "text", Text: string(body) + " at " + env.Stamp()}}}, nil
|
|
}
|
|
|
|
func moduleRequest(t *testing.T, target, body string) *http.Request {
|
|
t.Helper()
|
|
req := httptest.NewRequest(http.MethodPost, target, strings.NewReader(body))
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Set("Authorization", "Bearer "+validToken(t))
|
|
return req
|
|
}
|
|
|
|
const shoppingNote = `{"title":"Shopping","text":"Milk, eggs and the good bread from the bakery on Elm St.","items":["Milk","Eggs","Bread"],"done":[2]}`
|
|
|
|
func TestModulePrintAccepted(t *testing.T) {
|
|
jobs := &fakeJobs{nextID: newJobID(t)}
|
|
s := newTestServer(t, jobs, &fakePrinter{})
|
|
resp, body := do(t, s, moduleRequest(t, "/api/v1/print/fake?copies=2&printer=default", "hello"))
|
|
if resp.StatusCode != http.StatusAccepted {
|
|
t.Fatalf("status = %d (%v)", resp.StatusCode, body)
|
|
}
|
|
if body["id"] != "job_01h455vb4pex5vsknk084sn02q" || body["status"] != "queued" {
|
|
t.Errorf("body = %v", body)
|
|
}
|
|
if loc := resp.Header.Get("Location"); loc != "/api/v1/jobs/job_01h455vb4pex5vsknk084sn02q" {
|
|
t.Errorf("Location = %q", loc)
|
|
}
|
|
if len(jobs.submitted) != 1 {
|
|
t.Fatalf("submitted %d jobs", len(jobs.submitted))
|
|
}
|
|
job := jobs.submitted[0]
|
|
if job.Copies != 2 || job.Elements[0].Text != "hello at 29 Nov 21:04" {
|
|
t.Errorf("submitted %+v; want 2 copies of the text with the build time", job)
|
|
}
|
|
}
|
|
|
|
func TestModuleNotePrints(t *testing.T) {
|
|
jobs := &fakeJobs{nextID: newJobID(t)}
|
|
s := newTestServer(t, jobs, &fakePrinter{})
|
|
for _, target := range []string{"/api/v1/print/note", "/api/v1/print/note?printer="} {
|
|
resp, body := send(t, s, moduleRequest(t, target, shoppingNote))
|
|
if resp.StatusCode != http.StatusAccepted {
|
|
t.Fatalf("%s: status = %d (%s)", target, resp.StatusCode, body)
|
|
}
|
|
}
|
|
if len(jobs.submitted) != 2 {
|
|
t.Fatalf("submitted %d jobs, want 2", len(jobs.submitted))
|
|
}
|
|
box := jobs.submitted[0].Elements[0]
|
|
if box.Type != "box" || box.Title != "Shopping" || box.Footer != "29 Nov 21:04" || jobs.submitted[0].Copies != 0 {
|
|
t.Errorf("submitted %+v", jobs.submitted[0])
|
|
}
|
|
}
|
|
|
|
func TestModuleSkip(t *testing.T) {
|
|
jobs := &fakeJobs{nextID: newJobID(t)}
|
|
s := newTestServer(t, jobs, &fakePrinter{})
|
|
for _, target := range []string{"/api/v1/print/fake", "/api/v1/preview/fake"} {
|
|
resp, body := send(t, s, moduleRequest(t, target, "skip"))
|
|
if resp.StatusCode != http.StatusNoContent || len(body) != 0 {
|
|
t.Errorf("%s: status = %d, body %q; want 204 and no body", target, resp.StatusCode, body)
|
|
}
|
|
}
|
|
if len(jobs.submitted) != 0 {
|
|
t.Error("a skipped payload was queued")
|
|
}
|
|
}
|
|
|
|
func TestModuleRefusals(t *testing.T) {
|
|
tests := []struct {
|
|
name, target, body string
|
|
status int
|
|
code, message string
|
|
details []string
|
|
}{
|
|
{"payload problems", "/api/v1/print/fake", "payload", 400, "invalid_payload", `invalid payload for module "fake"`,
|
|
[]string{"text: required", "done[0]: index 5 is out of range"}},
|
|
{"note payload problems", "/api/v1/print/note", `{"title":"x","colour":"red"}`, 400, "invalid_payload", `invalid payload for module "note"`,
|
|
[]string{"colour: unknown field"}},
|
|
{"note without text", "/api/v1/preview/note", `{"title":"x"}`, 400, "invalid_payload", `invalid payload for module "note"`,
|
|
[]string{"text: required"}},
|
|
{"unknown module", "/api/v1/print/notx", "hello", 404, "module_not_found", `module "notx" not found`, nil},
|
|
{"unknown module on preview", "/api/v1/preview/notx?copies=9", "hello", 404, "module_not_found", `module "notx" not found`, nil},
|
|
{"another printer", "/api/v1/print/fake?printer=office", "hello", 400, "unknown_printer",
|
|
`printer "office" is not configured; the only printer is "default"`, nil},
|
|
{"another printer on preview", "/api/v1/preview/fake?printer=Default", "hello", 400, "unknown_printer",
|
|
`printer "Default" is not configured; the only printer is "default"`, nil},
|
|
{"no copies", "/api/v1/print/fake?copies=0", "hello", 400, "invalid_query", "copies must be 1-5", nil},
|
|
{"too many copies", "/api/v1/print/fake?copies=6", "hello", 400, "invalid_query", "copies must be 1-5", nil},
|
|
{"copies not a number", "/api/v1/print/fake?copies=two", "hello", 400, "invalid_query", "copies must be 1-5", nil},
|
|
{"copies twice", "/api/v1/print/fake?copies=1&copies=2", "hello", 400, "invalid_query", `query parameter "copies" is given more than once`, nil},
|
|
{"unknown parameter", "/api/v1/print/fake?copy=2", "hello", 400, "invalid_query",
|
|
`unknown query parameter "copy"; module routes take copies and printer`, nil},
|
|
}
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
jobs := &fakeJobs{nextID: newJobID(t)}
|
|
s, logs := newLoggedServer(t, jobs, &fakePrinter{})
|
|
resp, raw := send(t, s, moduleRequest(t, tt.target, tt.body))
|
|
e := expectError(t, resp, raw, tt.status, tt.code)
|
|
if e.Error != tt.message {
|
|
t.Errorf("error = %q, want %q", e.Error, tt.message)
|
|
}
|
|
if strings.Join(e.Details, "\n") != strings.Join(tt.details, "\n") {
|
|
t.Errorf("details = %q, want %q", e.Details, tt.details)
|
|
}
|
|
if len(jobs.submitted) != 0 {
|
|
t.Error("a refused request was queued")
|
|
}
|
|
if failures := errorLines(logs.lines(t)); len(failures) != 0 {
|
|
t.Errorf("a refusal was logged as a failure: %v", failures)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// A module that builds a job validation refuses has a bug: the client gets
|
|
// 422 with the problems, and the bug is logged and reported once, without
|
|
// the problems, which can quote the payload.
|
|
func TestModuleBuiltAnInvalidJob(t *testing.T) {
|
|
for _, target := range []string{"/api/v1/print/fake", "/api/v1/preview/fake"} {
|
|
t.Run(target, func(t *testing.T) {
|
|
events := captureSentryEvents(t)
|
|
jobs := &fakeJobs{nextID: newJobID(t)}
|
|
s, logs := newLoggedServer(t, jobs, &fakePrinter{})
|
|
resp, raw := send(t, s, moduleRequest(t, target, "invalid"))
|
|
e := expectError(t, resp, raw, http.StatusUnprocessableEntity, "module_failed")
|
|
want := []string{
|
|
"elements[0] (box): text or children is required",
|
|
"elements[1] (kv): pairs: at least one pair is required",
|
|
}
|
|
if e.Error != `module "fake" built an invalid receipt` || strings.Join(e.Details, "\n") != strings.Join(want, "\n") {
|
|
t.Errorf("error = %q, details = %q", e.Error, e.Details)
|
|
}
|
|
if len(jobs.submitted) != 0 {
|
|
t.Error("an invalid job was queued")
|
|
}
|
|
failures := errorLines(logs.lines(t))
|
|
if len(failures) != 1 || failures[0]["msg"] != "module built an invalid receipt" ||
|
|
failures[0]["module"] != "fake" || failures[0]["problems"] != float64(2) {
|
|
t.Errorf("error lines = %v, want one for the module", failures)
|
|
}
|
|
logs.mu.Lock()
|
|
logged := logs.buf.String()
|
|
logs.mu.Unlock()
|
|
if strings.Contains(logged, "pairs: at least one") {
|
|
t.Error("the problems were logged")
|
|
}
|
|
if n := events.count(); n != 1 {
|
|
t.Errorf("%d Sentry events, want 1", n)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestModuleUnexpectedError(t *testing.T) {
|
|
events := captureSentryEvents(t)
|
|
s, logs := newLoggedServer(t, &fakeJobs{}, &fakePrinter{})
|
|
resp, raw := send(t, s, moduleRequest(t, "/api/v1/print/fake", "fail"))
|
|
expectError(t, resp, raw, http.StatusInternalServerError, "internal_error")
|
|
failures := errorLines(logs.lines(t))
|
|
if len(failures) != 1 || failures[0]["err"] != "module fake: module broke" {
|
|
t.Errorf("error lines = %v", failures)
|
|
}
|
|
if n := events.count(); n != 1 {
|
|
t.Errorf("%d Sentry events, want 1", n)
|
|
}
|
|
}
|
|
|
|
func TestModuleQueueRefusals(t *testing.T) {
|
|
tests := []struct {
|
|
err error
|
|
code string
|
|
wantRetryAfter bool
|
|
}{
|
|
{printqueue.ErrQueueFull, "queue_full", true},
|
|
{printqueue.ErrClosed, "shutting_down", false},
|
|
}
|
|
for _, tt := range tests {
|
|
t.Run(tt.code, func(t *testing.T) {
|
|
s := newTestServer(t, &fakeJobs{submitErr: tt.err}, &fakePrinter{})
|
|
resp, body := send(t, s, moduleRequest(t, "/api/v1/print/note", shoppingNote))
|
|
expectError(t, resp, body, http.StatusServiceUnavailable, tt.code)
|
|
if got := resp.Header.Get("Retry-After") == "10"; got != tt.wantRetryAfter {
|
|
t.Errorf("Retry-After = %q", resp.Header.Get("Retry-After"))
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestModuleList(t *testing.T) {
|
|
s := newTestServer(t, &fakeJobs{}, &fakePrinter{})
|
|
req := httptest.NewRequest(http.MethodGet, "/api/v1/modules", nil)
|
|
req.Header.Set("Authorization", "Bearer "+validToken(t))
|
|
resp, body := send(t, s, req)
|
|
if resp.StatusCode != http.StatusOK {
|
|
t.Fatalf("status = %d (%s)", resp.StatusCode, body)
|
|
}
|
|
want := `[{"name":"fake","description":"Prints its body"},{"name":"note","description":"Boxed note with an optional checklist"}]`
|
|
if string(body) != want {
|
|
t.Errorf("body = %s, want %s", body, want)
|
|
}
|
|
if cc := resp.Header.Get(fiber.HeaderCacheControl); cc != "no-store" {
|
|
t.Errorf("Cache-Control = %q, want no-store", cc)
|
|
}
|
|
}
|
|
|
|
func TestModulePreview(t *testing.T) {
|
|
jobs := &fakeJobs{}
|
|
s := newTestServer(t, jobs, &fakePrinter{})
|
|
resp, body := send(t, s, moduleRequest(t, "/api/v1/preview/note", shoppingNote))
|
|
if resp.StatusCode != http.StatusOK {
|
|
t.Fatalf("status = %d (%s)", resp.StatusCode, body)
|
|
}
|
|
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 string(body) != want {
|
|
t.Errorf("body =\n%s\nwant\n%s", body, want)
|
|
}
|
|
if len(jobs.submitted) != 0 {
|
|
t.Error("a preview was queued for printing")
|
|
}
|
|
|
|
req := moduleRequest(t, "/api/v1/preview/fake?copies=3", "hi")
|
|
req.Header.Set("Accept", "application/json")
|
|
resp, raw := do(t, s, req)
|
|
if resp.StatusCode != http.StatusOK || raw["line_count"] != float64(3) {
|
|
t.Errorf("status %d, body %v; want three copies of one line", resp.StatusCode, raw)
|
|
}
|
|
}
|
|
|
|
func TestModulePreviewTooManyLines(t *testing.T) {
|
|
s, logs := newLoggedServer(t, &fakeJobs{}, &fakePrinter{})
|
|
s.previewer = testRenderer(5)
|
|
resp, raw := send(t, s, moduleRequest(t, "/api/v1/preview/note", shoppingNote))
|
|
e := expectError(t, resp, raw, http.StatusUnprocessableEntity, "too_many_lines")
|
|
if e.Error != "receipt would print 8 lines, limit is 5" {
|
|
t.Errorf("error = %q", e.Error)
|
|
}
|
|
if failures := errorLines(logs.lines(t)); len(failures) != 0 {
|
|
t.Errorf("a refusal was logged as a failure: %v", failures)
|
|
}
|
|
}
|