integration_test.go 11 KB

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