| 1 | package wireschema |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "fmt" |
| 6 | "go/ast" |
| 7 | "go/parser" |
| 8 | "go/token" |
| 9 | "math/big" |
| 10 | "os" |
| 11 | "path/filepath" |
| 12 | "reflect" |
| 13 | "regexp" |
| 14 | "slices" |
| 15 | "strconv" |
| 16 | "strings" |
| 17 | "testing" |
| 18 | "time" |
| 19 | |
| 20 | "amadan.net/rastrillo/rastrillo/budget" |
| 21 | ) |
| 22 | |
| 23 | func TestMain(m *testing.M) { os.Exit(budget.Main(m)) } |
| 24 | |
| 25 | type sampleInner struct { |
| 26 | N int64 `json:"n"` |
| 27 | } |
| 28 | |
| 29 | type sample struct { |
| 30 | Always string `json:"always"` |
| 31 | Maybe string `json:"maybe,omitempty"` |
| 32 | Nil *sampleInner `json:"nil"` |
| 33 | Gone *sampleInner `json:"gone,omitempty"` |
| 34 | Struct sampleInner `json:"struct,omitempty"` |
| 35 | List []string `json:"list"` |
| 36 | Short []string `json:"short,omitempty"` |
| 37 | Labels map[string]string `json:"labels"` |
| 38 | At time.Time `json:"at"` |
| 39 | Raw json.RawMessage `json:"raw"` |
| 40 | Skipped string `json:"-"` |
| 41 | unwritten string |
| 42 | } |
| 43 | |
| 44 | // The schema says what encoding/json writes: a field omitempty can drop |
| 45 | // is optional, and never null; a struct value is always written; a nil |
| 46 | // pointer, slice or map that is written is null. |
| 47 | func TestSchemaFollowsEncodingJSON(t *testing.T) { |
| 48 | g := newGen() |
| 49 | raw, _ := json.Marshal(g.ref(sample{})) |
| 50 | if string(raw) != `{"$ref":"#/components/schemas/sample"}` { |
| 51 | t.Fatal(string(raw)) |
| 52 | } |
| 53 | got, _ := json.Marshal(g.defs["sample"]) |
| 54 | want := `{"type":"object","properties":{` + |
| 55 | `"always":{"type":"string"},` + |
| 56 | `"maybe":{"type":"string"},` + |
| 57 | `"nil":{"anyOf":[{"$ref":"#/components/schemas/sampleInner"},{"type":"null"}]},` + |
| 58 | `"gone":{"$ref":"#/components/schemas/sampleInner"},` + |
| 59 | `"struct":{"$ref":"#/components/schemas/sampleInner"},` + |
| 60 | `"list":{"type":["array","null"],"items":{"type":"string"}},` + |
| 61 | `"short":{"type":"array","items":{"type":"string"}},` + |
| 62 | `"labels":{"type":["object","null"],"additionalProperties":{"type":"string"}},` + |
| 63 | `"at":{"type":"string","format":"date-time"},` + |
| 64 | `"raw":{}},` + |
| 65 | `"required":["always","nil","struct","list","labels","at","raw"],` + |
| 66 | `"additionalProperties":false,"x-go-type":"wireschema.sample"}` |
| 67 | if string(got) != want { |
| 68 | t.Fatalf("got %s\nwant %s", got, want) |
| 69 | } |
| 70 | _ = sample{}.unwritten |
| 71 | } |
| 72 | |
| 73 | func TestValidateRejectsWhatTheSchemaDoesNot(t *testing.T) { |
| 74 | defs := map[string]any{} |
| 75 | for name, raw := range Generate() { |
| 76 | var v any |
| 77 | if err := json.Unmarshal(raw, &v); err != nil { |
| 78 | t.Fatal(err) |
| 79 | } |
| 80 | defs[name] = v |
| 81 | } |
| 82 | delta := map[string]any{"$ref": "#/components/schemas/Delta"} |
| 83 | for doc, want := range map[string]string{ |
| 84 | `{"turn_id":"t","offset":0,"text":"a"}`: "", |
| 85 | `{"turn_id":"t","offset":0,"text":"a","extra":true}`: "invented extra", |
| 86 | `{"turn_id":"t","offset":0}`: "missing text", |
| 87 | `{"turn_id":"t","offset":"0","text":"a"}`: "string is not", |
| 88 | `{"turn_id":"t","offset":0.5,"text":"a"}`: "number is not", |
| 89 | } { |
| 90 | var v any |
| 91 | if err := json.Unmarshal([]byte(doc), &v); err != nil { |
| 92 | t.Fatal(err) |
| 93 | } |
| 94 | err := Validate(defs, v, delta, "$") |
| 95 | if want == "" && err != nil || want != "" && (err == nil || !strings.Contains(err.Error(), want)) { |
| 96 | t.Errorf("%s: %v, want %q", doc, err, want) |
| 97 | } |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | // TestDump writes the generated schemas and each operation's bodies, |
| 102 | // for updating docs/api/equipo-v1.openapi.json, when |
| 103 | // EQUIPO_DEVICE_SCHEMAS names a file. |
| 104 | func TestDump(t *testing.T) { |
| 105 | path := os.Getenv("EQUIPO_DEVICE_SCHEMAS") |
| 106 | if path == "" { |
| 107 | t.Skip("set EQUIPO_DEVICE_SCHEMAS to write the generated schemas") |
| 108 | } |
| 109 | ops := map[string]any{} |
| 110 | for key, op := range Ops { |
| 111 | out := map[string]any{} |
| 112 | for status, v := range op.Out { |
| 113 | out[status] = nil |
| 114 | if v != nil { |
| 115 | out[status] = Body(v) |
| 116 | } |
| 117 | } |
| 118 | o := map[string]any{"out": out} |
| 119 | if op.In != nil { |
| 120 | o["in"] = RequestBody(op.In) |
| 121 | } |
| 122 | ops[key] = o |
| 123 | } |
| 124 | raw, err := json.MarshalIndent(map[string]any{"schemas": Generate(), "ops": ops}, "", " ") |
| 125 | if err != nil { |
| 126 | t.Fatal(err) |
| 127 | } |
| 128 | if err := os.WriteFile(path, raw, 0o644); err != nil { |
| 129 | t.Fatal(err) |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | // families says where each enum in Enums comes from: the internal/wire |
| 134 | // string constants named with prefix, less those named in other (a |
| 135 | // different field's, recorded here so a new constant must be placed). |
| 136 | // zero are values the field takes that no constant names. |
| 137 | var families = map[string]struct{ prefix, other, zero string }{ |
| 138 | "ChangedFile.status": {"ChangeFile", "", ""}, |
| 139 | "Turn.state": {"Turn", "TurnPerson TurnMoveIn TurnExplore TurnHousekeeping TurnSpecialistAdded TurnTeamUpdate", `""`}, |
| 140 | "Turn.kind": {"Turn", "TurnQueued TurnRunning TurnWaiting TurnReplied TurnFailed TurnCancelled TurnTeamUpdate", ""}, // team_update: the Assistant's lane only |
| 141 | "Message.role": {"Role", "RolePrimary RoleWorker RoleAssistant", `""`}, // assistant: the Assistant's lane only |
| 142 | "Runner.role": {"Role", "RolePerson RoleCoordinator RoleAssistant", `""`}, |
| 143 | "MessageAttachment.kind": {"Attachment", "AttachmentRepo", ""}, // a project's attachment |
| 144 | "Activity.kind": {"Activity", "ActivityRead ActivitySearch ActivityEdit ActivityRun ActivityOther", ""}, |
| 145 | "ActivityLine.kind": {"Activity", "ActivityThink ActivityTool", ""}, |
| 146 | "Coordinator.state": {"Coordinator", "CoordinatorLooking CoordinatorMerging", ""}, // TaskActivity kinds |
| 147 | "Project.state": {"Project", "", ""}, |
| 148 | "Connection.state": {"Conn", "", ""}, |
| 149 | "Question.state": {"Question", "", ""}, |
| 150 | "Task.stage": {"Stage", "", ""}, |
| 151 | "Task.kind": {"Kind", "KindAPIKey KindSubscription KindToken", ""}, // connection kinds |
| 152 | "Step.state": {"Step", "", ""}, |
| 153 | "Advice.kind": {"Advice", "AdviceOpen AdviceActed AdviceDismissed AdviceWithdrawn", ""}, |
| 154 | "Advice.state": {"Advice", "AdviceBudgetNear AdvicePreferSwitch AdviceDeferTasks AdviceHeldLong", ""}, |
| 155 | "Specialist.state": {"Specialist", "SpecialistChecks SpecialistCopy SpecialistEngineering SpecialistMerge SpecialistPreview SpecialistPublish SpecialistResearch SpecialistReview", ""}, // step specialists |
| 156 | "HousekeepingAction.state": {"Action", "", ""}, |
| 157 | "TaskPriority.priority": {"Priority", "PrioritySetByCoordinator PrioritySetByPerson", ""}, |
| 158 | "SetPriority.priority": {"Priority", "PrioritySetByCoordinator PrioritySetByPerson", ""}, |
| 159 | "TaskPriority.set_by": {"PrioritySetBy", "", ""}, |
| 160 | "UsageTotals.period": {"Usage", "UsageByConnection UsageByRole UsageByProject UsageByTask UsageByModel UsageProbe", ""}, // probe: a usage row's role |
| 161 | "UsageTotals.by": {"UsageBy", "", ""}, |
| 162 | "Event.type": {"Event", "EventPing EventGlance", ""}, // a ping is not an Event; a glance is the Assistant's |
| 163 | |
| 164 | "RegisterPush.environment": {"APNs", "", ""}, |
| 165 | "RegisterPush.platform": {"Platform", "", ""}, |
| 166 | "PushRegistration.environment": {"APNs", "", ""}, |
| 167 | "PushRegistration.platform": {"Platform", "", ""}, |
| 168 | } |
| 169 | |
| 170 | // parseGo parses the Go files in dir, tests apart. |
| 171 | func parseGo(t *testing.T, dir string) []*ast.File { |
| 172 | t.Helper() |
| 173 | names, _ := filepath.Glob(filepath.Join(dir, "*.go")) |
| 174 | var out []*ast.File |
| 175 | fset := token.NewFileSet() |
| 176 | for _, name := range names { |
| 177 | if strings.HasSuffix(name, "_test.go") { |
| 178 | continue |
| 179 | } |
| 180 | f, err := parser.ParseFile(fset, name, nil, 0) |
| 181 | if err != nil { |
| 182 | t.Fatal(err) |
| 183 | } |
| 184 | out = append(out, f) |
| 185 | } |
| 186 | if len(out) == 0 { |
| 187 | t.Fatal("no Go files in " + dir) |
| 188 | } |
| 189 | return out |
| 190 | } |
| 191 | |
| 192 | // wireConstants are internal/wire's string constants by name. |
| 193 | func wireConstants(t *testing.T) map[string]string { |
| 194 | t.Helper() |
| 195 | files := parseGo(t, "..") |
| 196 | out := map[string]string{} |
| 197 | for _, f := range files { |
| 198 | for _, d := range f.Decls { |
| 199 | if g, ok := d.(*ast.GenDecl); ok && g.Tok == token.CONST { |
| 200 | for _, spec := range g.Specs { |
| 201 | v := spec.(*ast.ValueSpec) |
| 202 | for i, name := range v.Names { |
| 203 | if i < len(v.Values) { |
| 204 | if lit, ok := v.Values[i].(*ast.BasicLit); ok && lit.Kind == token.STRING { |
| 205 | out[name.Name], _ = strconv.Unquote(lit.Value) |
| 206 | } |
| 207 | } |
| 208 | } |
| 209 | } |
| 210 | } |
| 211 | } |
| 212 | } |
| 213 | return out |
| 214 | } |
| 215 | |
| 216 | // Each enum is exactly its family of wire constants: a new constant |
| 217 | // fails here until it is placed. |
| 218 | func TestEnumsAreTheWireConstants(t *testing.T) { |
| 219 | consts := wireConstants(t) |
| 220 | for key := range Enums { |
| 221 | if _, ok := families[key]; !ok && key != "Event.resource" && !strings.HasSuffix(key, "Conflict.code") { |
| 222 | t.Errorf("%s has no family of wire constants", key) |
| 223 | } |
| 224 | } |
| 225 | for key, f := range families { |
| 226 | want := []string{} |
| 227 | for name, value := range consts { |
| 228 | if strings.HasPrefix(name, f.prefix) && !slices.Contains(strings.Fields(f.other), name) { |
| 229 | want = append(want, value) |
| 230 | } |
| 231 | } |
| 232 | if f.zero != "" { |
| 233 | want = append(want, "") |
| 234 | } |
| 235 | got := slices.Clone(Enums[key]) |
| 236 | slices.Sort(want) |
| 237 | slices.Sort(got) |
| 238 | if !slices.Equal(got, want) { |
| 239 | t.Errorf("%s is %q; its wire constants are %q", key, got, want) |
| 240 | } |
| 241 | } |
| 242 | } |
| 243 | |
| 244 | // Every event the engine appends (txn.event in internal/equipo/chat) has |
| 245 | // a schema, and every schema an event: by type and resource. |
| 246 | func TestEventDataIsWhatTheEngineAppends(t *testing.T) { |
| 247 | consts := wireConstants(t) |
| 248 | files, _ := filepath.Glob("../../equipo/chat/*.go") |
| 249 | call := regexp.MustCompile(`\.event\(([^,]+), ([^,]+), ([^,]+), ([^,]+),`) |
| 250 | resolve := func(arg string) string { |
| 251 | if v, err := strconv.Unquote(arg); err == nil { |
| 252 | return v |
| 253 | } |
| 254 | if v, ok := consts[strings.TrimPrefix(arg, "wire.")]; ok && strings.HasPrefix(arg, "wire.") { |
| 255 | return v |
| 256 | } |
| 257 | t.Errorf("an event's type or resource is %s, not a constant", arg) |
| 258 | return "" |
| 259 | } |
| 260 | found := map[string]bool{} |
| 261 | for _, file := range files { |
| 262 | if strings.HasSuffix(file, "_test.go") { |
| 263 | continue |
| 264 | } |
| 265 | src, err := os.ReadFile(file) |
| 266 | if err != nil { |
| 267 | t.Fatal(err) |
| 268 | } |
| 269 | for _, m := range call.FindAllStringSubmatch(string(src), -1) { |
| 270 | found[resolve(m[3])+" "+resolve(m[4])] = true |
| 271 | } |
| 272 | } |
| 273 | for key := range found { |
| 274 | if _, ok := EventData[key]; !ok { |
| 275 | t.Errorf("the engine appends %s events, which have no schema", key) |
| 276 | } |
| 277 | } |
| 278 | for key := range EventData { |
| 279 | if !found[key] { |
| 280 | t.Errorf("nothing appends %s events", key) |
| 281 | } |
| 282 | } |
| 283 | } |
| 284 | |
| 285 | // The generator refuses what it cannot describe, rather than guess. |
| 286 | func TestGeneratorRefusesWhatItCannotDescribe(t *testing.T) { |
| 287 | type text struct{ big.Int } |
| 288 | type stringy struct { |
| 289 | N int64 `json:"n,string"` |
| 290 | } |
| 291 | type embedded struct { |
| 292 | *sampleInner |
| 293 | } |
| 294 | type keyed struct { |
| 295 | M map[int]string `json:"m"` |
| 296 | } |
| 297 | type marshals struct { |
| 298 | V big.Float `json:"v"` |
| 299 | } |
| 300 | for name, v := range map[string]any{"text": text{}, "string": stringy{}, "embedded": embedded{}, "keyed": keyed{}, "marshals": marshals{}} { |
| 301 | func() { |
| 302 | defer func() { |
| 303 | if recover() == nil { |
| 304 | t.Errorf("%s: described", name) |
| 305 | } |
| 306 | }() |
| 307 | newGen().ref(v) |
| 308 | }() |
| 309 | } |
| 310 | type raw struct { |
| 311 | R json.RawMessage `json:"r,omitempty"` |
| 312 | } |
| 313 | g := newGen() |
| 314 | g.ref(raw{}) |
| 315 | if got, _ := json.Marshal(g.defs["raw"]); !strings.Contains(string(got), `"properties":{"r":{}}`) || strings.Contains(string(got), "required") { |
| 316 | t.Errorf("an omitempty RawMessage: %s", got) |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | // A request body requires nothing (wire.Strict takes a missing field), |
| 321 | // and an input type that is also an answer's takes the suffix Input. |
| 322 | func TestRequestBodies(t *testing.T) { |
| 323 | out := newGen() |
| 324 | out.ref(sample{}) |
| 325 | in := newGen() |
| 326 | in.input, in.outputs = true, out.types |
| 327 | if got, _ := json.Marshal(in.ref(sample{})); string(got) != `{"$ref":"#/components/schemas/sampleInput"}` { |
| 328 | t.Fatal(string(got)) |
| 329 | } |
| 330 | if got, _ := json.Marshal(in.defs["sampleInput"]); strings.Contains(string(got), `"required"`) { |
| 331 | t.Errorf("an input requires fields: %s", got) |
| 332 | } |
| 333 | for name, s := range Generate() { |
| 334 | var v map[string]any |
| 335 | if err := json.Unmarshal(s, &v); err != nil { |
| 336 | t.Fatal(err) |
| 337 | } |
| 338 | if _, required := v["required"]; required && strings.HasSuffix(name, "Input") && InputRequired[name] == nil { |
| 339 | t.Errorf("%s requires fields", name) |
| 340 | } |
| 341 | } |
| 342 | } |
| 343 | |
| 344 | // handlerSource is internal/equipo/chat read for what its person API |
| 345 | // handlers write: the functions by name, HTTP's and Store's methods |
| 346 | // apart. |
| 347 | type handlerSource struct { |
| 348 | http, store, funcs map[string]*ast.FuncDecl |
| 349 | } |
| 350 | |
| 351 | func readHandlers(t *testing.T) handlerSource { |
| 352 | t.Helper() |
| 353 | files := parseGo(t, "../../equipo/chat") |
| 354 | src := handlerSource{map[string]*ast.FuncDecl{}, map[string]*ast.FuncDecl{}, map[string]*ast.FuncDecl{}} |
| 355 | for _, f := range files { |
| 356 | for _, d := range f.Decls { |
| 357 | fn, ok := d.(*ast.FuncDecl) |
| 358 | if !ok { |
| 359 | continue |
| 360 | } |
| 361 | switch recv := receiver(fn); recv { |
| 362 | case "HTTP": |
| 363 | src.http[fn.Name.Name] = fn |
| 364 | case "Store": |
| 365 | src.store[fn.Name.Name] = fn |
| 366 | case "": |
| 367 | src.funcs[fn.Name.Name] = fn |
| 368 | } |
| 369 | } |
| 370 | } |
| 371 | return src |
| 372 | } |
| 373 | |
| 374 | func receiver(fn *ast.FuncDecl) string { |
| 375 | if fn.Recv == nil { |
| 376 | return "" |
| 377 | } |
| 378 | if star, ok := fn.Recv.List[0].Type.(*ast.StarExpr); ok { |
| 379 | if id, ok := star.X.(*ast.Ident); ok { |
| 380 | return id.Name |
| 381 | } |
| 382 | } |
| 383 | return "other" |
| 384 | } |
| 385 | |
| 386 | var statuses = map[string]string{"http.StatusOK": "200", "http.StatusCreated": "201", "http.StatusAccepted": "202", "http.StatusNoContent": "204", "http.StatusConflict": "409"} |
| 387 | |
| 388 | // typeName is a type expression's wire name: "Task" for wire.Task. |
| 389 | func typeName(e ast.Expr) string { |
| 390 | if sel, ok := e.(*ast.SelectorExpr); ok { |
| 391 | if pkg, ok := sel.X.(*ast.Ident); ok && pkg.Name == "wire" { |
| 392 | return sel.Sel.Name |
| 393 | } |
| 394 | } |
| 395 | if _, ok := e.(*ast.MapType); ok { |
| 396 | return "map" |
| 397 | } |
| 398 | return "?" + fmt.Sprintf("%T", e) |
| 399 | } |
| 400 | |
| 401 | // writes is what fn writes, by status: the wire type's name, "" for no |
| 402 | // body, "bytes" for a file, "map" for a map literal. in is the request |
| 403 | // body's type, if it reads one. |
| 404 | func (src handlerSource) writes(t *testing.T, fn *ast.FuncDecl, out map[string]string, in *string) { |
| 405 | t.Helper() |
| 406 | params := map[string]*ast.FuncType{} |
| 407 | for _, f := range fn.Type.Params.List { |
| 408 | if ft, ok := f.Type.(*ast.FuncType); ok { |
| 409 | for _, n := range f.Names { |
| 410 | params[n.Name] = ft |
| 411 | } |
| 412 | } |
| 413 | } |
| 414 | // resultOf is the first result type of what a call calls. |
| 415 | resultOf := func(call *ast.CallExpr) string { |
| 416 | switch fun := call.Fun.(type) { |
| 417 | case *ast.Ident: |
| 418 | if ft := params[fun.Name]; ft != nil { |
| 419 | return typeName(ft.Results.List[0].Type) |
| 420 | } |
| 421 | case *ast.SelectorExpr: |
| 422 | if m := src.store[fun.Sel.Name]; m != nil { |
| 423 | return typeName(m.Type.Results.List[0].Type) |
| 424 | } |
| 425 | } |
| 426 | return "?call" |
| 427 | } |
| 428 | assigned := map[string][]ast.Expr{} // ident -> every value assigned |
| 429 | vars := map[string]string{} // var in wire.T |
| 430 | writes := false |
| 431 | for n := range ast.Preorder(fn.Body) { |
| 432 | switch x := n.(type) { |
| 433 | case *ast.AssignStmt: |
| 434 | for i, l := range x.Lhs { |
| 435 | if id, ok := l.(*ast.Ident); ok { |
| 436 | if len(x.Rhs) == len(x.Lhs) { |
| 437 | assigned[id.Name] = append(assigned[id.Name], x.Rhs[i]) |
| 438 | } else if i == 0 && len(x.Rhs) == 1 { |
| 439 | assigned[id.Name] = append(assigned[id.Name], x.Rhs[0]) |
| 440 | } |
| 441 | } |
| 442 | } |
| 443 | case *ast.ValueSpec: |
| 444 | for _, n := range x.Names { |
| 445 | if x.Type != nil { |
| 446 | vars[n.Name] = typeName(x.Type) |
| 447 | } |
| 448 | } |
| 449 | case *ast.CallExpr: |
| 450 | if sel, ok := x.Fun.(*ast.SelectorExpr); ok && sel.Sel.Name == "Write" { |
| 451 | writes = true |
| 452 | } |
| 453 | } |
| 454 | } |
| 455 | status := func(e ast.Expr) []string { |
| 456 | switch x := e.(type) { |
| 457 | case *ast.BasicLit: |
| 458 | return []string{x.Value} |
| 459 | case *ast.SelectorExpr: |
| 460 | return []string{statuses[fmt.Sprint(x.X, ".", x.Sel.Name)]} |
| 461 | case *ast.Ident: |
| 462 | var all []string |
| 463 | for _, v := range assigned[x.Name] { |
| 464 | if sel, ok := v.(*ast.SelectorExpr); ok { |
| 465 | all = append(all, statuses[fmt.Sprint(sel.X, ".", sel.Sel.Name)]) |
| 466 | } |
| 467 | } |
| 468 | return all |
| 469 | } |
| 470 | return []string{"?status"} |
| 471 | } |
| 472 | body := func(e ast.Expr) string { |
| 473 | switch x := e.(type) { |
| 474 | case *ast.CompositeLit: |
| 475 | return typeName(x.Type) |
| 476 | case *ast.Ident: |
| 477 | for _, v := range assigned[x.Name] { |
| 478 | if call, ok := v.(*ast.CallExpr); ok { |
| 479 | return resultOf(call) |
| 480 | } |
| 481 | } |
| 482 | } |
| 483 | return "?body" |
| 484 | } |
| 485 | for n := range ast.Preorder(fn.Body) { |
| 486 | call, ok := n.(*ast.CallExpr) |
| 487 | if !ok { |
| 488 | continue |
| 489 | } |
| 490 | switch fun := call.Fun.(type) { |
| 491 | case *ast.Ident: |
| 492 | switch { |
| 493 | case fun.Name == "writeJSON": |
| 494 | for _, s := range status(call.Args[1]) { |
| 495 | out[s] = body(call.Args[2]) |
| 496 | } |
| 497 | case fun.Name == "readJSON": |
| 498 | if u, ok := call.Args[1].(*ast.UnaryExpr); ok { |
| 499 | *in = vars[u.X.(*ast.Ident).Name] |
| 500 | } |
| 501 | case fun.Name == "ReadUpload": |
| 502 | *in = "bytes" |
| 503 | case src.funcs[fun.Name] != nil: |
| 504 | src.writes(t, src.funcs[fun.Name], out, in) |
| 505 | } |
| 506 | case *ast.SelectorExpr: |
| 507 | switch { |
| 508 | case fun.Sel.Name == "WriteHeader": |
| 509 | for _, s := range status(call.Args[0]) { |
| 510 | out[s] = "" |
| 511 | if writes { |
| 512 | out[s] = "bytes" |
| 513 | } |
| 514 | } |
| 515 | case fun.Sel.Name == "Strict" && fmt.Sprint(fun.X) == "wire": |
| 516 | if u, ok := call.Args[1].(*ast.UnaryExpr); ok { |
| 517 | *in = vars[u.X.(*ast.Ident).Name] |
| 518 | } |
| 519 | case fmt.Sprint(fun.X) == "h" && src.http[fun.Sel.Name] != nil: |
| 520 | src.writes(t, src.http[fun.Sel.Name], out, in) |
| 521 | } |
| 522 | } |
| 523 | } |
| 524 | } |
| 525 | |
| 526 | // handlerOf is the HTTP method a route's handler expression ends in: |
| 527 | // h.bearer(h.name), h.thinOr(..., h.bearer(h.name)), h.bearer(h.name(...)). |
| 528 | func handlerOf(e ast.Expr) string { |
| 529 | switch x := e.(type) { |
| 530 | case *ast.CallExpr: |
| 531 | if sel, ok := x.Fun.(*ast.SelectorExpr); ok && sel.Sel.Name != "bearer" && sel.Sel.Name != "thinOr" { |
| 532 | return sel.Sel.Name |
| 533 | } |
| 534 | return handlerOf(x.Args[len(x.Args)-1]) |
| 535 | case *ast.SelectorExpr: |
| 536 | return x.Sel.Name |
| 537 | } |
| 538 | return "" |
| 539 | } |
| 540 | |
| 541 | // Ops is what the handlers write: each route's request body and its |
| 542 | // answers' statuses and wire types, read from internal/equipo/chat. |
| 543 | // The event stream writes text, not JSON, and is held by the fixtures. |
| 544 | func TestOpsAreWhatTheHandlersWrite(t *testing.T) { |
| 545 | src := readHandlers(t) |
| 546 | seen := map[string]bool{} |
| 547 | for _, mount := range []string{"Mount", "mountHousekeeping", "mountUsage"} { |
| 548 | for n := range ast.Preorder(src.http[mount].Body) { |
| 549 | call, ok := n.(*ast.CallExpr) |
| 550 | if !ok || len(call.Args) != 2 { |
| 551 | continue |
| 552 | } |
| 553 | fun, isSel := call.Fun.(*ast.SelectorExpr) |
| 554 | lit, isLit := call.Args[0].(*ast.BasicLit) |
| 555 | if !isSel || !isLit || !slices.Contains([]string{"Get", "Post", "Put", "Delete"}, fun.Sel.Name) { |
| 556 | continue |
| 557 | } |
| 558 | path, _ := strconv.Unquote(lit.Value) |
| 559 | key := strings.ToUpper(fun.Sel.Name) + " " + path |
| 560 | seen[key] = true |
| 561 | op, ok := Ops[key] |
| 562 | if !ok { |
| 563 | t.Errorf("%s is served but not in Ops", key) |
| 564 | continue |
| 565 | } |
| 566 | if key == "GET /events" { |
| 567 | continue |
| 568 | } |
| 569 | name := handlerOf(call.Args[1]) |
| 570 | fn := src.http[name] |
| 571 | if fn == nil { |
| 572 | t.Errorf("%s: cannot find its handler %q", key, name) |
| 573 | continue |
| 574 | } |
| 575 | got, in := map[string]string{}, "" |
| 576 | src.writes(t, fn, got, &in) |
| 577 | want := map[string]string{} |
| 578 | for status, v := range op.Out { |
| 579 | want[status] = opName(v) |
| 580 | // A handler's primary body must be one of its documented |
| 581 | // variants. Compatibility routes and fail() supply the others. |
| 582 | if variants, ok := v.(OneOf); ok { |
| 583 | for _, variant := range variants { |
| 584 | if opName(variant) == got[status] { |
| 585 | want[status] = got[status] |
| 586 | break |
| 587 | } |
| 588 | } |
| 589 | } |
| 590 | } |
| 591 | if !reflect.DeepEqual(got, want) { |
| 592 | t.Errorf("%s (%s) writes %v; Ops says %v", key, name, got, want) |
| 593 | } |
| 594 | if wantIn := opName(op.In); in != wantIn { |
| 595 | t.Errorf("%s (%s) reads %q; Ops says %q", key, name, in, wantIn) |
| 596 | } |
| 597 | continue |
| 598 | } |
| 599 | } |
| 600 | for key := range Ops { |
| 601 | if !seen[key] { |
| 602 | t.Errorf("%s is in Ops but not served", key) |
| 603 | } |
| 604 | } |
| 605 | } |
| 606 | |
| 607 | func opName(v any) string { |
| 608 | switch v.(type) { |
| 609 | case nil: |
| 610 | return "" |
| 611 | case Bytes: |
| 612 | return "bytes" |
| 613 | } |
| 614 | if name := reflect.TypeOf(v).Name(); name != "" { |
| 615 | return name |
| 616 | } |
| 617 | return "map" |
| 618 | } |
| 619 | |
| 620 | // The native routes' handlers refuse a body missing these fields, so the |
| 621 | // document must say so: an app built from it would otherwise send none. |
| 622 | func TestNativeInputsRequireWhatTheirHandlersRequire(t *testing.T) { |
| 623 | defs := map[string]any{} |
| 624 | for name, raw := range Generate() { |
| 625 | var s any |
| 626 | if err := json.Unmarshal(raw, &s); err != nil { |
| 627 | t.Fatal(err) |
| 628 | } |
| 629 | defs[name] = s |
| 630 | } |
| 631 | for name, cases := range map[string][]string{ |
| 632 | "BeginDeviceInput": {`{}`, `{"label":"phone"}`, `{"public_key":"key"}`}, |
| 633 | "NativeRequest": {`{}`, `{"verifier":"v"}`, `{"assertion":"a","choice":"new"}`}, |
| 634 | } { |
| 635 | s := map[string]any{"$ref": "#/components/schemas/" + name} |
| 636 | for _, body := range cases { |
| 637 | var v any |
| 638 | if err := json.Unmarshal([]byte(body), &v); err != nil { |
| 639 | t.Fatal(err) |
| 640 | } |
| 641 | if Validate(defs, v, s, name) == nil { |
| 642 | t.Errorf("%s accepts %s", name, body) |
| 643 | } |
| 644 | } |
| 645 | } |
| 646 | for name, body := range map[string]string{"BeginDeviceInput": `{"public_key":"key","label":"phone"}`, "NativeRequest": `{"assertion":"a","verifier":"v"}`} { |
| 647 | var v any |
| 648 | _ = json.Unmarshal([]byte(body), &v) |
| 649 | if err := Validate(defs, v, map[string]any{"$ref": "#/components/schemas/" + name}, name); err != nil { |
| 650 | t.Errorf("%s refuses a complete body: %v", name, err) |
| 651 | } |
| 652 | } |
| 653 | } |
| 654 | |