Files
coder/coderd/coderdtest/swagger_test.go
T
Thomas Kosiewski 70f62ae429 fix(coderd/coderdtest): render the Swagger spec once in parallel tests (#31829)
## Why

`test-go-race-pg` fails on PRs that touch no Go product code, for
example two runs on #31782. Since #30124, two parallel tests in
`coderd/coderdtest` call swag's `Spec.ReadDoc`, which writes shared
state, so the race detector fails the whole package (`WARNING: DATA
RACE` in `swag.(*Spec).ReadDoc`, `swagger_test.go:41` and `:77`).

## What changed

`swagger_test.go` renders the spec once through `sync.OnceValue`, and
both tests read that string.

## Verification

- On `main`, `go test -race -count=20 -run
'TestSwaggerParametersValid|TestChatModelPathParametersFormatted'
./coderd/coderdtest/` reported 4 data races and failed.
- With this change, the same command passed with 0 races.
- `golangci-lint` reports 0 issues for `./coderd/coderdtest/` with both
the main and the new-code configs.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model:
`anthropic:claude-opus-5-5` • Thinking: `high`_
2026-11-09 17:37:35 +11:00

143 lines
4.4 KiB
Go

package coderdtest_test
import (
"encoding/json"
"go/ast"
"go/parser"
"go/token"
"strings"
"sync"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/coder/coder/v2/coderd/apidoc"
"github.com/coder/coder/v2/coderd/coderdtest"
)
// swaggerDoc renders the spec once. swag's ReadDoc writes shared state, so
// parallel tests that each call it race.
var swaggerDoc = sync.OnceValue(apidoc.SwaggerInfo.ReadDoc)
func TestEndpointsDocumented(t *testing.T) {
t.Parallel()
swaggerComments, err := coderdtest.ParseSwaggerComments("..", "../workspaceconnwatcher")
require.NoError(t, err, "can't parse swagger comments")
require.NotEmpty(t, swaggerComments, "swagger comments must be present")
_, _, api := coderdtest.NewWithAPI(t, nil)
coderdtest.VerifySwaggerDefinitions(t, api.APIHandler, swaggerComments, coderdtest.WithSwaggerRoutePrefix("/api/v2"))
}
func TestChatModelPathParametersFormatted(t *testing.T) {
t.Parallel()
var swagger struct {
Paths map[string]map[string]struct {
Parameters []struct {
Name string `json:"name"`
In string `json:"in"`
Format string `json:"format"`
} `json:"parameters"`
} `json:"paths"`
}
require.NoError(t, json.Unmarshal([]byte(swaggerDoc()), &swagger))
operations := swagger.Paths["/api/v2/organizations/{organization}/chats/models/{model}"]
for _, method := range []string{"get", "patch", "delete"} {
t.Run(method, func(t *testing.T) {
t.Parallel()
for _, parameter := range operations[method].Parameters {
if parameter.Name == "model" && parameter.In == "path" {
require.Equal(t, "uuid", parameter.Format)
return
}
}
require.Fail(t, "model path parameter not found")
})
}
}
// TestSwaggerParametersValid guards against parameter annotations that
// produce a wrong spec. Swagger 2.0 does not allow "example" on non-body
// parameters, swag writes format(...) on an array parameter to the array
// rather than its items, and a path parameter must appear in its route.
func TestSwaggerParametersValid(t *testing.T) {
t.Parallel()
var swagger struct {
Paths map[string]map[string]struct {
Parameters []struct {
Name string `json:"name"`
In string `json:"in"`
Type string `json:"type"`
Format string `json:"format"`
Example any `json:"example"`
} `json:"parameters"`
} `json:"paths"`
}
require.NoError(t, json.Unmarshal([]byte(swaggerDoc()), &swagger))
require.NotEmpty(t, swagger.Paths)
for path, operations := range swagger.Paths {
for method, operation := range operations {
for _, parameter := range operation.Parameters {
if parameter.In != "body" {
assert.Nil(t, parameter.Example, "%s %s: %s parameter %q must not have an example; use extensions(x-example=...)", method, path, parameter.In, parameter.Name)
}
if parameter.Type == "array" {
assert.Empty(t, parameter.Format, "%s %s: array parameter %q must not have a format; swag cannot set an item format, so state it in the description", method, path, parameter.Name)
}
if parameter.In == "path" {
assert.Contains(t, path, "{"+parameter.Name+"}", "%s %s: path parameter %q is not in the route", method, path, parameter.Name)
}
}
}
}
}
func TestSDKFieldsFormatted(t *testing.T) {
t.Parallel()
fileSet := token.NewFileSet()
nodes, err := parser.ParseDir(fileSet, "../../codersdk", nil, parser.ParseComments)
require.NoError(t, err, "parser.ParseDir failed")
for _, node := range nodes {
ast.Inspect(node, func(n ast.Node) bool {
typeSpec, ok := n.(*ast.TypeSpec)
if !ok {
return true
}
structureName := typeSpec.Name
structType, ok := typeSpec.Type.(*ast.StructType)
if !ok {
return true // not a structure
}
for _, field := range structType.Fields.List {
selectorExpr, ok := field.Type.(*ast.SelectorExpr)
if !ok {
continue // rather a basic, or primitive
}
if field.Tag == nil || !strings.Contains(field.Tag.Value, `json:"`) {
continue // not a JSON property
}
switch selectorExpr.Sel.Name {
case "UUID":
assert.Contains(t, field.Tag.Value, `format:"uuid"`, `Swagger formatting requires to annotate the field with - format:"uuid". Location: %s/%s`, structureName, field.Names)
case "Time":
assert.Contains(t, field.Tag.Value, `format:"date-time"`, `Swagger formatting requires to annotate the field with - format:"date-time". Location: %s/%s`, structureName, field.Names)
}
}
return true
})
}
}