gomod_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. package ctx
  2. import (
  3. "bytes"
  4. "go/build"
  5. "os"
  6. "path/filepath"
  7. "reflect"
  8. "testing"
  9. "github.com/stretchr/testify/assert"
  10. "github.com/zeromicro/go-zero/core/stringx"
  11. "github.com/zeromicro/go-zero/tools/goctl/rpc/execx"
  12. "github.com/zeromicro/go-zero/tools/goctl/util/pathx"
  13. )
  14. func TestProjectFromGoMod(t *testing.T) {
  15. dft := build.Default
  16. gp := dft.GOPATH
  17. if len(gp) == 0 {
  18. return
  19. }
  20. projectName := stringx.Rand()
  21. dir := filepath.Join(gp, "src", projectName)
  22. err := pathx.MkdirIfNotExist(dir)
  23. if err != nil {
  24. return
  25. }
  26. _, err = execx.Run("go mod init "+projectName, dir)
  27. assert.Nil(t, err)
  28. defer func() {
  29. _ = os.RemoveAll(dir)
  30. }()
  31. ctx, err := projectFromGoMod(dir)
  32. assert.Nil(t, err)
  33. assert.Equal(t, projectName, ctx.Path)
  34. assert.Equal(t, dir, ctx.Dir)
  35. }
  36. func Test_getRealModule(t *testing.T) {
  37. type args struct {
  38. workDir string
  39. execRun execx.RunFunc
  40. }
  41. tests := []struct {
  42. name string
  43. args args
  44. want *Module
  45. wantErr bool
  46. }{
  47. {
  48. name: "single module",
  49. args: args{
  50. workDir: "/home/foo",
  51. execRun: func(arg, dir string, in ...*bytes.Buffer) (string, error) {
  52. return `{
  53. "Path":"foo",
  54. "Dir":"/home/foo",
  55. "GoMod":"/home/foo/go.mod",
  56. "GoVersion":"go1.16"}`, nil
  57. },
  58. },
  59. want: &Module{
  60. Path: "foo",
  61. Dir: "/home/foo",
  62. GoMod: "/home/foo/go.mod",
  63. GoVersion: "go1.16",
  64. },
  65. },
  66. {
  67. name: "go work multiple modules",
  68. args: args{
  69. workDir: "/home/bar",
  70. execRun: func(arg, dir string, in ...*bytes.Buffer) (string, error) {
  71. return `
  72. {
  73. "Path":"foo",
  74. "Dir":"/home/foo",
  75. "GoMod":"/home/foo/go.mod",
  76. "GoVersion":"go1.18"
  77. }
  78. {
  79. "Path":"bar",
  80. "Dir":"/home/bar",
  81. "GoMod":"/home/bar/go.mod",
  82. "GoVersion":"go1.18"
  83. }`, nil
  84. },
  85. },
  86. want: &Module{
  87. Path: "bar",
  88. Dir: "/home/bar",
  89. GoMod: "/home/bar/go.mod",
  90. GoVersion: "go1.18",
  91. },
  92. },
  93. }
  94. for _, tt := range tests {
  95. t.Run(tt.name, func(t *testing.T) {
  96. got, err := getRealModule(tt.args.workDir, tt.args.execRun)
  97. if (err != nil) != tt.wantErr {
  98. t.Errorf("getRealModule() error = %v, wantErr %v", err, tt.wantErr)
  99. return
  100. }
  101. if !reflect.DeepEqual(got, tt.want) {
  102. t.Errorf("getRealModule() = %v, want %v", got, tt.want)
  103. }
  104. })
  105. }
  106. }