Skip to content

Commit 415e34e

Browse files
committed
Unique annotations
1 parent 6d21862 commit 415e34e

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

coderd/coderdtest/swaggerparser.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,7 @@ func parseSwaggerComment(commentGroup *ast.CommentGroup) SwaggerComment {
149149

150150
func VerifySwaggerDefinitions(t *testing.T, router chi.Router, swaggerComments []SwaggerComment) {
151151
assertUniqueRoutes(t, swaggerComments)
152+
assertUniqueAnnotations(t, swaggerComments)
152153

153154
err := chi.Walk(router, func(method, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error {
154155
method = strings.ToLower(method)
@@ -192,6 +193,36 @@ func assertUniqueRoutes(t *testing.T, comments []SwaggerComment) {
192193
}
193194
}
194195

196+
var uniqueAnnotations = []string{"@ID", "@Summary", "@Tags", "@Router"}
197+
198+
func assertUniqueAnnotations(t *testing.T, comments []SwaggerComment) {
199+
for _, comment := range comments {
200+
counters := map[string]int{}
201+
202+
for _, line := range comment.raw {
203+
splitN := strings.SplitN(strings.TrimSpace(line.Text), " ", 3)
204+
if len(splitN) < 2 {
205+
continue // comment prefix without any content
206+
}
207+
208+
if !strings.HasPrefix(splitN[1], "@") {
209+
continue // not a swagger annotation
210+
}
211+
212+
annotation := splitN[1]
213+
if _, ok := counters[annotation]; !ok {
214+
counters[annotation] = 0
215+
}
216+
counters[annotation]++
217+
}
218+
219+
for _, annotation := range uniqueAnnotations {
220+
v := counters[annotation]
221+
assert.Equal(t, 1, v, "%s annotation for route %s must be defined only once", annotation, comment.router)
222+
}
223+
}
224+
}
225+
195226
func findSwaggerCommentByMethodAndRoute(comments []SwaggerComment, method, route string) *SwaggerComment {
196227
for _, c := range comments {
197228
if c.method == method && c.router == route {
@@ -219,6 +250,7 @@ func assertRequiredAnnotations(t *testing.T, comment SwaggerComment) {
219250
assert.NotEmpty(t, comment.id, "@ID must be defined")
220251
assert.NotEmpty(t, comment.summary, "@Summary must be defined")
221252
assert.NotEmpty(t, comment.tags, "@Tags must be defined")
253+
assert.NotEmpty(t, comment.tags, "@Router must be defined")
222254
}
223255

224256
func assertGoCommentFirst(t *testing.T, comment SwaggerComment) {

0 commit comments

Comments
 (0)