add more test (#189)

* new test

* import bug when with quotation

* new test

* add test condition

* rpc template command use -o param

Co-authored-by: kim <xutao@xiaoheiban.cn>
This commit is contained in:
kingxt
2020-11-07 17:13:40 +08:00
committed by GitHub
parent 7d7cb836af
commit 7f6eceb5a3
9 changed files with 144 additions and 51 deletions

View File

@@ -94,7 +94,6 @@ func ApiFormatByPath(apiFilePath string) error {
} }
func apiFormat(data string) (string, error) { func apiFormat(data string) (string, error) {
r := reg.ReplaceAllStringFunc(data, func(m string) string { r := reg.ReplaceAllStringFunc(data, func(m string) string {
parts := reg.FindStringSubmatch(m) parts := reg.FindStringSubmatch(m)
if len(parts) < 2 { if len(parts) < 2 {

View File

@@ -1,11 +1,9 @@
package gogen package gogen
import ( import (
"bytes"
"errors" "errors"
"fmt" "fmt"
"os" "os"
"os/exec"
"path" "path"
"path/filepath" "path/filepath"
"strconv" "strconv"
@@ -60,7 +58,6 @@ func DoGenProject(apiFile, dir string, force bool) error {
logx.Must(genHandlers(dir, api)) logx.Must(genHandlers(dir, api))
logx.Must(genRoutes(dir, api, force)) logx.Must(genRoutes(dir, api, force))
logx.Must(genLogic(dir, api)) logx.Must(genLogic(dir, api))
createGoModFileIfNeed(dir)
if err := backupAndSweep(apiFile); err != nil { if err := backupAndSweep(apiFile); err != nil {
return err return err
@@ -129,34 +126,3 @@ func sweep() error {
return nil return nil
}) })
} }
func createGoModFileIfNeed(dir string) {
absDir, err := filepath.Abs(dir)
if err != nil {
panic(err)
}
_, hasGoMod := util.FindGoModPath(dir)
if hasGoMod {
return
}
gopath := os.Getenv("GOPATH")
parent := path.Join(gopath, "src")
pos := strings.Index(absDir, parent)
if pos >= 0 {
return
}
moduleName := absDir[len(filepath.Dir(absDir))+1:]
cmd := exec.Command("go", "mod", "init", moduleName)
cmd.Dir = dir
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if err = cmd.Run(); err != nil {
fmt.Println(err.Error())
}
outStr, errStr := string(stdout.Bytes()), string(stderr.Bytes())
fmt.Printf(outStr + "\n" + errStr)
}

View File

@@ -10,6 +10,7 @@ import (
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/tal-tech/go-zero/tools/goctl/api/parser" "github.com/tal-tech/go-zero/tools/goctl/api/parser"
"github.com/tal-tech/go-zero/tools/goctl/rpc/execx"
) )
const testApiTemplate = ` const testApiTemplate = `
@@ -29,6 +30,9 @@ type Response struct {
Message string ` + "`" + `json:"message"` + "`" + ` Message string ` + "`" + `json:"message"` + "`" + `
} }
@server(
group: greet
)
service A-api { service A-api {
@server( @server(
handler: GreetHandler handler: GreetHandler
@@ -37,6 +41,7 @@ service A-api {
@server( @server(
handler: NoResponseHandler handler: NoResponseHandler
) )
get /greet/get(Request) returns get /greet/get(Request) returns
} }
@@ -204,6 +209,75 @@ service A-api {
} }
` `
const hasCommentApiTest = `
type Inline struct {
}
type Request struct {
Inline
Name string ` + "`" + `path:"name,options=you|me"` + "`" + ` // name in path
}
type Response struct {
Message string ` + "`" + `json:"msg"` + "`" + ` // message
}
service A-api {
@doc(helloworld)
@server(
handler: GreetHandler
)
get /greet/from/:name(Request) returns (Response)
}
`
const hasInlineNoExistTest = `
type Request struct {
Inline
Name string ` + "`" + `path:"name,options=you|me"` + "`" + `
}
type Response struct {
Message string ` + "`" + `json:"message"` + "`" + ` // message
}
service A-api {
@doc(helloworld)
@server(
handler: GreetHandler
)
get /greet/from/:name(Request) returns (Response)
}
`
const importApi = `
type ImportData struct {
Name string ` + "`" + `path:"name,options=you|me"` + "`" + `
}
`
const hasImportApi = `
import "importApi.api"
type Request struct {
Name string ` + "`" + `path:"name,options=you|me"` + "`" + `
}
type Response struct {
Message string ` + "`" + `json:"message"` + "`" + ` // message
}
service A-api {
@server(
handler: GreetHandler
)
get /greet/from/:name(Request) returns (Response)
}
`
func TestParser(t *testing.T) { func TestParser(t *testing.T) {
filename := "greet.api" filename := "greet.api"
err := ioutil.WriteFile(filename, []byte(testApiTemplate), os.ModePerm) err := ioutil.WriteFile(filename, []byte(testApiTemplate), os.ModePerm)
@@ -367,6 +441,64 @@ func TestApiRoutes(t *testing.T) {
validate(t, filename) validate(t, filename)
} }
func TestHasCommentRoutes(t *testing.T) {
filename := "greet.api"
err := ioutil.WriteFile(filename, []byte(hasCommentApiTest), os.ModePerm)
assert.Nil(t, err)
defer os.Remove(filename)
parser, err := parser.NewParser(filename)
assert.Nil(t, err)
_, err = parser.Parse()
assert.Nil(t, err)
validate(t, filename)
}
func TestInlineTypeNotExist(t *testing.T) {
filename := "greet.api"
err := ioutil.WriteFile(filename, []byte(hasInlineNoExistTest), os.ModePerm)
assert.Nil(t, err)
defer os.Remove(filename)
parser, err := parser.NewParser(filename)
assert.Nil(t, err)
_, err = parser.Parse()
assert.Nil(t, err)
validate(t, filename)
}
func TestHasImportApi(t *testing.T) {
filename := "greet.api"
err := ioutil.WriteFile(filename, []byte(hasImportApi), os.ModePerm)
assert.Nil(t, err)
defer os.Remove(filename)
importApiName := "importApi.api"
err = ioutil.WriteFile(importApiName, []byte(importApi), os.ModePerm)
assert.Nil(t, err)
defer os.Remove(importApiName)
parser, err := parser.NewParser(filename)
assert.Nil(t, err)
api, err := parser.Parse()
assert.Nil(t, err)
var hasInline bool
for _, ty := range api.Types {
if ty.Name == "ImportData" {
hasInline = true
break
}
}
assert.True(t, hasInline)
validate(t, filename)
}
func validate(t *testing.T, api string) { func validate(t *testing.T, api string) {
dir := "_go" dir := "_go"
err := DoGenProject(api, dir, true) err := DoGenProject(api, dir, true)
@@ -380,6 +512,9 @@ func validate(t *testing.T, api string) {
} }
return nil return nil
}) })
_, err = execx.Run("go test ./...", dir)
assert.Nil(t, err)
} }
func validateCode(code string) error { func validateCode(code string) error {

View File

@@ -90,12 +90,6 @@ func convertTypeCase(types []spec.Type, t string) (string, error) {
if typ.Name == tp { if typ.Name == tp {
defTypes = append(defTypes, tp) defTypes = append(defTypes, tp)
} }
if len(typ.Annotations) > 0 {
if value, ok := apiutil.GetAnnotationValue(typ.Annotations, "serverReplacer", tp); ok {
t = strings.ReplaceAll(t, tp, value)
}
}
} }
} }

View File

@@ -12,7 +12,7 @@ import (
const apiTemplate = ` const apiTemplate = `
type Request struct { type Request struct {
Name string ` + "`" + `path:"name,options=you|me"` + "`" + ` // 框架自动验证请求参数是否合法 Name string ` + "`" + `path:"name,options=you|me"` + "`" + `
} }
type Response struct { type Response struct {

View File

@@ -39,6 +39,8 @@ func NewParser(filename string) (*Parser, error) {
if len(ip) > 0 { if len(ip) > 0 {
item := strings.TrimPrefix(item, "import") item := strings.TrimPrefix(item, "import")
item = strings.TrimSpace(item) item = strings.TrimSpace(item)
item = strings.TrimPrefix(item, `"`)
item = strings.TrimSuffix(item, `"`)
var path = item var path = item
if !util.FileExists(item) { if !util.FileExists(item) {
path = filepath.Join(filepath.Dir(apiAbsPath), item) path = filepath.Join(filepath.Dir(apiAbsPath), item)

View File

@@ -125,7 +125,7 @@ func ParseApi(api string) (*ApiStruct, error) {
} }
func isImportBeginLine(line string) bool { func isImportBeginLine(line string) bool {
return strings.HasPrefix(line, "import") && strings.HasSuffix(line, ".api") return strings.HasPrefix(line, "import") && (strings.HasSuffix(line, ".api") || strings.HasSuffix(line, `.api"`))
} }
func isTypeBeginLine(line string) bool { func isTypeBeginLine(line string) bool {

View File

@@ -224,10 +224,6 @@ var (
Name: "out, o", Name: "out, o",
Usage: "the target path of proto", Usage: "the target path of proto",
}, },
cli.BoolFlag{
Name: "idea",
Usage: "whether the command execution environment is from idea plugin. [optional]",
},
}, },
Action: rpc.RpcTemplate, Action: rpc.RpcTemplate,
}, },

View File

@@ -59,9 +59,10 @@ func RpcNew(c *cli.Context) error {
} }
func RpcTemplate(c *cli.Context) error { func RpcTemplate(c *cli.Context) error {
name := c.Args().First() protoFile := c.String("o")
if len(name) == 0 { if len(protoFile) == 0 {
name = "greet.proto" return errors.New("missing -o")
} }
return generator.ProtoTmpl(name)
return generator.ProtoTmpl(protoFile)
} }