|
| 1 | +package httpapi_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + "log/slog" |
| 9 | + "os" |
| 10 | + "sort" |
| 11 | + "testing" |
| 12 | + |
| 13 | + "github.com/coder/agentapi/lib/httpapi" |
| 14 | + "github.com/coder/agentapi/lib/logctx" |
| 15 | + "github.com/coder/agentapi/lib/msgfmt" |
| 16 | + "github.com/stretchr/testify/require" |
| 17 | +) |
| 18 | + |
| 19 | +func normalizeSchema(t *testing.T, schema any) any { |
| 20 | + t.Helper() |
| 21 | + switch val := (schema).(type) { |
| 22 | + case []any: |
| 23 | + for i := range val { |
| 24 | + normalizeSchema(t, &val[i]) |
| 25 | + } |
| 26 | + sort.SliceStable(val, func(i, j int) bool { |
| 27 | + return fmt.Sprintf("%v", val[i]) < fmt.Sprintf("%v", val[j]) |
| 28 | + }) |
| 29 | + case map[string]any: |
| 30 | + for k := range val { |
| 31 | + valUnderKey := val[k] |
| 32 | + normalizeSchema(t, &valUnderKey) |
| 33 | + val[k] = valUnderKey |
| 34 | + } |
| 35 | + } |
| 36 | + return schema |
| 37 | +} |
| 38 | + |
| 39 | +// Ensure the OpenAPI schema on disk is up to date. |
| 40 | +// To update the schema, run `go run main.go server --print-openapi dummy > openapi.json`. |
| 41 | +func TestOpenAPISchema(t *testing.T) { |
| 42 | + t.Parallel() |
| 43 | + |
| 44 | + ctx := logctx.WithLogger(context.Background(), slog.New(slog.NewTextHandler(os.Stdout, nil))) |
| 45 | + srv := httpapi.NewServer(ctx, msgfmt.AgentTypeClaude, nil, 0) |
| 46 | + currentSchemaStr := srv.GetOpenAPI() |
| 47 | + var currentSchema any |
| 48 | + if err := json.Unmarshal([]byte(currentSchemaStr), ¤tSchema); err != nil { |
| 49 | + t.Fatalf("failed to unmarshal current schema: %s", err) |
| 50 | + } |
| 51 | + |
| 52 | + diskSchemaFile, err := os.OpenFile("../../openapi.json", os.O_RDONLY, 0) |
| 53 | + if err != nil { |
| 54 | + t.Fatalf("failed to open disk schema: %s", err) |
| 55 | + } |
| 56 | + defer diskSchemaFile.Close() |
| 57 | + |
| 58 | + diskSchemaBytes, err := io.ReadAll(diskSchemaFile) |
| 59 | + if err != nil { |
| 60 | + t.Fatalf("failed to read disk schema: %s", err) |
| 61 | + } |
| 62 | + var diskSchema any |
| 63 | + if err := json.Unmarshal(diskSchemaBytes, &diskSchema); err != nil { |
| 64 | + t.Fatalf("failed to unmarshal disk schema: %s", err) |
| 65 | + } |
| 66 | + |
| 67 | + normalizeSchema(t, ¤tSchema) |
| 68 | + normalizeSchema(t, &diskSchema) |
| 69 | + |
| 70 | + require.Equal(t, currentSchema, diskSchema) |
| 71 | +} |
0 commit comments