gen_test.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package generator
  2. import (
  3. "go/build"
  4. "os"
  5. "path/filepath"
  6. "strings"
  7. "testing"
  8. "git.i2edu.net/i2/go-zero/core/logx"
  9. "git.i2edu.net/i2/go-zero/core/stringx"
  10. conf "git.i2edu.net/i2/go-zero/tools/goctl/config"
  11. "git.i2edu.net/i2/go-zero/tools/goctl/rpc/execx"
  12. "github.com/stretchr/testify/assert"
  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. }