gen_test.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package generator
  2. import (
  3. "go/build"
  4. "os"
  5. "path/filepath"
  6. "strings"
  7. "testing"
  8. "github.com/stretchr/testify/assert"
  9. "github.com/tal-tech/go-zero/core/logx"
  10. "github.com/tal-tech/go-zero/core/stringx"
  11. conf "github.com/tal-tech/go-zero/tools/goctl/config"
  12. "github.com/tal-tech/go-zero/tools/goctl/rpc/execx"
  13. )
  14. var cfg = &conf.Config{
  15. NamingFormat: "gozero",
  16. }
  17. func TestRpcGenerate(t *testing.T) {
  18. _ = Clean()
  19. dispatcher := NewDefaultGenerator()
  20. err := dispatcher.Prepare()
  21. if err != nil {
  22. logx.Error(err)
  23. return
  24. }
  25. projectName := stringx.Rand()
  26. g := NewRPCGenerator(dispatcher, cfg)
  27. // case go path
  28. src := filepath.Join(build.Default.GOPATH, "src")
  29. _, err = os.Stat(src)
  30. if err != nil {
  31. return
  32. }
  33. projectDir := filepath.Join(src, projectName)
  34. srcDir := projectDir
  35. defer func() {
  36. _ = os.RemoveAll(srcDir)
  37. }()
  38. err = g.Generate("./test.proto", projectDir, []string{src})
  39. assert.Nil(t, err)
  40. _, err = execx.Run("go test "+projectName, projectDir)
  41. if err != nil {
  42. assert.True(t, func() bool {
  43. return strings.Contains(err.Error(), "not in GOROOT") || strings.Contains(err.Error(), "cannot find package")
  44. }())
  45. }
  46. // case go mod
  47. workDir := t.TempDir()
  48. name := filepath.Base(workDir)
  49. _, err = execx.Run("go mod init "+name, workDir)
  50. if err != nil {
  51. logx.Error(err)
  52. return
  53. }
  54. projectDir = filepath.Join(workDir, projectName)
  55. err = g.Generate("./test.proto", projectDir, []string{src})
  56. assert.Nil(t, err)
  57. _, err = execx.Run("go test "+projectName, projectDir)
  58. if err != nil {
  59. assert.True(t, func() bool {
  60. return strings.Contains(err.Error(), "not in GOROOT") || strings.Contains(err.Error(), "cannot find package")
  61. }())
  62. }
  63. // case not in go mod and go path
  64. err = g.Generate("./test.proto", projectDir, []string{src})
  65. assert.Nil(t, err)
  66. _, err = execx.Run("go test "+projectName, projectDir)
  67. if err != nil {
  68. assert.True(t, func() bool {
  69. return strings.Contains(err.Error(), "not in GOROOT") || strings.Contains(err.Error(), "cannot find package")
  70. }())
  71. }
  72. // invalid directory
  73. projectDir = filepath.Join(t.TempDir(), ".....")
  74. err = g.Generate("./test.proto", projectDir, nil)
  75. assert.NotNil(t, err)
  76. }