| 1 | package console |
| 2 | |
| 3 | import ( |
| 4 | "go/ast" |
| 5 | "go/parser" |
| 6 | "go/token" |
| 7 | "os" |
| 8 | "path/filepath" |
| 9 | "slices" |
| 10 | "strings" |
| 11 | "testing" |
| 12 | ) |
| 13 | |
| 14 | func claimInventoryKeys(entries []claimEntry) []string { |
| 15 | keys := make([]string, 0, len(entries)) |
| 16 | for _, e := range entries { |
| 17 | keys = append(keys, e.Kind+" "+e.Pattern) |
| 18 | } |
| 19 | slices.Sort(keys) |
| 20 | return keys |
| 21 | } |
| 22 | func compareClaimInventory(entries []claimEntry, want []string) bool { |
| 23 | return slices.Equal(claimInventoryKeys(entries), want) |
| 24 | } |
| 25 | func TestClaimConsoleRouteCensus(t *testing.T) { |
| 26 | // The enabled console: two routes (host-loss resolve and inspect) exist only |
| 27 | // with HostClaim on, and the census is of what an enabled console serves. |
| 28 | s := newClaimCase(t).srv |
| 29 | b, err := os.ReadFile("testdata/claim-routes.txt") |
| 30 | if err != nil { |
| 31 | t.Fatal(err) |
| 32 | } |
| 33 | want := strings.Split(strings.TrimSpace(string(b)), "\n") |
| 34 | slices.Sort(want) |
| 35 | if !compareClaimInventory(s.claimEntries.snapshot(), want) { |
| 36 | got := claimInventoryKeys(s.claimEntries.snapshot()) |
| 37 | for _, k := range got { |
| 38 | if !slices.Contains(want, k) { |
| 39 | t.Errorf("new: %s", k) |
| 40 | } |
| 41 | } |
| 42 | for _, k := range want { |
| 43 | if !slices.Contains(got, k) { |
| 44 | t.Errorf("missing: %s", k) |
| 45 | } |
| 46 | } |
| 47 | t.FailNow() |
| 48 | } |
| 49 | s.registerRoute("POST /claim-unreviewed-door", s.handleHome) |
| 50 | if compareClaimInventory(s.claimEntries.snapshot(), want) { |
| 51 | t.Fatal("new route escaped census") |
| 52 | } |
| 53 | } |
| 54 | func TestClaimConsoleMuxHasOneRegistrar(t *testing.T) { |
| 55 | fs := token.NewFileSet() |
| 56 | entries, err := os.ReadDir(".") |
| 57 | if err != nil { |
| 58 | t.Fatal(err) |
| 59 | } |
| 60 | for _, entry := range entries { |
| 61 | if !strings.HasSuffix(entry.Name(), ".go") || strings.HasSuffix(entry.Name(), "_test.go") { |
| 62 | continue |
| 63 | } |
| 64 | f, err := parser.ParseFile(fs, entry.Name(), nil, 0) |
| 65 | if err != nil { |
| 66 | t.Fatal(err) |
| 67 | } |
| 68 | for _, d := range f.Decls { |
| 69 | fd, ok := d.(*ast.FuncDecl) |
| 70 | if !ok || fd.Body == nil { |
| 71 | continue |
| 72 | } |
| 73 | ast.Inspect(fd.Body, func(n ast.Node) bool { |
| 74 | call, ok := n.(*ast.CallExpr) |
| 75 | if !ok { |
| 76 | return true |
| 77 | } |
| 78 | sel, ok := call.Fun.(*ast.SelectorExpr) |
| 79 | if !ok { |
| 80 | return true |
| 81 | } |
| 82 | if sel.Sel.Name != "Handle" && sel.Sel.Name != "HandleFunc" { |
| 83 | return true |
| 84 | } |
| 85 | if filepath.Base(entry.Name()) != "claim_routes.go" || fd.Name.Name != "registerRoute" { |
| 86 | t.Errorf("mux registration outside registerRoute: %s", fs.Position(n.Pos())) |
| 87 | } |
| 88 | return true |
| 89 | }) |
| 90 | } |
| 91 | } |
| 92 | } |
| 93 | |