package wireschema import ( "encoding/json" "fmt" "go/ast" "go/parser" "go/token" "math/big" "os" "path/filepath" "reflect" "regexp" "slices" "strconv" "strings" "testing" "time" "amadan.net/rastrillo/rastrillo/budget" ) func TestMain(m *testing.M) { os.Exit(budget.Main(m)) } type sampleInner struct { N int64 `json:"n"` } type sample struct { Always string `json:"always"` Maybe string `json:"maybe,omitempty"` Nil *sampleInner `json:"nil"` Gone *sampleInner `json:"gone,omitempty"` Struct sampleInner `json:"struct,omitempty"` List []string `json:"list"` Short []string `json:"short,omitempty"` Labels map[string]string `json:"labels"` At time.Time `json:"at"` Raw json.RawMessage `json:"raw"` Skipped string `json:"-"` unwritten string } // The schema says what encoding/json writes: a field omitempty can drop // is optional, and never null; a struct value is always written; a nil // pointer, slice or map that is written is null. func TestSchemaFollowsEncodingJSON(t *testing.T) { g := newGen() raw, _ := json.Marshal(g.ref(sample{})) if string(raw) != `{"$ref":"#/components/schemas/sample"}` { t.Fatal(string(raw)) } got, _ := json.Marshal(g.defs["sample"]) want := `{"type":"object","properties":{` + `"always":{"type":"string"},` + `"maybe":{"type":"string"},` + `"nil":{"anyOf":[{"$ref":"#/components/schemas/sampleInner"},{"type":"null"}]},` + `"gone":{"$ref":"#/components/schemas/sampleInner"},` + `"struct":{"$ref":"#/components/schemas/sampleInner"},` + `"list":{"type":["array","null"],"items":{"type":"string"}},` + `"short":{"type":"array","items":{"type":"string"}},` + `"labels":{"type":["object","null"],"additionalProperties":{"type":"string"}},` + `"at":{"type":"string","format":"date-time"},` + `"raw":{}},` + `"required":["always","nil","struct","list","labels","at","raw"],` + `"additionalProperties":false,"x-go-type":"wireschema.sample"}` if string(got) != want { t.Fatalf("got %s\nwant %s", got, want) } _ = sample{}.unwritten } func TestValidateRejectsWhatTheSchemaDoesNot(t *testing.T) { defs := map[string]any{} for name, raw := range Generate() { var v any if err := json.Unmarshal(raw, &v); err != nil { t.Fatal(err) } defs[name] = v } delta := map[string]any{"$ref": "#/components/schemas/Delta"} for doc, want := range map[string]string{ `{"turn_id":"t","offset":0,"text":"a"}`: "", `{"turn_id":"t","offset":0,"text":"a","extra":true}`: "invented extra", `{"turn_id":"t","offset":0}`: "missing text", `{"turn_id":"t","offset":"0","text":"a"}`: "string is not", `{"turn_id":"t","offset":0.5,"text":"a"}`: "number is not", } { var v any if err := json.Unmarshal([]byte(doc), &v); err != nil { t.Fatal(err) } err := Validate(defs, v, delta, "$") if want == "" && err != nil || want != "" && (err == nil || !strings.Contains(err.Error(), want)) { t.Errorf("%s: %v, want %q", doc, err, want) } } } // TestDump writes the generated schemas and each operation's bodies, // for updating docs/api/equipo-v1.openapi.json, when // EQUIPO_DEVICE_SCHEMAS names a file. func TestDump(t *testing.T) { path := os.Getenv("EQUIPO_DEVICE_SCHEMAS") if path == "" { t.Skip("set EQUIPO_DEVICE_SCHEMAS to write the generated schemas") } ops := map[string]any{} for key, op := range Ops { out := map[string]any{} for status, v := range op.Out { out[status] = nil if v != nil { out[status] = Body(v) } } o := map[string]any{"out": out} if op.In != nil { o["in"] = RequestBody(op.In) } ops[key] = o } raw, err := json.MarshalIndent(map[string]any{"schemas": Generate(), "ops": ops}, "", " ") if err != nil { t.Fatal(err) } if err := os.WriteFile(path, raw, 0o644); err != nil { t.Fatal(err) } } // families says where each enum in Enums comes from: the internal/wire // string constants named with prefix, less those named in other (a // different field's, recorded here so a new constant must be placed). // zero are values the field takes that no constant names. var families = map[string]struct{ prefix, other, zero string }{ "ChangedFile.status": {"ChangeFile", "", ""}, "Turn.state": {"Turn", "TurnPerson TurnMoveIn TurnExplore TurnHousekeeping TurnSpecialistAdded TurnTeamUpdate", `""`}, "Turn.kind": {"Turn", "TurnQueued TurnRunning TurnWaiting TurnReplied TurnFailed TurnCancelled TurnTeamUpdate", ""}, // team_update: the Assistant's lane only "Message.role": {"Role", "RolePrimary RoleWorker RoleAssistant", `""`}, // assistant: the Assistant's lane only "Runner.role": {"Role", "RolePerson RoleCoordinator RoleAssistant", `""`}, "MessageAttachment.kind": {"Attachment", "AttachmentRepo", ""}, // a project's attachment "Activity.kind": {"Activity", "ActivityRead ActivitySearch ActivityEdit ActivityRun ActivityOther", ""}, "ActivityLine.kind": {"Activity", "ActivityThink ActivityTool", ""}, "Coordinator.state": {"Coordinator", "CoordinatorLooking CoordinatorMerging", ""}, // TaskActivity kinds "Project.state": {"Project", "", ""}, "Connection.state": {"Conn", "", ""}, "Question.state": {"Question", "", ""}, "Task.stage": {"Stage", "", ""}, "Task.kind": {"Kind", "KindAPIKey KindSubscription KindToken", ""}, // connection kinds "Step.state": {"Step", "", ""}, "Advice.kind": {"Advice", "AdviceOpen AdviceActed AdviceDismissed AdviceWithdrawn", ""}, "Advice.state": {"Advice", "AdviceBudgetNear AdvicePreferSwitch AdviceDeferTasks AdviceHeldLong", ""}, "Specialist.state": {"Specialist", "SpecialistChecks SpecialistCopy SpecialistEngineering SpecialistMerge SpecialistPreview SpecialistPublish SpecialistResearch SpecialistReview", ""}, // step specialists "HousekeepingAction.state": {"Action", "", ""}, "TaskPriority.priority": {"Priority", "PrioritySetByCoordinator PrioritySetByPerson", ""}, "SetPriority.priority": {"Priority", "PrioritySetByCoordinator PrioritySetByPerson", ""}, "TaskPriority.set_by": {"PrioritySetBy", "", ""}, "UsageTotals.period": {"Usage", "UsageByConnection UsageByRole UsageByProject UsageByTask UsageByModel UsageProbe", ""}, // probe: a usage row's role "UsageTotals.by": {"UsageBy", "", ""}, "Event.type": {"Event", "EventPing EventGlance", ""}, // a ping is not an Event; a glance is the Assistant's "RegisterPush.environment": {"APNs", "", ""}, "RegisterPush.platform": {"Platform", "", ""}, "PushRegistration.environment": {"APNs", "", ""}, "PushRegistration.platform": {"Platform", "", ""}, } // parseGo parses the Go files in dir, tests apart. func parseGo(t *testing.T, dir string) []*ast.File { t.Helper() names, _ := filepath.Glob(filepath.Join(dir, "*.go")) var out []*ast.File fset := token.NewFileSet() for _, name := range names { if strings.HasSuffix(name, "_test.go") { continue } f, err := parser.ParseFile(fset, name, nil, 0) if err != nil { t.Fatal(err) } out = append(out, f) } if len(out) == 0 { t.Fatal("no Go files in " + dir) } return out } // wireConstants are internal/wire's string constants by name. func wireConstants(t *testing.T) map[string]string { t.Helper() files := parseGo(t, "..") out := map[string]string{} for _, f := range files { for _, d := range f.Decls { if g, ok := d.(*ast.GenDecl); ok && g.Tok == token.CONST { for _, spec := range g.Specs { v := spec.(*ast.ValueSpec) for i, name := range v.Names { if i < len(v.Values) { if lit, ok := v.Values[i].(*ast.BasicLit); ok && lit.Kind == token.STRING { out[name.Name], _ = strconv.Unquote(lit.Value) } } } } } } } return out } // Each enum is exactly its family of wire constants: a new constant // fails here until it is placed. func TestEnumsAreTheWireConstants(t *testing.T) { consts := wireConstants(t) for key := range Enums { if _, ok := families[key]; !ok && key != "Event.resource" && !strings.HasSuffix(key, "Conflict.code") { t.Errorf("%s has no family of wire constants", key) } } for key, f := range families { want := []string{} for name, value := range consts { if strings.HasPrefix(name, f.prefix) && !slices.Contains(strings.Fields(f.other), name) { want = append(want, value) } } if f.zero != "" { want = append(want, "") } got := slices.Clone(Enums[key]) slices.Sort(want) slices.Sort(got) if !slices.Equal(got, want) { t.Errorf("%s is %q; its wire constants are %q", key, got, want) } } } // Every event the engine appends (txn.event in internal/equipo/chat) has // a schema, and every schema an event: by type and resource. func TestEventDataIsWhatTheEngineAppends(t *testing.T) { consts := wireConstants(t) files, _ := filepath.Glob("../../equipo/chat/*.go") call := regexp.MustCompile(`\.event\(([^,]+), ([^,]+), ([^,]+), ([^,]+),`) resolve := func(arg string) string { if v, err := strconv.Unquote(arg); err == nil { return v } if v, ok := consts[strings.TrimPrefix(arg, "wire.")]; ok && strings.HasPrefix(arg, "wire.") { return v } t.Errorf("an event's type or resource is %s, not a constant", arg) return "" } found := map[string]bool{} for _, file := range files { if strings.HasSuffix(file, "_test.go") { continue } src, err := os.ReadFile(file) if err != nil { t.Fatal(err) } for _, m := range call.FindAllStringSubmatch(string(src), -1) { found[resolve(m[3])+" "+resolve(m[4])] = true } } for key := range found { if _, ok := EventData[key]; !ok { t.Errorf("the engine appends %s events, which have no schema", key) } } for key := range EventData { if !found[key] { t.Errorf("nothing appends %s events", key) } } } // The generator refuses what it cannot describe, rather than guess. func TestGeneratorRefusesWhatItCannotDescribe(t *testing.T) { type text struct{ big.Int } type stringy struct { N int64 `json:"n,string"` } type embedded struct { *sampleInner } type keyed struct { M map[int]string `json:"m"` } type marshals struct { V big.Float `json:"v"` } for name, v := range map[string]any{"text": text{}, "string": stringy{}, "embedded": embedded{}, "keyed": keyed{}, "marshals": marshals{}} { func() { defer func() { if recover() == nil { t.Errorf("%s: described", name) } }() newGen().ref(v) }() } type raw struct { R json.RawMessage `json:"r,omitempty"` } g := newGen() g.ref(raw{}) if got, _ := json.Marshal(g.defs["raw"]); !strings.Contains(string(got), `"properties":{"r":{}}`) || strings.Contains(string(got), "required") { t.Errorf("an omitempty RawMessage: %s", got) } } // A request body requires nothing (wire.Strict takes a missing field), // and an input type that is also an answer's takes the suffix Input. func TestRequestBodies(t *testing.T) { out := newGen() out.ref(sample{}) in := newGen() in.input, in.outputs = true, out.types if got, _ := json.Marshal(in.ref(sample{})); string(got) != `{"$ref":"#/components/schemas/sampleInput"}` { t.Fatal(string(got)) } if got, _ := json.Marshal(in.defs["sampleInput"]); strings.Contains(string(got), `"required"`) { t.Errorf("an input requires fields: %s", got) } for name, s := range Generate() { var v map[string]any if err := json.Unmarshal(s, &v); err != nil { t.Fatal(err) } if _, required := v["required"]; required && strings.HasSuffix(name, "Input") && InputRequired[name] == nil { t.Errorf("%s requires fields", name) } } } // handlerSource is internal/equipo/chat read for what its person API // handlers write: the functions by name, HTTP's and Store's methods // apart. type handlerSource struct { http, store, funcs map[string]*ast.FuncDecl } func readHandlers(t *testing.T) handlerSource { t.Helper() files := parseGo(t, "../../equipo/chat") src := handlerSource{map[string]*ast.FuncDecl{}, map[string]*ast.FuncDecl{}, map[string]*ast.FuncDecl{}} for _, f := range files { for _, d := range f.Decls { fn, ok := d.(*ast.FuncDecl) if !ok { continue } switch recv := receiver(fn); recv { case "HTTP": src.http[fn.Name.Name] = fn case "Store": src.store[fn.Name.Name] = fn case "": src.funcs[fn.Name.Name] = fn } } } return src } func receiver(fn *ast.FuncDecl) string { if fn.Recv == nil { return "" } if star, ok := fn.Recv.List[0].Type.(*ast.StarExpr); ok { if id, ok := star.X.(*ast.Ident); ok { return id.Name } } return "other" } var statuses = map[string]string{"http.StatusOK": "200", "http.StatusCreated": "201", "http.StatusAccepted": "202", "http.StatusNoContent": "204", "http.StatusConflict": "409"} // typeName is a type expression's wire name: "Task" for wire.Task. func typeName(e ast.Expr) string { if sel, ok := e.(*ast.SelectorExpr); ok { if pkg, ok := sel.X.(*ast.Ident); ok && pkg.Name == "wire" { return sel.Sel.Name } } if _, ok := e.(*ast.MapType); ok { return "map" } return "?" + fmt.Sprintf("%T", e) } // writes is what fn writes, by status: the wire type's name, "" for no // body, "bytes" for a file, "map" for a map literal. in is the request // body's type, if it reads one. func (src handlerSource) writes(t *testing.T, fn *ast.FuncDecl, out map[string]string, in *string) { t.Helper() params := map[string]*ast.FuncType{} for _, f := range fn.Type.Params.List { if ft, ok := f.Type.(*ast.FuncType); ok { for _, n := range f.Names { params[n.Name] = ft } } } // resultOf is the first result type of what a call calls. resultOf := func(call *ast.CallExpr) string { switch fun := call.Fun.(type) { case *ast.Ident: if ft := params[fun.Name]; ft != nil { return typeName(ft.Results.List[0].Type) } case *ast.SelectorExpr: if m := src.store[fun.Sel.Name]; m != nil { return typeName(m.Type.Results.List[0].Type) } } return "?call" } assigned := map[string][]ast.Expr{} // ident -> every value assigned vars := map[string]string{} // var in wire.T writes := false for n := range ast.Preorder(fn.Body) { switch x := n.(type) { case *ast.AssignStmt: for i, l := range x.Lhs { if id, ok := l.(*ast.Ident); ok { if len(x.Rhs) == len(x.Lhs) { assigned[id.Name] = append(assigned[id.Name], x.Rhs[i]) } else if i == 0 && len(x.Rhs) == 1 { assigned[id.Name] = append(assigned[id.Name], x.Rhs[0]) } } } case *ast.ValueSpec: for _, n := range x.Names { if x.Type != nil { vars[n.Name] = typeName(x.Type) } } case *ast.CallExpr: if sel, ok := x.Fun.(*ast.SelectorExpr); ok && sel.Sel.Name == "Write" { writes = true } } } status := func(e ast.Expr) []string { switch x := e.(type) { case *ast.BasicLit: return []string{x.Value} case *ast.SelectorExpr: return []string{statuses[fmt.Sprint(x.X, ".", x.Sel.Name)]} case *ast.Ident: var all []string for _, v := range assigned[x.Name] { if sel, ok := v.(*ast.SelectorExpr); ok { all = append(all, statuses[fmt.Sprint(sel.X, ".", sel.Sel.Name)]) } } return all } return []string{"?status"} } body := func(e ast.Expr) string { switch x := e.(type) { case *ast.CompositeLit: return typeName(x.Type) case *ast.Ident: for _, v := range assigned[x.Name] { if call, ok := v.(*ast.CallExpr); ok { return resultOf(call) } } } return "?body" } for n := range ast.Preorder(fn.Body) { call, ok := n.(*ast.CallExpr) if !ok { continue } switch fun := call.Fun.(type) { case *ast.Ident: switch { case fun.Name == "writeJSON": for _, s := range status(call.Args[1]) { out[s] = body(call.Args[2]) } case fun.Name == "readJSON": if u, ok := call.Args[1].(*ast.UnaryExpr); ok { *in = vars[u.X.(*ast.Ident).Name] } case fun.Name == "ReadUpload": *in = "bytes" case src.funcs[fun.Name] != nil: src.writes(t, src.funcs[fun.Name], out, in) } case *ast.SelectorExpr: switch { case fun.Sel.Name == "WriteHeader": for _, s := range status(call.Args[0]) { out[s] = "" if writes { out[s] = "bytes" } } case fun.Sel.Name == "Strict" && fmt.Sprint(fun.X) == "wire": if u, ok := call.Args[1].(*ast.UnaryExpr); ok { *in = vars[u.X.(*ast.Ident).Name] } case fmt.Sprint(fun.X) == "h" && src.http[fun.Sel.Name] != nil: src.writes(t, src.http[fun.Sel.Name], out, in) } } } } // handlerOf is the HTTP method a route's handler expression ends in: // h.bearer(h.name), h.thinOr(..., h.bearer(h.name)), h.bearer(h.name(...)). func handlerOf(e ast.Expr) string { switch x := e.(type) { case *ast.CallExpr: if sel, ok := x.Fun.(*ast.SelectorExpr); ok && sel.Sel.Name != "bearer" && sel.Sel.Name != "thinOr" { return sel.Sel.Name } return handlerOf(x.Args[len(x.Args)-1]) case *ast.SelectorExpr: return x.Sel.Name } return "" } // Ops is what the handlers write: each route's request body and its // answers' statuses and wire types, read from internal/equipo/chat. // The event stream writes text, not JSON, and is held by the fixtures. func TestOpsAreWhatTheHandlersWrite(t *testing.T) { src := readHandlers(t) seen := map[string]bool{} for _, mount := range []string{"Mount", "mountHousekeeping", "mountUsage"} { for n := range ast.Preorder(src.http[mount].Body) { call, ok := n.(*ast.CallExpr) if !ok || len(call.Args) != 2 { continue } fun, isSel := call.Fun.(*ast.SelectorExpr) lit, isLit := call.Args[0].(*ast.BasicLit) if !isSel || !isLit || !slices.Contains([]string{"Get", "Post", "Put", "Delete"}, fun.Sel.Name) { continue } path, _ := strconv.Unquote(lit.Value) key := strings.ToUpper(fun.Sel.Name) + " " + path seen[key] = true op, ok := Ops[key] if !ok { t.Errorf("%s is served but not in Ops", key) continue } if key == "GET /events" { continue } name := handlerOf(call.Args[1]) fn := src.http[name] if fn == nil { t.Errorf("%s: cannot find its handler %q", key, name) continue } got, in := map[string]string{}, "" src.writes(t, fn, got, &in) want := map[string]string{} for status, v := range op.Out { want[status] = opName(v) // A handler's primary body must be one of its documented // variants. Compatibility routes and fail() supply the others. if variants, ok := v.(OneOf); ok { for _, variant := range variants { if opName(variant) == got[status] { want[status] = got[status] break } } } } if !reflect.DeepEqual(got, want) { t.Errorf("%s (%s) writes %v; Ops says %v", key, name, got, want) } if wantIn := opName(op.In); in != wantIn { t.Errorf("%s (%s) reads %q; Ops says %q", key, name, in, wantIn) } continue } } for key := range Ops { if !seen[key] { t.Errorf("%s is in Ops but not served", key) } } } func opName(v any) string { switch v.(type) { case nil: return "" case Bytes: return "bytes" } if name := reflect.TypeOf(v).Name(); name != "" { return name } return "map" } // The native routes' handlers refuse a body missing these fields, so the // document must say so: an app built from it would otherwise send none. func TestNativeInputsRequireWhatTheirHandlersRequire(t *testing.T) { defs := map[string]any{} for name, raw := range Generate() { var s any if err := json.Unmarshal(raw, &s); err != nil { t.Fatal(err) } defs[name] = s } for name, cases := range map[string][]string{ "BeginDeviceInput": {`{}`, `{"label":"phone"}`, `{"public_key":"key"}`}, "NativeRequest": {`{}`, `{"verifier":"v"}`, `{"assertion":"a","choice":"new"}`}, } { s := map[string]any{"$ref": "#/components/schemas/" + name} for _, body := range cases { var v any if err := json.Unmarshal([]byte(body), &v); err != nil { t.Fatal(err) } if Validate(defs, v, s, name) == nil { t.Errorf("%s accepts %s", name, body) } } } for name, body := range map[string]string{"BeginDeviceInput": `{"public_key":"key","label":"phone"}`, "NativeRequest": `{"assertion":"a","verifier":"v"}`} { var v any _ = json.Unmarshal([]byte(body), &v) if err := Validate(defs, v, map[string]any{"$ref": "#/components/schemas/" + name}, name); err != nil { t.Errorf("%s refuses a complete body: %v", name, err) } } }