Skip to content

Commit

Permalink
Add go1.18 test code
Browse files Browse the repository at this point in the history
  • Loading branch information
pytimer committed Apr 28, 2022
1 parent e48e0a6 commit ceb23ac
Show file tree
Hide file tree
Showing 13 changed files with 359 additions and 14 deletions.
10 changes: 3 additions & 7 deletions golist.go
Expand Up @@ -53,11 +53,6 @@ func (parser *Parser) getAllGoFileInfoFromDepsByList(pkg *build.Package) error {
return nil
}

// Skip cgo
if pkg.Name == "C" {
return nil
}

srcDir := pkg.Dir
var err error
for i := range pkg.GoFiles {
Expand All @@ -67,8 +62,9 @@ func (parser *Parser) getAllGoFileInfoFromDepsByList(pkg *build.Package) error {
}
}

for i := range pkg.CFiles {
err = parser.parseFile(pkg.ImportPath, filepath.Join(srcDir, pkg.CFiles[i]), nil)
// parse .go source files that import "C"
for i := range pkg.CgoFiles {
err = parser.parseFile(pkg.ImportPath, filepath.Join(srcDir, pkg.CgoFiles[i]), nil)
if err != nil {
return err
}
Expand Down
116 changes: 116 additions & 0 deletions golist_test.go
@@ -0,0 +1,116 @@
package swag

import (
"context"
"errors"
"fmt"
"go/build"
"os"
"path/filepath"
"testing"

"github.com/stretchr/testify/assert"
)

func TestListPackages(t *testing.T) {

cases := []struct {
name string
args []string
searchDir string
except error
}{
{
name: "errorArgs",
args: []string{"-abc"},
searchDir: "testdata/golist",
except: fmt.Errorf("exit status 2"),
},
{
name: "normal",
args: []string{"-deps"},
searchDir: "testdata/golist",
except: nil,
},
{
name: "list error",
args: []string{"-deps"},
searchDir: "testdata/golist_not_exist",
except: errors.New("searchDir not exist"),
},
}

for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
_, err := listPackages(context.TODO(), c.searchDir, nil, c.args...)
if c.except != nil {
assert.NotNil(t, err)
} else {
assert.Nil(t, err)
}
})
}
}

func TestGetAllGoFileInfoFromDepsByList(t *testing.T) {
p := New(ParseUsingGoList(true))
pwd, err := os.Getwd()
assert.NoError(t, err)
cases := []struct {
name string
buildPackage *build.Package
ignoreInternal bool
except error
}{
{
name: "normal",
buildPackage: &build.Package{
Name: "main",
ImportPath: "github.com/swaggo/swag/testdata/golist",
Dir: "testdata/golist",
GoFiles: []string{"main.go"},
CgoFiles: []string{"api/api.go"},
},
except: nil,
},
{
name: "ignore internal",
buildPackage: &build.Package{
Goroot: true,
},
ignoreInternal: true,
except: nil,
},
{
name: "gofiles error",
buildPackage: &build.Package{
Dir: "testdata/golist_not_exist",
GoFiles: []string{"main.go"},
},
except: errors.New("file not exist"),
},
{
name: "cgofiles error",
buildPackage: &build.Package{
Dir: "testdata/golist_not_exist",
CgoFiles: []string{"main.go"},
},
except: errors.New("file not exist"),
},
}

for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if c.ignoreInternal {
p.ParseInternal = false
}
c.buildPackage.Dir = filepath.Join(pwd, c.buildPackage.Dir)
err := p.getAllGoFileInfoFromDepsByList(c.buildPackage)
if c.except != nil {
assert.NotNil(t, err)
} else {
assert.Nil(t, err)
}
})
}
}
15 changes: 15 additions & 0 deletions packages_test.go
Expand Up @@ -4,6 +4,7 @@ import (
"go/ast"
"go/token"
"path/filepath"
"runtime"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -151,6 +152,20 @@ func TestPackage_rangeFiles(t *testing.T) {
Path: "testdata/simple/api/api.go",
PackagePath: "api",
},
{
Name: &ast.Ident{Name: "foo.go"},
}: {
File: &ast.File{Name: &ast.Ident{Name: "foo.go"}},
Path: "vendor/foo/foo.go",
PackagePath: "vendor/foo",
},
{
Name: &ast.Ident{Name: "bar.go"},
}: {
File: &ast.File{Name: &ast.Ident{Name: "bar.go"}},
Path: filepath.Join(runtime.GOROOT(), "bar.go"),
PackagePath: "bar",
},
}

var sorted []string
Expand Down
104 changes: 99 additions & 5 deletions parser_test.go
Expand Up @@ -3,6 +3,7 @@ package swag
import (
"bytes"
"encoding/json"
"errors"
"go/ast"
goparser "go/parser"
"go/token"
Expand Down Expand Up @@ -2160,13 +2161,106 @@ func TestParseExternalModels(t *testing.T) {
}

func TestParseGoList(t *testing.T) {
searchDir := "testdata/golist"
mainAPIFile := "main.go"
p := New()
p := New(ParseUsingGoList(true))
p.ParseDependency = true
p.parseGoList = true
err := p.ParseAPI(searchDir, mainAPIFile, defaultParseDepth)
assert.NoError(t, err)

go111moduleEnv := os.Getenv("GO111MODULE")

cases := []struct {
name string
gomodule bool
searchDir string
err error
run func(searchDir string) error
}{
{
name: "disableGOMODULE",
gomodule: false,
searchDir: "testdata/golist_disablemodule",
run: func(searchDir string) error {
return p.ParseAPI(searchDir, mainAPIFile, defaultParseDepth)
},
},
{
name: "enableGOMODULE",
gomodule: true,
searchDir: "testdata/golist",
run: func(searchDir string) error {
return p.ParseAPI(searchDir, mainAPIFile, defaultParseDepth)
},
},
{
name: "invalid_main",
gomodule: true,
searchDir: "testdata/golist_invalid",
err: errors.New("no such file or directory"),
run: func(searchDir string) error {
return p.ParseAPI(searchDir, "invalid/main.go", defaultParseDepth)
},
},
{
name: "internal_invalid_pkg",
gomodule: true,
searchDir: "testdata/golist_invalid",
err: errors.New("expected 'package', found This"),
run: func(searchDir string) error {
mockErrGoFile := "testdata/golist_invalid/err.go"
f, err := os.OpenFile(mockErrGoFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return err
}
defer f.Close()
_, err = f.Write([]byte(`package invalid
function a() {}`))
if err != nil {
return err
}
defer os.Remove(mockErrGoFile)
return p.ParseAPI(searchDir, mainAPIFile, defaultParseDepth)
},
},
{
name: "invalid_pkg",
gomodule: true,
searchDir: "testdata/golist_invalid",
err: errors.New("expected 'package', found This"),
run: func(searchDir string) error {
mockErrGoFile := "testdata/invalid_external_pkg/invalid/err.go"
f, err := os.OpenFile(mockErrGoFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return err
}
defer f.Close()
_, err = f.Write([]byte(`package invalid
function a() {}`))
if err != nil {
return err
}
defer os.Remove(mockErrGoFile)
return p.ParseAPI(searchDir, mainAPIFile, defaultParseDepth)
},
},
}

for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if c.gomodule {
os.Setenv("GO111MODULE", "on")
} else {
os.Setenv("GO111MODULE", "off")
}
err := c.run(c.searchDir)
os.Setenv("GO111MODULE", go111moduleEnv)
if c.err == nil {
assert.NoError(t, err)
} else {
assert.Error(t, err)
}
})
}
}

func TestParser_ParseStructArrayObject(t *testing.T) {
Expand Down
28 changes: 27 additions & 1 deletion testdata/golist/api/api.go
Expand Up @@ -4,9 +4,35 @@ package api
#include "foo.h"
*/
import "C"
import "fmt"
import (
"fmt"
"net/http"
)

func PrintInt(i, j int) {
res := C.add(C.int(i), C.int(j))
fmt.Println(res)
}

type Foo struct {
ID int `json:"id"`
Name string `json:"name"`
PhotoUrls []string `json:"photoUrls"`
Status string `json:"status"`
}

// GetFoo example
// @Summary Get foo
// @Description get foo
// @ID foo
// @Accept json
// @Produce json
// @Param some_id query int true "Some ID"
// @Param some_foo formData Foo true "Foo"
// @Success 200 {string} string "ok"
// @Failure 400 {object} web.APIError "We need ID!!"
// @Failure 404 {object} web.APIError "Can not find ID"
// @Router /testapi/foo [get]
func GetFoo(w http.ResponseWriter, r *http.Request) {
// write your code
}
8 changes: 7 additions & 1 deletion testdata/golist/main.go
Expand Up @@ -19,12 +19,18 @@ import (
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html

// @securityDefinitions.apikey ApiKeyAuth
// @in header
// @name Authorization

// @query.collection.format multi
// @host petstore.swagger.io
// @BasePath /v2
func main() {
goapi.PrintInt(10, 5)
http.HandleFunc("/testapi/get-string-by-int/", api.GetStringByInt)
http.HandleFunc("//testapi/get-struct-array-by-string/", api.GetStructArrayByString)
http.HandleFunc("/testapi/get-struct-array-by-string/", api.GetStructArrayByString)
http.HandleFunc("/testapi/upload", api.Upload)
http.HandleFunc("/testapi/foo", goapi.GetFoo)
http.ListenAndServe(":8080", nil)
}
14 changes: 14 additions & 0 deletions testdata/golist_disablemodule/api/api.go
@@ -0,0 +1,14 @@
package api

/*
#include "foo.h"
*/
import "C"
import (
"fmt"
)

func PrintInt(i, j int) {
res := C.add(C.int(i), C.int(j))
fmt.Println(res)
}
3 changes: 3 additions & 0 deletions testdata/golist_disablemodule/api/foo.c
@@ -0,0 +1,3 @@
int add(int a, int b) {
return a + b;
}
1 change: 1 addition & 0 deletions testdata/golist_disablemodule/api/foo.h
@@ -0,0 +1 @@
int add(int, int);

0 comments on commit ceb23ac

Please sign in to comment.