From 81ed8514bea693864aeadd2c7f9d6d1196028e60 Mon Sep 17 00:00:00 2001 From: John Date: Tue, 28 May 2019 15:43:05 +0800 Subject: [PATCH 01/10] search package from import paths, while missing type object --- generate/swaggergen/g_docs.go | 81 +++++++++++++++++++++++++++++++---- 1 file changed, 72 insertions(+), 9 deletions(-) diff --git a/generate/swaggergen/g_docs.go b/generate/swaggergen/g_docs.go index 512e01c..a79f751 100644 --- a/generate/swaggergen/g_docs.go +++ b/generate/swaggergen/g_docs.go @@ -54,7 +54,7 @@ const ( astTypeMap = "map" ) -var pkgCache map[string]struct{} //pkg:controller:function:comments comments: key:value +var pkgCache map[string]string //pkg:controller:function:comments comments: key:value var controllerComments map[string]string var importlist map[string]string var controllerList map[string]map[string]*swagger.Item //controllername Paths items @@ -94,7 +94,7 @@ var stdlibObject = map[string]string{ } func init() { - pkgCache = make(map[string]struct{}) + pkgCache = make(map[string]string) controllerComments = make(map[string]string) importlist = make(map[string]string) controllerList = make(map[string]map[string]*swagger.Item) @@ -455,7 +455,7 @@ func analyseControllerPkg(vendorPath, localName, pkgpath string) { if _, ok := pkgCache[pkgpath]; ok { return } - pkgCache[pkgpath] = struct{}{} + pkgCache[pkgpath] = localName } else { beeLogger.Log.Fatalf("Package '%s' does not exist in the GOPATH or vendor path", pkgpath) } @@ -802,7 +802,7 @@ func setParamType(para *swagger.Parameter, typ string, pkgpath, controllerName s paraFormat = typeFormat[1] if para.In == "body" { para.Schema = &swagger.Schema{ - Type: paraType, + Type: paraType, Format: paraFormat, } } @@ -939,7 +939,8 @@ L: // Still searching for the right object continue } - parseObject(d, k, &m, &realTypes, astPkgs, packageName) + + parseObject(fl.Imports, d, k, &m, &realTypes, packageName) // When we've found the correct object, we can stop searching break L @@ -964,7 +965,7 @@ L: return str, m, realTypes } -func parseObject(d *ast.Object, k string, m *swagger.Schema, realTypes *[]string, astPkgs []*ast.Package, packageName string) { +func parseObject(ims []*ast.ImportSpec, d *ast.Object, k string, m *swagger.Schema, realTypes *[]string, packageName string) { ts, ok := d.Decl.(*ast.TypeSpec) if !ok { beeLogger.Log.Fatalf("Unknown type without TypeSec: %v", d) @@ -989,7 +990,7 @@ func parseObject(d *ast.Object, k string, m *swagger.Schema, realTypes *[]string case *ast.Ident: parseIdent(t, k, m, astPkgs) case *ast.StructType: - parseStruct(t, k, m, realTypes, astPkgs, packageName) + parseStruct(ims, t, k, m, realTypes, packageName) } } @@ -1074,7 +1075,7 @@ func parseIdent(st *ast.Ident, k string, m *swagger.Schema, astPkgs []*ast.Packa } -func parseStruct(st *ast.StructType, k string, m *swagger.Schema, realTypes *[]string, astPkgs []*ast.Package, packageName string) { +func parseStruct(ims []*ast.ImportSpec, st *ast.StructType, k string, m *swagger.Schema, realTypes *[]string, packageName string) { m.Title = k if st.Fields.List != nil { m.Properties = make(map[string]swagger.Propertie) @@ -1091,6 +1092,9 @@ func parseStruct(st *ast.StructType, k string, m *swagger.Schema, realTypes *[]s } } *realTypes = append(*realTypes, realType) + + analyseImportPkg(ims, realType) + mp := swagger.Propertie{} isObject := false if isSlice { @@ -1210,7 +1214,7 @@ func parseStruct(st *ast.StructType, k string, m *swagger.Schema, realTypes *[]s for _, fl := range pkg.Files { for nameOfObj, obj := range fl.Scope.Objects { if obj.Name == fmt.Sprint(field.Type) { - parseObject(obj, nameOfObj, nm, realTypes, astPkgs, pkg.Name) + parseObject(fl.Imports, obj, nameOfObj, nm, realTypes, pkg.Name) } } } @@ -1346,3 +1350,62 @@ func str2RealType(s string, typ string) interface{} { return ret } + +func analyseImportPkg(ims []*ast.ImportSpec, realType string) error { + strs := strings.Split(realType, ".") + pkgName := strs[0] + + for _, im := range ims { + pkgPath := strings.Trim(im.Path.Value, "\"") + + if isSystemPackage(pkgPath) { + continue + } + + if val, ok := pkgCache[pkgPath]; ok { + if val == pkgName { + return nil + } + + continue + } + + pkgRealPath := "" + cwd, _ := os.Getwd() + vendorPath := path.Join(cwd, "vendor") + + realPath, _ := filepath.EvalSymlinks(filepath.Join(vendorPath, pkgPath)) + if bu.IsExist(realPath) { + pkgRealPath = realPath + } else { + ok, _, currentpath := bu.SearchGOPATHs(pkgPath) + if ok { + pkgRealPath, _ = filepath.EvalSymlinks(currentpath) + } + } + + if pkgRealPath == "" { + beeLogger.Log.Warnf("Cannot find pkgpath: %s ", pkgPath) + continue + } + + fileSet := token.NewFileSet() + folderPkgs, err := parser.ParseDir(fileSet, pkgRealPath, func(info os.FileInfo) bool { + name := info.Name() + return !info.IsDir() && !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".go") + }, parser.ParseComments) + if err != nil { + beeLogger.Log.Errorf("ParseDir Error, pkgpath:%s error:%s", pkgPath, err) + return err + } + + for _, pkg := range folderPkgs { + if pkgName == pkg.Name || pkgName == fmt.Sprintf("%s", im.Name) { + astPkgs = append(astPkgs, pkg) + pkgCache[pkgPath] = pkgName + } + } + } + + return nil +} From 5d223c6513c66161e7aef413f96bff4924383a59 Mon Sep 17 00:00:00 2001 From: John Date: Tue, 28 May 2019 01:43:30 +0800 Subject: [PATCH 02/10] update to go version 1.12.5 --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 0480311..0b86259 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,6 @@ language: go go: - - 1.10.3 + - 1.12.5 install: - export PATH=$PATH:$HOME/gopath/bin - go get -u github.com/opennota/check/cmd/structcheck From 8357e26a9f92b47cfdf1ba8cf93194428c1ad3d1 Mon Sep 17 00:00:00 2001 From: John Date: Tue, 28 May 2019 16:55:07 +0800 Subject: [PATCH 03/10] fix warning --- generate/swaggergen/g_docs.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/generate/swaggergen/g_docs.go b/generate/swaggergen/g_docs.go index a79f751..dba063d 100644 --- a/generate/swaggergen/g_docs.go +++ b/generate/swaggergen/g_docs.go @@ -1400,7 +1400,7 @@ func analyseImportPkg(ims []*ast.ImportSpec, realType string) error { } for _, pkg := range folderPkgs { - if pkgName == pkg.Name || pkgName == fmt.Sprintf("%s", im.Name) { + if pkgName == pkg.Name || pkgName == im.Name.Name { astPkgs = append(astPkgs, pkg) pkgCache[pkgPath] = pkgName } From 9541046a29928d782ceba2537b01c3b898abbf73 Mon Sep 17 00:00:00 2001 From: John Date: Fri, 5 Feb 2021 09:44:52 +0800 Subject: [PATCH 04/10] load package from ouside of the project --- generate/swaggergen/g_docs.go | 141 ++++++++++++++++++++-------------- 1 file changed, 82 insertions(+), 59 deletions(-) diff --git a/generate/swaggergen/g_docs.go b/generate/swaggergen/g_docs.go index 0fc4223..2f59777 100644 --- a/generate/swaggergen/g_docs.go +++ b/generate/swaggergen/g_docs.go @@ -35,6 +35,8 @@ import ( yaml "gopkg.in/yaml.v2" + bu "github.com/beego/bee/v2/utils" + beeLogger "github.com/beego/bee/v2/logger" "github.com/beego/beego/v2/core/utils" "github.com/beego/beego/v2/server/web/swagger" @@ -54,13 +56,14 @@ const ( astTypeMap = "map" ) -var pkgCache map[string]string //pkg:controller:function:comments comments: key:value +var pkgCache map[string]struct{} //pkg:controller:function:comments comments: key:value var controllerComments map[string]string var importlist map[string]string var controllerList map[string]map[string]*swagger.Item //controllername Paths items var modelsList map[string]map[string]swagger.Schema var rootapi swagger.Swagger var astPkgs []*ast.Package +var pkgLoadedCache map[string]struct{} // refer to builtin.go var basicTypes = map[string]string{ @@ -94,12 +97,13 @@ var stdlibObject = map[string]string{ } func init() { - pkgCache = make(map[string]string) + pkgCache = make(map[string]struct{}) controllerComments = make(map[string]string) importlist = make(map[string]string) controllerList = make(map[string]map[string]*swagger.Item) modelsList = make(map[string]map[string]swagger.Schema) astPkgs = make([]*ast.Package, 0) + pkgLoadedCache = make(map[string]struct{}) } // parsePackagesFromDir parses packages from a given directory @@ -152,6 +156,16 @@ func parsePackageFromDir(path string) error { astPkgs = append(astPkgs, v) } + if len(folderPkgs) != 0 { + workPath := bu.GetBeeWorkPath() + parentPath := filepath.Dir(workPath) + rel, err := filepath.Rel(parentPath, path) + if err != nil { + return err + } + pkgLoadedCache[rel] = struct{}{} + } + return nil } @@ -448,7 +462,7 @@ func analyseControllerPkg(localName, pkgpath string) { if _, ok := pkgCache[pkgpath]; ok { return } - pkgCache[pkgpath] = localName + pkgCache[pkgpath] = struct{}{} } else { beeLogger.Log.Fatalf("Package '%s' does not have source directory", pkgpath) } @@ -934,7 +948,7 @@ L: continue } - parseObject(fl.Imports, d, k, &m, &realTypes, packageName) + parseObject(fl.Imports, d, k, &m, &realTypes, astPkgs, packageName) // When we've found the correct object, we can stop searching break L @@ -959,7 +973,7 @@ L: return str, m, realTypes } -func parseObject(ims []*ast.ImportSpec, d *ast.Object, k string, m *swagger.Schema, realTypes *[]string, packageName string) { +func parseObject(imports []*ast.ImportSpec, d *ast.Object, k string, m *swagger.Schema, realTypes *[]string, astPkgs []*ast.Package, packageName string) { ts, ok := d.Decl.(*ast.TypeSpec) if !ok { beeLogger.Log.Fatalf("Unknown type without TypeSec: %v", d) @@ -984,7 +998,7 @@ func parseObject(ims []*ast.ImportSpec, d *ast.Object, k string, m *swagger.Sche case *ast.Ident: parseIdent(t, k, m, astPkgs) case *ast.StructType: - parseStruct(ims, t, k, m, realTypes, packageName) + parseStruct(imports, t, k, m, realTypes, astPkgs, packageName) } } @@ -1069,7 +1083,7 @@ func parseIdent(st *ast.Ident, k string, m *swagger.Schema, astPkgs []*ast.Packa } -func parseStruct(ims []*ast.ImportSpec, st *ast.StructType, k string, m *swagger.Schema, realTypes *[]string, packageName string) { +func parseStruct(imports []*ast.ImportSpec, st *ast.StructType, k string, m *swagger.Schema, realTypes *[]string, astPkgs []*ast.Package, packageName string) { m.Title = k if st.Fields.List != nil { m.Properties = make(map[string]swagger.Propertie) @@ -1085,10 +1099,12 @@ func parseStruct(ims []*ast.ImportSpec, st *ast.StructType, k string, m *swagger realType = packageName + "." + realType } } + + if !isBasicType(realType) && sType == astTypeObject { + checkAndLoadPackage(imports, realType, packageName) + } + *realTypes = append(*realTypes, realType) - - analyseImportPkg(ims, realType) - mp := swagger.Propertie{} isObject := false if isSlice { @@ -1208,7 +1224,7 @@ func parseStruct(ims []*ast.ImportSpec, st *ast.StructType, k string, m *swagger for _, fl := range pkg.Files { for nameOfObj, obj := range fl.Scope.Objects { if pkg.Name+"."+obj.Name == realType { - parseObject(obj, nameOfObj, nm, realTypes, astPkgs, pkg.Name) + parseObject(imports, obj, nameOfObj, nm, realTypes, astPkgs, pkg.Name) } } } @@ -1345,61 +1361,68 @@ func str2RealType(s string, typ string) interface{} { return ret } -func analyseImportPkg(ims []*ast.ImportSpec, realType string) error { - strs := strings.Split(realType, ".") - pkgName := strs[0] +func checkAndLoadPackage(imports []*ast.ImportSpec, realType, curPkgName string) { + arr := strings.Split(realType, ".") + if len(arr) != 2 { + return + } + objectPkgName := arr[0] + if objectPkgName == curPkgName { + return + } + pkgPath := "" + for _, im := range imports { + importPath := "" + if im.Path != nil { + importPath = strings.Trim(im.Path.Value, `"`) + } - for _, im := range ims { - pkgPath := strings.Trim(im.Path.Value, "\"") - - if isSystemPackage(pkgPath) { + if importPath == "" { continue } - if val, ok := pkgCache[pkgPath]; ok { - if val == pkgName { - return nil - } - - continue + if im.Name != nil && im.Name.Name == objectPkgName { + pkgPath = importPath + break } - pkgRealPath := "" - cwd, _ := os.Getwd() - vendorPath := path.Join(cwd, "vendor") - - realPath, _ := filepath.EvalSymlinks(filepath.Join(vendorPath, pkgPath)) - if bu.IsExist(realPath) { - pkgRealPath = realPath - } else { - ok, _, currentpath := bu.SearchGOPATHs(pkgPath) - if ok { - pkgRealPath, _ = filepath.EvalSymlinks(currentpath) - } - } - - if pkgRealPath == "" { - beeLogger.Log.Warnf("Cannot find pkgpath: %s ", pkgPath) - continue - } - - fileSet := token.NewFileSet() - folderPkgs, err := parser.ParseDir(fileSet, pkgRealPath, func(info os.FileInfo) bool { - name := info.Name() - return !info.IsDir() && !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".go") - }, parser.ParseComments) - if err != nil { - beeLogger.Log.Errorf("ParseDir Error, pkgpath:%s error:%s", pkgPath, err) - return err - } - - for _, pkg := range folderPkgs { - if pkgName == pkg.Name || pkgName == im.Name.Name { - astPkgs = append(astPkgs, pkg) - pkgCache[pkgPath] = pkgName - } + _, pkgName := filepath.Split(importPath) + if pkgName == objectPkgName { + pkgPath = importPath + break } } - return nil + if pkgPath == "" { + beeLogger.Log.Warnf("%s missing import package", realType) + return + } + + if isSystemPackage(pkgPath) { + return + } + if _, ok := pkgLoadedCache[pkgPath]; ok { + return + } + + pkg, err := build.Default.Import(pkgPath, ".", build.FindOnly) + if err != nil { + beeLogger.Log.Warnf("Package %s cannot be imported, err:%v", pkgPath, err) + } + pkgRealpath := pkg.Dir + + fileSet := token.NewFileSet() + pkgs, err := parser.ParseDir(fileSet, pkgRealpath, func(info os.FileInfo) bool { + name := info.Name() + return !info.IsDir() && !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".go") + }, parser.ParseComments) + if err != nil { + beeLogger.Log.Fatalf("Error while parsing dir at '%s': %s", pkgRealpath, err) + } + + for _, pkg := range pkgs { + astPkgs = append(astPkgs, pkg) + } + + pkgLoadedCache[pkgPath] = struct{}{} } From 02a66c7bd7adfd2dc2ac5e634b9d932045aeed0d Mon Sep 17 00:00:00 2001 From: John Date: Sat, 6 Feb 2021 19:44:32 +0800 Subject: [PATCH 05/10] change log level --- generate/swaggergen/g_docs.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/generate/swaggergen/g_docs.go b/generate/swaggergen/g_docs.go index 2f59777..e2fbb6a 100644 --- a/generate/swaggergen/g_docs.go +++ b/generate/swaggergen/g_docs.go @@ -1408,6 +1408,7 @@ func checkAndLoadPackage(imports []*ast.ImportSpec, realType, curPkgName string) pkg, err := build.Default.Import(pkgPath, ".", build.FindOnly) if err != nil { beeLogger.Log.Warnf("Package %s cannot be imported, err:%v", pkgPath, err) + return } pkgRealpath := pkg.Dir @@ -1417,7 +1418,7 @@ func checkAndLoadPackage(imports []*ast.ImportSpec, realType, curPkgName string) return !info.IsDir() && !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".go") }, parser.ParseComments) if err != nil { - beeLogger.Log.Fatalf("Error while parsing dir at '%s': %s", pkgRealpath, err) + beeLogger.Log.Warnf("Error while parsing dir at '%s': %s", pkgRealpath, err) } for _, pkg := range pkgs { From d995fc5328f5fe2ce9843e573f9509ba8019c76c Mon Sep 17 00:00:00 2001 From: John Date: Sat, 6 Feb 2021 20:10:12 +0800 Subject: [PATCH 06/10] add unit test --- generate/swaggergen/go_docs_test.go | 117 ++++++++++++++++++++++++++++ 1 file changed, 117 insertions(+) create mode 100644 generate/swaggergen/go_docs_test.go diff --git a/generate/swaggergen/go_docs_test.go b/generate/swaggergen/go_docs_test.go new file mode 100644 index 0000000..ddfbdb7 --- /dev/null +++ b/generate/swaggergen/go_docs_test.go @@ -0,0 +1,117 @@ +package swaggergen + +import ( + "go/ast" + "go/build" + "io/ioutil" + "os" + "path/filepath" + "testing" +) + +//package model +// +//import ( +// "github.com/shopspring/decimal" +//) +// +//type Object struct{ +// Total decimal.Decimal +//} +func TestCheckAndLoadPackageOnGoMod(t *testing.T) { + var ( + pkgName = "decimal" + pkgImportPath = "github.com/shopspring/decimal" + ) + + defer os.Setenv("GO111MODULE", os.Getenv("GO111MODULE")) + os.Setenv("GO111MODULE", "on") + + imports := []*ast.ImportSpec{ + { + Path: &ast.BasicLit{ + Value: pkgImportPath, + }, + }, + } + checkAndLoadPackage(imports, "decimal.Decimal", "model") + if len(astPkgs) == 0 { + t.Fatalf("failed to load module: %s", pkgImportPath) + } + notLoadFlag := true + for _, v := range astPkgs { + if v.Name == pkgName { + notLoadFlag = false + } + } + if notLoadFlag { + t.Fatalf("failed to load module: %s", pkgImportPath) + } +} + +//package model +// +//import ( +//"example.com/comm" +//) +// +//type Object struct { +// Total comm.Common +//} +func TestCheckAndLoadPackageOnGoPath(t *testing.T) { + var ( + pkgName = "comm" + pkgImportPath = "example.com/comm" + + testCommPkg = ` +package comm + +type Common struct { + Code string + Error string +} +` + ) + + gopath, err := ioutil.TempDir("", "gobuild-gopath") + if err != nil { + t.Fatal(err) + } + + defer os.RemoveAll(gopath) + + if err := os.MkdirAll(filepath.Join(gopath, "src/example.com/comm"), 0777); err != nil { + t.Fatal(err) + } + + if err := ioutil.WriteFile(filepath.Join(gopath, "src/example.com/comm/comm.go"), []byte(testCommPkg), 0666); err != nil { + t.Fatal(err) + } + + defer os.Setenv("GO111MODULE", os.Getenv("GO111MODULE")) + os.Setenv("GO111MODULE", "off") + defer os.Setenv("GOPATH", os.Getenv("GOPATH")) + os.Setenv("GOPATH", gopath) + build.Default.GOPATH = gopath + + imports := []*ast.ImportSpec{ + { + Path: &ast.BasicLit{ + Value: pkgImportPath, + }, + }, + } + checkAndLoadPackage(imports, "comm.Common", "model") + if len(astPkgs) == 0 { + t.Fatalf("failed to load module: %s", pkgImportPath) + } + notLoadFlag := true + for _, v := range astPkgs { + if v.Name == pkgName { + notLoadFlag = false + } + } + if notLoadFlag { + t.Fatalf("failed to load module: %s", pkgImportPath) + } +} From 7f80477761eec54d6ed10f9510495ab40be7d442 Mon Sep 17 00:00:00 2001 From: John Date: Sat, 6 Feb 2021 20:22:05 +0800 Subject: [PATCH 07/10] update .travis.yml --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index 9c5f4d7..66d2dd9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -12,6 +12,7 @@ script: - cd $(dirname `dirname $(pwd)`)/beego/bee - export GO111MODULE="on" - go mod download + - go test -coverprofile=coverage.txt -covermode=atomic ./... - find . ! \( -path './vendor' -prune \) -type f -name '*.go' -print0 | xargs -0 gofmt -l -s - go list ./... | grep -v /vendor/ | grep -v /pkg/mod/ - go vet $(go list ./... | grep -v /vendor/ | grep -v /pkg/mod/ ) From 637637efb21f16a9d916329351b373e828f88e84 Mon Sep 17 00:00:00 2001 From: John Date: Sat, 6 Feb 2021 20:32:17 +0800 Subject: [PATCH 08/10] add copyright comment --- generate/swaggergen/go_docs_test.go | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/generate/swaggergen/go_docs_test.go b/generate/swaggergen/go_docs_test.go index ddfbdb7..d6135d4 100644 --- a/generate/swaggergen/go_docs_test.go +++ b/generate/swaggergen/go_docs_test.go @@ -1,3 +1,17 @@ +// Copyright 2013 bee authors +// +// Licensed under the Apache License, Version 2.0 (the "License"): you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. + package swaggergen import ( From 824fa639f050b1f401df0029aceb02c221ff9edd Mon Sep 17 00:00:00 2001 From: John Date: Sun, 7 Feb 2021 10:47:42 +0800 Subject: [PATCH 09/10] add more test case --- generate/swaggergen/go_docs_test.go | 170 +++++++++++++++++++++------- 1 file changed, 130 insertions(+), 40 deletions(-) diff --git a/generate/swaggergen/go_docs_test.go b/generate/swaggergen/go_docs_test.go index d6135d4..f96ce12 100644 --- a/generate/swaggergen/go_docs_test.go +++ b/generate/swaggergen/go_docs_test.go @@ -26,57 +26,103 @@ import ( //package model // //import ( -// "github.com/shopspring/decimal" +//"sync" +// +//"example.com/pkgnotexist" +//"github.com/shopspring/decimal" //) // -//type Object struct{ -// Total decimal.Decimal +//type Object struct { +// Field1 decimal.Decimal +// Field2 pkgnotexist.TestType +// Field3 sync.Map //} func TestCheckAndLoadPackageOnGoMod(t *testing.T) { - var ( - pkgName = "decimal" - pkgImportPath = "github.com/shopspring/decimal" - ) - defer os.Setenv("GO111MODULE", os.Getenv("GO111MODULE")) os.Setenv("GO111MODULE", "on") - imports := []*ast.ImportSpec{ + testCases := []struct { + pkgName string + pkgImportPath string + imports []*ast.ImportSpec + realType string + curPkgName string + expected bool + }{ { - Path: &ast.BasicLit{ - Value: pkgImportPath, + pkgName: "decimal", + pkgImportPath: "github.com/shopspring/decimal", + imports: []*ast.ImportSpec{ + { + Path: &ast.BasicLit{ + Value: "github.com/shopspring/decimal", + }, + }, }, + realType: "decimal.Decimal", + curPkgName: "model", + expected: true, + }, + { + pkgName: "pkgnotexist", + pkgImportPath: "example.com/pkgnotexist", + imports: []*ast.ImportSpec{ + { + Path: &ast.BasicLit{ + Value: "example.com/pkgnotexist", + }, + }, + }, + realType: "pkgnotexist.TestType", + curPkgName: "model", + expected: false, + }, + { + pkgName: "sync", + pkgImportPath: "sync", + imports: []*ast.ImportSpec{ + { + Path: &ast.BasicLit{ + Value: "sync", + }, + }, + }, + realType: "sync.Map", + curPkgName: "model", + expected: false, }, } - checkAndLoadPackage(imports, "decimal.Decimal", "model") - if len(astPkgs) == 0 { - t.Fatalf("failed to load module: %s", pkgImportPath) - } - notLoadFlag := true - for _, v := range astPkgs { - if v.Name == pkgName { - notLoadFlag = false + + for _, test := range testCases { + checkAndLoadPackage(test.imports, test.realType, test.curPkgName) + result := false + for _, v := range astPkgs { + if v.Name == test.pkgName { + result = true + } + } + if test.expected != result { + t.Fatalf("load module error, expected: %v, result: %v", test.expected, result) } - } - if notLoadFlag { - t.Fatalf("failed to load module: %s", pkgImportPath) } } //package model // //import ( +//"sync" +// //"example.com/comm" +//"example.com/pkgnotexist" //) // //type Object struct { -// Total comm.Common +// Field1 comm.Common +// Field2 pkgnotexist.TestType +// Field3 sync.Map //} func TestCheckAndLoadPackageOnGoPath(t *testing.T) { var ( - pkgName = "comm" - pkgImportPath = "example.com/comm" - testCommPkg = ` package comm @@ -108,24 +154,68 @@ type Common struct { os.Setenv("GOPATH", gopath) build.Default.GOPATH = gopath - imports := []*ast.ImportSpec{ + testCases := []struct { + pkgName string + pkgImportPath string + imports []*ast.ImportSpec + realType string + curPkgName string + expected bool + }{ { - Path: &ast.BasicLit{ - Value: pkgImportPath, + pkgName: "comm", + pkgImportPath: "example.com/comm", + imports: []*ast.ImportSpec{ + { + Path: &ast.BasicLit{ + Value: "example.com/comm", + }, + }, }, + realType: "comm.Common", + curPkgName: "model", + expected: true, + }, + { + pkgName: "pkgnotexist", + pkgImportPath: "example.com/pkgnotexist", + imports: []*ast.ImportSpec{ + { + Path: &ast.BasicLit{ + Value: "example.com/pkgnotexist", + }, + }, + }, + realType: "pkgnotexist.TestType", + curPkgName: "model", + expected: false, + }, + { + pkgName: "sync", + pkgImportPath: "sync", + imports: []*ast.ImportSpec{ + { + Path: &ast.BasicLit{ + Value: "sync", + }, + }, + }, + realType: "sync.Map", + curPkgName: "model", + expected: false, }, } - checkAndLoadPackage(imports, "comm.Common", "model") - if len(astPkgs) == 0 { - t.Fatalf("failed to load module: %s", pkgImportPath) - } - notLoadFlag := true - for _, v := range astPkgs { - if v.Name == pkgName { - notLoadFlag = false + + for _, test := range testCases { + checkAndLoadPackage(test.imports, test.realType, test.curPkgName) + result := false + for _, v := range astPkgs { + if v.Name == test.pkgName { + result = true + } + } + if test.expected != result { + t.Fatalf("load module error, expected: %v, result: %v", test.expected, result) } } - if notLoadFlag { - t.Fatalf("failed to load module: %s", pkgImportPath) - } } From 9428a53176c2807c95b7d617907dec3794fb6f38 Mon Sep 17 00:00:00 2001 From: John Date: Sun, 7 Feb 2021 10:54:57 +0800 Subject: [PATCH 10/10] fix test case --- generate/swaggergen/go_docs_test.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/generate/swaggergen/go_docs_test.go b/generate/swaggergen/go_docs_test.go index f96ce12..6b3aec9 100644 --- a/generate/swaggergen/go_docs_test.go +++ b/generate/swaggergen/go_docs_test.go @@ -99,6 +99,7 @@ func TestCheckAndLoadPackageOnGoMod(t *testing.T) { for _, v := range astPkgs { if v.Name == test.pkgName { result = true + break } } if test.expected != result { @@ -212,6 +213,7 @@ type Common struct { for _, v := range astPkgs { if v.Name == test.pkgName { result = true + break } } if test.expected != result {