integration_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. // Copyright 2019 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // +build ignore
  5. package main
  6. import (
  7. "archive/tar"
  8. "bytes"
  9. "compress/gzip"
  10. "flag"
  11. "fmt"
  12. "io"
  13. "io/ioutil"
  14. "net/http"
  15. "os"
  16. "os/exec"
  17. "path/filepath"
  18. "regexp"
  19. "runtime"
  20. "strings"
  21. "testing"
  22. "time"
  23. )
  24. var (
  25. regenerate = flag.Bool("regenerate", false, "regenerate files")
  26. protobufVersion = "3.7.1"
  27. golangVersions = []string{"1.9.7", "1.10.8", "1.11.6", "1.12.1"}
  28. golangLatest = golangVersions[len(golangVersions)-1]
  29. // purgeTimeout determines the maximum age of unused sub-directories.
  30. purgeTimeout = 30 * 24 * time.Hour // 1 month
  31. // Variables initialized by mustInitDeps.
  32. goPath string
  33. modulePath string
  34. )
  35. func Test(t *testing.T) {
  36. mustInitDeps(t)
  37. if *regenerate {
  38. t.Run("Generate", func(t *testing.T) {
  39. fmt.Print(mustRunCommand(t, ".", "go", "run", "./internal/cmd/generate-types", "-execute"))
  40. fmt.Print(mustRunCommand(t, ".", "go", "run", "./internal/cmd/generate-protos", "-execute"))
  41. files := strings.Split(strings.TrimSpace(mustRunCommand(t, ".", "git", "ls-files", "*.go")), "\n")
  42. mustRunCommand(t, ".", append([]string{"gofmt", "-w"}, files...)...)
  43. })
  44. t.SkipNow()
  45. }
  46. for _, v := range golangVersions {
  47. t.Run("Go"+v, func(t *testing.T) {
  48. runGo := func(label, workDir string, args ...string) {
  49. args[0] += v
  50. t.Run(label, func(t *testing.T) {
  51. t.Parallel()
  52. mustRunCommand(t, workDir, args...)
  53. })
  54. }
  55. workDir := filepath.Join(goPath, "src", modulePath)
  56. runGo("TestNormal", workDir, "go", "test", "-race", "./...")
  57. runGo("TestPureGo", workDir, "go", "test", "-race", "-tags", "purego", "./...")
  58. runGo("TestReflect", workDir, "go", "test", "-race", "-tags", "protoreflect", "./...")
  59. if v == golangLatest {
  60. runGo("TestProto1Legacy", workDir, "go", "test", "-race", "-tags", "proto1_legacy", "./...")
  61. runGo("TestProtocGenGo", "cmd/protoc-gen-go/testdata", "go", "test")
  62. runGo("TestProtocGenGoGRPC", "cmd/protoc-gen-go-grpc/testdata", "go", "test")
  63. }
  64. })
  65. }
  66. t.Run("GeneratedGoFiles", func(t *testing.T) {
  67. diff := mustRunCommand(t, ".", "go", "run", "./internal/cmd/generate-types")
  68. if strings.TrimSpace(diff) != "" {
  69. t.Fatalf("stale generated files:\n%v", diff)
  70. }
  71. diff = mustRunCommand(t, ".", "go", "run", "./internal/cmd/generate-protos")
  72. if strings.TrimSpace(diff) != "" {
  73. t.Fatalf("stale generated files:\n%v", diff)
  74. }
  75. })
  76. t.Run("FormattedGoFiles", func(t *testing.T) {
  77. files := strings.Split(strings.TrimSpace(mustRunCommand(t, ".", "git", "ls-files", "*.go")), "\n")
  78. diff := mustRunCommand(t, ".", append([]string{"gofmt", "-d"}, files...)...)
  79. if strings.TrimSpace(diff) != "" {
  80. t.Fatalf("unformatted source files:\n%v", diff)
  81. }
  82. })
  83. t.Run("CommittedGitChanges", func(t *testing.T) {
  84. diff := mustRunCommand(t, ".", "git", "diff", "--no-prefix", "HEAD")
  85. if strings.TrimSpace(diff) != "" {
  86. t.Fatalf("uncommitted changes:\n%v", diff)
  87. }
  88. })
  89. t.Run("TrackedGitFiles", func(t *testing.T) {
  90. diff := mustRunCommand(t, ".", "git", "ls-files", "--others", "--exclude-standard")
  91. if strings.TrimSpace(diff) != "" {
  92. t.Fatalf("untracked files:\n%v", diff)
  93. }
  94. })
  95. }
  96. func mustInitDeps(t *testing.T) {
  97. check := func(err error) {
  98. t.Helper()
  99. if err != nil {
  100. t.Fatal(err)
  101. }
  102. }
  103. // Determine the directory to place the test directory.
  104. repoRoot, err := os.Getwd()
  105. check(err)
  106. testDir := filepath.Join(repoRoot, ".cache")
  107. check(os.MkdirAll(testDir, 0775))
  108. // Travis-CI has a hard-coded timeout where it kills the test after
  109. // 10 minutes of a lack of activity on stdout.
  110. // We work around this restriction by periodically printing the timestamp.
  111. ticker := time.NewTicker(5 * time.Minute)
  112. done := make(chan struct{})
  113. go func() {
  114. now := time.Now()
  115. for {
  116. select {
  117. case t := <-ticker.C:
  118. fmt.Printf("\tt=%0.fmin\n", t.Sub(now).Minutes())
  119. case <-done:
  120. return
  121. }
  122. }
  123. }()
  124. defer close(done)
  125. defer ticker.Stop()
  126. // Delete the current directory if non-empty,
  127. // which only occurs if a dependency failed to initialize properly.
  128. var workingDir string
  129. defer func() {
  130. if workingDir != "" {
  131. os.RemoveAll(workingDir) // best-effort
  132. }
  133. }()
  134. // Delete other sub-directories that are no longer relevant.
  135. defer func() {
  136. subDirs := map[string]bool{"bin": true, "gocache": true, "gopath": true}
  137. subDirs["protobuf-"+protobufVersion] = true
  138. for _, v := range golangVersions {
  139. subDirs["go"+v] = true
  140. }
  141. now := time.Now()
  142. fis, _ := ioutil.ReadDir(testDir)
  143. for _, fi := range fis {
  144. if subDirs[fi.Name()] {
  145. os.Chtimes(filepath.Join(testDir, fi.Name()), now, now) // best-effort
  146. continue
  147. }
  148. if now.Sub(fi.ModTime()) < purgeTimeout {
  149. continue
  150. }
  151. fmt.Printf("delete %v\n", fi.Name())
  152. os.RemoveAll(filepath.Join(testDir, fi.Name())) // best-effort
  153. }
  154. }()
  155. // The bin directory contains symlinks to each tool by version.
  156. // It is safe to delete this directory and run the test script from scratch.
  157. binPath := filepath.Join(testDir, "bin")
  158. check(os.RemoveAll(binPath))
  159. check(os.Mkdir(binPath, 0775))
  160. check(os.Setenv("PATH", binPath+":"+os.Getenv("PATH")))
  161. registerBinary := func(name, path string) {
  162. check(os.Symlink(path, filepath.Join(binPath, name)))
  163. }
  164. // Download and build the protobuf toolchain.
  165. // We avoid downloading the pre-compiled binaries since they do not contain
  166. // the conformance test runner.
  167. workingDir = filepath.Join(testDir, "protobuf-"+protobufVersion)
  168. if _, err := os.Stat(workingDir); err != nil {
  169. fmt.Printf("download %v\n", filepath.Base(workingDir))
  170. url := fmt.Sprintf("https://github.com/google/protobuf/releases/download/v%v/protobuf-all-%v.tar.gz", protobufVersion, protobufVersion)
  171. downloadArchive(check, workingDir, url, "protobuf-"+protobufVersion)
  172. fmt.Printf("build %v\n", filepath.Base(workingDir))
  173. mustRunCommand(t, workingDir, "./autogen.sh")
  174. mustRunCommand(t, workingDir, "./configure")
  175. mustRunCommand(t, workingDir, "make")
  176. mustRunCommand(t, filepath.Join(workingDir, "conformance"), "make")
  177. }
  178. patchProtos(check, workingDir)
  179. check(os.Setenv("PROTOBUF_ROOT", workingDir)) // for generate-protos
  180. registerBinary("conform-test-runner", filepath.Join(workingDir, "conformance", "conformance-test-runner"))
  181. registerBinary("protoc", filepath.Join(workingDir, "src", "protoc"))
  182. workingDir = ""
  183. // Download each Go toolchain version.
  184. for _, v := range golangVersions {
  185. workingDir = filepath.Join(testDir, "go"+v)
  186. if _, err := os.Stat(workingDir); err != nil {
  187. fmt.Printf("download %v\n", filepath.Base(workingDir))
  188. url := fmt.Sprintf("https://dl.google.com/go/go%v.%v-%v.tar.gz", v, runtime.GOOS, runtime.GOARCH)
  189. downloadArchive(check, workingDir, url, "go")
  190. }
  191. registerBinary("go"+v, filepath.Join(workingDir, "bin", "go"))
  192. }
  193. registerBinary("go", filepath.Join(testDir, "go"+golangLatest, "bin", "go"))
  194. registerBinary("gofmt", filepath.Join(testDir, "go"+golangLatest, "bin", "gofmt"))
  195. workingDir = ""
  196. // Travis-CI sets GOROOT, which confuses invocations of the Go toolchain.
  197. // Explicitly clear GOROOT, so each toolchain uses their default GOROOT.
  198. check(os.Unsetenv("GOROOT"))
  199. // Set a cache directory within the test directory.
  200. check(os.Setenv("GOCACHE", filepath.Join(testDir, "gocache")))
  201. // Setup GOPATH for pre-module support (i.e., go1.10 and earlier).
  202. goPath = filepath.Join(testDir, "gopath")
  203. modulePath = strings.TrimSpace(mustRunCommand(t, testDir, "go", "list", "-m", "-f", "{{.Path}}"))
  204. check(os.RemoveAll(filepath.Join(goPath, "src")))
  205. check(os.MkdirAll(filepath.Join(goPath, "src", filepath.Dir(modulePath)), 0775))
  206. check(os.Symlink(repoRoot, filepath.Join(goPath, "src", modulePath)))
  207. mustRunCommand(t, repoRoot, "go", "mod", "tidy")
  208. mustRunCommand(t, repoRoot, "go", "mod", "vendor")
  209. check(os.Setenv("GOPATH", goPath))
  210. }
  211. func downloadArchive(check func(error), dstPath, srcURL, skipPrefix string) {
  212. check(os.RemoveAll(dstPath))
  213. resp, err := http.Get(srcURL)
  214. check(err)
  215. defer resp.Body.Close()
  216. zr, err := gzip.NewReader(resp.Body)
  217. check(err)
  218. tr := tar.NewReader(zr)
  219. for {
  220. h, err := tr.Next()
  221. if err == io.EOF {
  222. return
  223. }
  224. check(err)
  225. // Skip directories or files outside the prefix directory.
  226. if len(skipPrefix) > 0 {
  227. if !strings.HasPrefix(h.Name, skipPrefix) {
  228. continue
  229. }
  230. if len(h.Name) > len(skipPrefix) && h.Name[len(skipPrefix)] != '/' {
  231. continue
  232. }
  233. }
  234. path := strings.TrimPrefix(strings.TrimPrefix(h.Name, skipPrefix), "/")
  235. path = filepath.Join(dstPath, filepath.FromSlash(path))
  236. mode := os.FileMode(h.Mode & 0777)
  237. switch h.Typeflag {
  238. case tar.TypeReg:
  239. b, err := ioutil.ReadAll(tr)
  240. check(err)
  241. check(ioutil.WriteFile(path, b, mode))
  242. case tar.TypeDir:
  243. check(os.Mkdir(path, mode))
  244. }
  245. }
  246. }
  247. // patchProtos patches proto files with v2 locations of Go packages.
  248. // TODO: Commit these changes upstream.
  249. func patchProtos(check func(error), repoRoot string) {
  250. javaPackageRx := regexp.MustCompile(`^option\s+java_package\s*=\s*".*"\s*;\s*$`)
  251. goPackageRx := regexp.MustCompile(`^option\s+go_package\s*=\s*".*"\s*;\s*$`)
  252. files := map[string]string{
  253. "src/google/protobuf/any.proto": "github.com/golang/protobuf/v2/types/known;known_proto",
  254. "src/google/protobuf/api.proto": "github.com/golang/protobuf/v2/types/known;known_proto",
  255. "src/google/protobuf/duration.proto": "github.com/golang/protobuf/v2/types/known;known_proto",
  256. "src/google/protobuf/empty.proto": "github.com/golang/protobuf/v2/types/known;known_proto",
  257. "src/google/protobuf/field_mask.proto": "github.com/golang/protobuf/v2/types/known;known_proto",
  258. "src/google/protobuf/source_context.proto": "github.com/golang/protobuf/v2/types/known;known_proto",
  259. "src/google/protobuf/struct.proto": "github.com/golang/protobuf/v2/types/known;known_proto",
  260. "src/google/protobuf/timestamp.proto": "github.com/golang/protobuf/v2/types/known;known_proto",
  261. "src/google/protobuf/type.proto": "github.com/golang/protobuf/v2/types/known;known_proto",
  262. "src/google/protobuf/wrappers.proto": "github.com/golang/protobuf/v2/types/known;known_proto",
  263. "src/google/protobuf/descriptor.proto": "github.com/golang/protobuf/v2/types/descriptor;descriptor_proto",
  264. "src/google/protobuf/compiler/plugin.proto": "github.com/golang/protobuf/v2/types/plugin;plugin_proto",
  265. "conformance/conformance.proto": "github.com/golang/protobuf/v2/internal/testprotos/conformance;conformance_proto",
  266. }
  267. for pbpath, gopath := range files {
  268. b, err := ioutil.ReadFile(filepath.Join(repoRoot, pbpath))
  269. check(err)
  270. ss := strings.Split(string(b), "\n")
  271. // Locate java_package and (possible) go_package options.
  272. javaPackageIdx, goPackageIdx := -1, -1
  273. for i, s := range ss {
  274. if javaPackageIdx < 0 && javaPackageRx.MatchString(s) {
  275. javaPackageIdx = i
  276. }
  277. if goPackageIdx < 0 && goPackageRx.MatchString(s) {
  278. goPackageIdx = i
  279. }
  280. }
  281. // Ensure the proto file has the correct go_package option.
  282. opt := `option go_package = "` + gopath + `";`
  283. if goPackageIdx >= 0 {
  284. if ss[goPackageIdx] == opt {
  285. continue // no changes needed
  286. }
  287. ss[goPackageIdx] = opt
  288. } else {
  289. // Insert go_package option before java_package option.
  290. ss = append(ss[:javaPackageIdx], append([]string{opt}, ss[javaPackageIdx:]...)...)
  291. }
  292. fmt.Println("patch " + pbpath)
  293. b = []byte(strings.Join(ss, "\n"))
  294. check(ioutil.WriteFile(filepath.Join(repoRoot, pbpath), b, 0664))
  295. }
  296. }
  297. func mustRunCommand(t *testing.T, dir string, args ...string) string {
  298. t.Helper()
  299. stdout := new(bytes.Buffer)
  300. stderr := new(bytes.Buffer)
  301. cmd := exec.Command(args[0], args[1:]...)
  302. cmd.Dir = dir
  303. cmd.Env = append(os.Environ(), "PWD="+dir)
  304. cmd.Stdout = stdout
  305. cmd.Stderr = stderr
  306. if err := cmd.Run(); err != nil {
  307. t.Fatalf("executing (%v): %v\n%s%s", strings.Join(args, " "), err, stdout.String(), stderr.String())
  308. }
  309. return stdout.String()
  310. }