1
0
Эх сурвалжийг харах

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>
kingxt 4 жил өмнө
parent
commit
7f6eceb5a3

+ 0 - 1
tools/goctl/api/format/format.go

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

+ 0 - 34
tools/goctl/api/gogen/gen.go

@@ -1,11 +1,9 @@
 package gogen
 
 import (
-	"bytes"
 	"errors"
 	"fmt"
 	"os"
-	"os/exec"
 	"path"
 	"path/filepath"
 	"strconv"
@@ -60,7 +58,6 @@ func DoGenProject(apiFile, dir string, force bool) error {
 	logx.Must(genHandlers(dir, api))
 	logx.Must(genRoutes(dir, api, force))
 	logx.Must(genLogic(dir, api))
-	createGoModFileIfNeed(dir)
 
 	if err := backupAndSweep(apiFile); err != nil {
 		return err
@@ -129,34 +126,3 @@ func sweep() error {
 		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)
-}

+ 135 - 0
tools/goctl/api/gogen/gen_test.go

@@ -10,6 +10,7 @@ import (
 
 	"github.com/stretchr/testify/assert"
 	"github.com/tal-tech/go-zero/tools/goctl/api/parser"
+	"github.com/tal-tech/go-zero/tools/goctl/rpc/execx"
 )
 
 const testApiTemplate = `
@@ -29,6 +30,9 @@ type Response struct {
   Message string ` + "`" + `json:"message"` + "`" + `
 }
 
+@server(
+	group: greet
+)
 service A-api {
   @server(
     handler: GreetHandler
@@ -37,6 +41,7 @@ service A-api {
 
   @server(
     handler: NoResponseHandler
+    
   )
   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) {
 	filename := "greet.api"
 	err := ioutil.WriteFile(filename, []byte(testApiTemplate), os.ModePerm)
@@ -367,6 +441,64 @@ func TestApiRoutes(t *testing.T) {
 	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) {
 	dir := "_go"
 	err := DoGenProject(api, dir, true)
@@ -380,6 +512,9 @@ func validate(t *testing.T, api string) {
 		}
 		return nil
 	})
+
+	_, err = execx.Run("go test ./...", dir)
+	assert.Nil(t, err)
 }
 
 func validateCode(code string) error {

+ 0 - 6
tools/goctl/api/gogen/gentypes.go

@@ -90,12 +90,6 @@ func convertTypeCase(types []spec.Type, t string) (string, error) {
 			if typ.Name == 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)
-				}
-			}
 		}
 	}
 

+ 1 - 1
tools/goctl/api/new/newservice.go

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

+ 2 - 0
tools/goctl/api/parser/parser.go

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

+ 1 - 1
tools/goctl/api/parser/util.go

@@ -125,7 +125,7 @@ func ParseApi(api string) (*ApiStruct, error) {
 }
 
 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 {

+ 0 - 4
tools/goctl/goctl.go

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

+ 5 - 4
tools/goctl/rpc/cli/cli.go

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