integration_test.go 13 KB

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