integration_test.go 12 KB

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