Skip to content

Commit

Permalink
Add form and query struct test for operations
Browse files Browse the repository at this point in the history
  • Loading branch information
tanenbaum committed Jan 15, 2024
1 parent d1cb577 commit e254a2a
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 3 deletions.
7 changes: 6 additions & 1 deletion operation.go
Original file line number Diff line number Diff line change
Expand Up @@ -312,8 +312,13 @@ func (operation *Operation) ParseParamComment(commentLine string, astFile *ast.F
}
}

nameOverrideType := paramType
// query also uses formData tags
if paramType == "query" {
nameOverrideType = "formData"
}
// load overridden type specific name from extensions if exists
if nameVal, ok := item.Schema.Extensions[paramType]; ok {
if nameVal, ok := item.Schema.Extensions[nameOverrideType]; ok {
name = nameVal.(string)
}

Expand Down
35 changes: 33 additions & 2 deletions operation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package swag

import (
"encoding/json"
"fmt"
"go/ast"
goparser "go/parser"
"go/token"
Expand Down Expand Up @@ -2105,9 +2106,40 @@ func TestParseParamStructCodeExample(t *testing.T) {

// values used in validation checks
max := float64(10)
maxLen := int64(10)
min := float64(0)

t.Run("Header struct", func(t *testing.T) {
// query and form behave the same
for _, param := range []string{"query", "formData"} {
t.Run(param+" struct", func(t *testing.T) {
operation := NewOperation(parser)
comment := fmt.Sprintf(`@Param model %s structs.FormModel true "query params"`, param)
err = operation.ParseComment(comment, ast)
assert.NoError(t, err)

validateParameters(operation,
spec.Parameter{
ParamProps: spec.ParamProps{
Name: "f",
Description: "",
In: param,
Required: true,
},
CommonValidations: spec.CommonValidations{
MaxLength: &maxLen,
},
},
spec.Parameter{
ParamProps: spec.ParamProps{
Name: "b",
Description: "B is another field",
In: param,
},
})
})
}

t.Run("header struct", func(t *testing.T) {
operation := NewOperation(parser)
comment := `@Param auth header structs.AuthHeader true "auth header"`
err = operation.ParseComment(comment, ast)
Expand All @@ -2126,7 +2158,6 @@ func TestParseParamStructCodeExample(t *testing.T) {
Name: "anotherHeader",
Description: "AnotherHeader is another header",
In: "header",
Required: false,
},
CommonValidations: spec.CommonValidations{
Maximum: &max,
Expand Down
6 changes: 6 additions & 0 deletions testdata/param_structs/structs.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
package structs

type FormModel struct {
Foo string `form:"f" binding:"required" validate:"max=10"`
// B is another field
B string
}

type AuthHeader struct {
// Token is the auth token
Token string `header:"X-Auth-Token" binding:"required"`
Expand Down

0 comments on commit e254a2a

Please sign in to comment.