integration_test.go 12 KB

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