Skip to content

Commit

Permalink
chore: fix bug and refactor (#1048)
Browse files Browse the repository at this point in the history
  • Loading branch information
forsaken628 authored Nov 11, 2021
1 parent 9b23c9e commit e59f457
Show file tree
Hide file tree
Showing 11 changed files with 118 additions and 174 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ jobs:
test:
strategy:
matrix:
go: [ '1.13.x', '1.14.x', '1.15.x' ]
go: [ '1.13.x', '1.14.x', '1.15.x', '1.16.x', '1.17.x' ]
platform: [ubuntu-latest, macos-latest]
runs-on: ${{ matrix.platform }}
steps:
Expand Down
4 changes: 4 additions & 0 deletions field_parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,7 @@ func (ps *tagBaseFieldParser) ComplementSchema(schema *spec.Schema) error {
enumType = structField.arrayType
}

structField.enums = nil
for _, e := range strings.Split(enumsTag, ",") {
value, err := defineType(enumType, e)
if err != nil {
Expand Down Expand Up @@ -438,6 +439,9 @@ func (ps *tagBaseFieldParser) parseValidTags(validTag string, sf *structField) {
}
checkSchemaTypeAndSetValue(sf, minValue, false)
case "oneof":
if len(sf.enums) != 0 {
continue
}
enumType := sf.schemaType
if sf.schemaType == ARRAY {
enumType = sf.arrayType
Expand Down
22 changes: 22 additions & 0 deletions field_parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -430,6 +430,28 @@ func TestValidTags(t *testing.T) {
).ComplementSchema(&schema)
assert.NoError(t, err)
assert.Equal(t, []interface{}{"c0x9Ab", "book"}, schema.Enum)

schema = spec.Schema{}
schema.Type = []string{"string"}
err = newTagBaseFieldParser(
&Parser{},
&ast.Field{Tag: &ast.BasicLit{
Value: `json:"test" binding:"oneof=foo bar" validate:"required,oneof=foo bar" enums:"a,b,c"`,
}},
).ComplementSchema(&schema)
assert.NoError(t, err)
assert.Equal(t, []interface{}{"a", "b", "c"}, schema.Enum)

schema = spec.Schema{}
schema.Type = []string{"string"}
err = newTagBaseFieldParser(
&Parser{},
&ast.Field{Tag: &ast.BasicLit{
Value: `json:"test" binding:"oneof=aa bb" validate:"required,oneof=foo bar"`,
}},
).ComplementSchema(&schema)
assert.NoError(t, err)
assert.Equal(t, []interface{}{"aa", "bb"}, schema.Enum)
})
t.Run("Required with unique tag", func(t *testing.T) {
t.Parallel()
Expand Down
48 changes: 24 additions & 24 deletions gen/gen_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func TestGen_Build(t *testing.T) {
}
for _, expectedFile := range expectedFiles {
if _, err := os.Stat(expectedFile); os.IsNotExist(err) {
t.Fatal(err)
require.NoError(t, err)
}
_ = os.Remove(expectedFile)
}
Expand All @@ -55,7 +55,7 @@ func TestGen_BuildInstanceName(t *testing.T) {
// Validate default registration name
expectedCode, err := ioutil.ReadFile(goSourceFile)
if err != nil {
t.Fatal(err)
require.NoError(t, err)
}
if !strings.Contains(string(expectedCode), "swag.Register(\"swagger\", &s{})") {
t.Fatal(errors.New("generated go code does not contain the correct default registration sequence"))
Expand All @@ -66,7 +66,7 @@ func TestGen_BuildInstanceName(t *testing.T) {
assert.NoError(t, New().Build(config))
expectedCode, err = ioutil.ReadFile(goSourceFile)
if err != nil {
t.Fatal(err)
require.NoError(t, err)
}
if !strings.Contains(string(expectedCode), "swag.Register(\"custom\", &s{})") {
t.Fatal(errors.New("generated go code does not contain the correct registration sequence"))
Expand All @@ -80,7 +80,7 @@ func TestGen_BuildInstanceName(t *testing.T) {
}
for _, expectedFile := range expectedFiles {
if _, err := os.Stat(expectedFile); os.IsNotExist(err) {
t.Fatal(err)
require.NoError(t, err)
}
_ = os.Remove(expectedFile)
}
Expand All @@ -103,7 +103,7 @@ func TestGen_BuildSnakeCase(t *testing.T) {
}
for _, expectedFile := range expectedFiles {
if _, err := os.Stat(expectedFile); os.IsNotExist(err) {
t.Fatal(err)
require.NoError(t, err)
}
_ = os.Remove(expectedFile)
}
Expand All @@ -126,7 +126,7 @@ func TestGen_BuildLowerCamelcase(t *testing.T) {
}
for _, expectedFile := range expectedFiles {
if _, err := os.Stat(expectedFile); os.IsNotExist(err) {
t.Fatal(err)
require.NoError(t, err)
}
_ = os.Remove(expectedFile)
}
Expand All @@ -149,35 +149,35 @@ func TestGen_BuildDescriptionWithQuotes(t *testing.T) {
}
for _, expectedFile := range expectedFiles {
if _, err := os.Stat(expectedFile); os.IsNotExist(err) {
t.Fatal(err)
require.NoError(t, err)
}
}
cmd := exec.Command("go", "build", "-buildmode=plugin", "github.com/swaggo/swag/testdata/quotes")
cmd.Dir = config.SearchDir
output, err := cmd.CombinedOutput()
if err != nil {
t.Fatal(err, string(output))
require.NoError(t, err, string(output))
}
p, err := plugin.Open(filepath.Join(config.SearchDir, "quotes.so"))
if err != nil {
t.Fatal(err)
require.NoError(t, err)
}
defer os.Remove("quotes.so")

readDoc, err := p.Lookup("ReadDoc")
if err != nil {
t.Fatal(err)
require.NoError(t, err)
}
jsonOutput := []byte(readDoc.(func() string)())
jsonOutput := readDoc.(func() string)()
var jsonDoc interface{}
if err := json.Unmarshal(jsonOutput, &jsonDoc); err != nil {
t.Fatal(err, string(jsonOutput))
if err := json.Unmarshal([]byte(jsonOutput), &jsonDoc); err != nil {
require.NoError(t, err)
}
expectedJSON, err := ioutil.ReadFile(filepath.Join(config.SearchDir, "expected.json"))
if err != nil {
t.Fatal(err)
require.NoError(t, err)
}
assert.Equal(t, expectedJSON, jsonOutput)
assert.JSONEq(t, string(expectedJSON), jsonOutput)
}

func TestGen_jsonIndent(t *testing.T) {
Expand Down Expand Up @@ -213,7 +213,7 @@ func TestGen_jsonToYAML(t *testing.T) {
}
for _, expectedFile := range expectedFiles {
if _, err := os.Stat(expectedFile); os.IsNotExist(err) {
t.Fatal(err)
require.NoError(t, err)
}
_ = os.Remove(expectedFile)
}
Expand Down Expand Up @@ -265,34 +265,34 @@ func TestGen_FailToWrite(t *testing.T) {

err := os.MkdirAll(outputDir, 0755)
if err != nil {
t.Fatal(err)
require.NoError(t, err)
}

_ = os.RemoveAll(filepath.Join(outputDir, "swagger.yaml"))
err = os.Mkdir(filepath.Join(outputDir, "swagger.yaml"), 0755)
if err != nil {
t.Fatal(err)
require.NoError(t, err)
}
assert.Error(t, New().Build(config))

_ = os.RemoveAll(filepath.Join(outputDir, "swagger.json"))
err = os.Mkdir(filepath.Join(outputDir, "swagger.json"), 0755)
if err != nil {
t.Fatal(err)
require.NoError(t, err)
}
assert.Error(t, New().Build(config))

_ = os.RemoveAll(filepath.Join(outputDir, "docs.go"))

err = os.Mkdir(filepath.Join(outputDir, "docs.go"), 0755)
if err != nil {
t.Fatal(err)
require.NoError(t, err)
}
assert.Error(t, New().Build(config))

err = os.RemoveAll(outputDir)
if err != nil {
t.Fatal(err)
require.NoError(t, err)
}
}

Expand All @@ -313,7 +313,7 @@ func TestGen_configWithOutputDir(t *testing.T) {
}
for _, expectedFile := range expectedFiles {
if _, err := os.Stat(expectedFile); os.IsNotExist(err) {
t.Fatal(err)
require.NoError(t, err)
}
_ = os.Remove(expectedFile)
}
Expand Down Expand Up @@ -417,7 +417,7 @@ func TestGen_GeneratedDoc(t *testing.T) {
}
for _, expectedFile := range expectedFiles {
if _, err := os.Stat(expectedFile); os.IsNotExist(err) {
t.Fatal(err)
require.NoError(t, err)
}
_ = os.Remove(expectedFile)
}
Expand All @@ -441,7 +441,7 @@ func TestGen_cgoImports(t *testing.T) {
}
for _, expectedFile := range expectedFiles {
if _, err := os.Stat(expectedFile); os.IsNotExist(err) {
t.Fatal(err)
require.NoError(t, err)
}
_ = os.Remove(expectedFile)
}
Expand Down
14 changes: 8 additions & 6 deletions operation.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ func (operation *Operation) ParseMetadata(attribute, lowerAttribute, lineRemaind
return fmt.Errorf("annotation %s need a valid json value", attribute)
}

// don't use the method provided by spec lib, b3cause it will call toLower() on attribute names, which is wrongly
// don't use the method provided by spec lib, because it will call toLower() on attribute names, which is wrongly
operation.Extensions[attribute[1:]] = valueJSON
}

Expand Down Expand Up @@ -587,13 +587,15 @@ func (operation *Operation) ParseRouterComment(commentLine string) error {
if len(matches) != 3 {
return fmt.Errorf("can not parse router comment \"%s\"", commentLine)
}
path := matches[1]
httpMethod := matches[2]

signature := RouteProperties{
Path: path,
HTTPMethod: strings.ToUpper(httpMethod),
Path: matches[1],
HTTPMethod: strings.ToUpper(matches[2]),
}

if _, ok := allMethod[signature.HTTPMethod]; !ok {
return fmt.Errorf("invalid method: %s", signature.HTTPMethod)
}

operation.RouterProperties = append(operation.RouterProperties, signature)

return nil
Expand Down
5 changes: 5 additions & 0 deletions operation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,11 @@ func TestParseRouterComment(t *testing.T) {
assert.Len(t, operation.RouterProperties, 1)
assert.Equal(t, "/customer/get-wishlist/{wishlist_id}", operation.RouterProperties[0].Path)
assert.Equal(t, "GET", operation.RouterProperties[0].HTTPMethod)

comment = `/@Router /customer/get-wishlist/{wishlist_id} [unknown]`
operation = NewOperation(nil)
err = operation.ParseComment(comment, nil)
assert.Error(t, err)
}

func TestParseRouterMultipleComments(t *testing.T) {
Expand Down
2 changes: 1 addition & 1 deletion packages.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func (pkgs *PackagesDefinitions) CollectAstFile(packageDir, path string, astFile
}

// return without storing the file if we lack a packageDir
if len(packageDir) == 0 {
if packageDir == "" {
return nil
}

Expand Down
Loading

0 comments on commit e59f457

Please sign in to comment.