integration_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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"
  18. "path/filepath"
  19. "regexp"
  20. "runtime"
  21. "strings"
  22. "sync"
  23. "testing"
  24. "time"
  25. )
  26. var (
  27. regenerate = flag.Bool("regenerate", false, "regenerate files")
  28. protobufVersion = "3.7.1"
  29. golangVersions = []string{"1.9.7", "1.10.8", "1.11.6", "1.12.1"}
  30. golangLatest = golangVersions[len(golangVersions)-1]
  31. // purgeTimeout determines the maximum age of unused sub-directories.
  32. purgeTimeout = 30 * 24 * time.Hour // 1 month
  33. // Variables initialized by mustInitDeps.
  34. goPath string
  35. modulePath string
  36. protobufPath string
  37. )
  38. func Test(t *testing.T) {
  39. mustInitDeps(t)
  40. if *regenerate {
  41. t.Run("Generate", func(t *testing.T) {
  42. fmt.Print(mustRunCommand(t, ".", "go", "run", "./internal/cmd/generate-types", "-execute"))
  43. fmt.Print(mustRunCommand(t, ".", "go", "run", "./internal/cmd/generate-protos", "-execute"))
  44. files := strings.Split(strings.TrimSpace(mustRunCommand(t, ".", "git", "ls-files", "*.go")), "\n")
  45. mustRunCommand(t, ".", append([]string{"gofmt", "-w"}, files...)...)
  46. })
  47. t.SkipNow()
  48. }
  49. var wg sync.WaitGroup
  50. sema := make(chan bool, (runtime.NumCPU()+1)/2)
  51. for i := range golangVersions {
  52. goVersion := golangVersions[i]
  53. goLabel := "Go" + goVersion
  54. runGo := func(label, workDir string, args ...string) {
  55. wg.Add(1)
  56. sema <- true
  57. go func() {
  58. defer wg.Done()
  59. defer func() { <-sema }()
  60. t.Run(goLabel+"/"+label, func(t *testing.T) {
  61. args[0] += goVersion
  62. mustRunCommand(t, workDir, args...)
  63. })
  64. }()
  65. }
  66. workDir := filepath.Join(goPath, "src", modulePath)
  67. runGo("Normal", workDir, "go", "test", "-race", "./...")
  68. runGo("PureGo", workDir, "go", "test", "-race", "-tags", "purego", "./...")
  69. runGo("Reflect", workDir, "go", "test", "-race", "-tags", "protoreflect", "./...")
  70. if goVersion == golangLatest {
  71. runGo("Proto1Legacy", workDir, "go", "test", "-race", "-tags", "proto1_legacy", "./...")
  72. runGo("ProtocGenGo", "cmd/protoc-gen-go/testdata", "go", "test")
  73. runGo("ProtocGenGoGRPC", "cmd/protoc-gen-go-grpc/testdata", "go", "test")
  74. }
  75. }
  76. wg.Wait()
  77. t.Run("ConformanceTests", func(t *testing.T) {
  78. driverPath := filepath.Join("internal", "cmd", "conformance")
  79. driver := filepath.Join(driverPath, "conformance.sh")
  80. failureList := filepath.Join(driverPath, "failure_list_go.txt")
  81. runner := filepath.Join(protobufPath, "conformance", "conformance-test-runner")
  82. mustRunCommand(t, ".", runner, "--failure_list", failureList, "--enforce_recommended", driver)
  83. })
  84. t.Run("GeneratedGoFiles", func(t *testing.T) {
  85. diff := mustRunCommand(t, ".", "go", "run", "./internal/cmd/generate-types")
  86. if strings.TrimSpace(diff) != "" {
  87. t.Fatalf("stale generated files:\n%v", diff)
  88. }
  89. diff = mustRunCommand(t, ".", "go", "run", "./internal/cmd/generate-protos")
  90. if strings.TrimSpace(diff) != "" {
  91. t.Fatalf("stale generated files:\n%v", diff)
  92. }
  93. })
  94. t.Run("FormattedGoFiles", func(t *testing.T) {
  95. files := strings.Split(strings.TrimSpace(mustRunCommand(t, ".", "git", "ls-files", "*.go")), "\n")
  96. diff := mustRunCommand(t, ".", append([]string{"gofmt", "-d"}, files...)...)
  97. if strings.TrimSpace(diff) != "" {
  98. t.Fatalf("unformatted source files:\n%v", diff)
  99. }
  100. })
  101. t.Run("CommittedGitChanges", func(t *testing.T) {
  102. diff := mustRunCommand(t, ".", "git", "diff", "--no-prefix", "HEAD")
  103. if strings.TrimSpace(diff) != "" {
  104. t.Fatalf("uncommitted changes:\n%v", diff)
  105. }
  106. })
  107. t.Run("TrackedGitFiles", func(t *testing.T) {
  108. diff := mustRunCommand(t, ".", "git", "ls-files", "--others", "--exclude-standard")
  109. if strings.TrimSpace(diff) != "" {
  110. t.Fatalf("untracked files:\n%v", diff)
  111. }
  112. })
  113. }
  114. func mustInitDeps(t *testing.T) {
  115. check := func(err error) {
  116. t.Helper()
  117. if err != nil {
  118. t.Fatal(err)
  119. }
  120. }
  121. // Determine the directory to place the test directory.
  122. repoRoot, err := os.Getwd()
  123. check(err)
  124. testDir := filepath.Join(repoRoot, ".cache")
  125. check(os.MkdirAll(testDir, 0775))
  126. // Travis-CI has a hard-coded timeout where it kills the test after
  127. // 10 minutes of a lack of activity on stdout.
  128. // We work around this restriction by periodically printing the timestamp.
  129. ticker := time.NewTicker(5 * time.Minute)
  130. done := make(chan struct{})
  131. go func() {
  132. now := time.Now()
  133. for {
  134. select {
  135. case t := <-ticker.C:
  136. fmt.Printf("\tt=%0.fmin\n", t.Sub(now).Minutes())
  137. case <-done:
  138. return
  139. }
  140. }
  141. }()
  142. defer close(done)
  143. defer ticker.Stop()
  144. // Delete the current directory if non-empty,
  145. // which only occurs if a dependency failed to initialize properly.
  146. var workingDir string
  147. defer func() {
  148. if workingDir != "" {
  149. os.RemoveAll(workingDir) // best-effort
  150. }
  151. }()
  152. // Delete other sub-directories that are no longer relevant.
  153. defer func() {
  154. subDirs := map[string]bool{"bin": true, "gocache": true, "gopath": true}
  155. subDirs["protobuf-"+protobufVersion] = true
  156. for _, v := range golangVersions {
  157. subDirs["go"+v] = true
  158. }
  159. now := time.Now()
  160. fis, _ := ioutil.ReadDir(testDir)
  161. for _, fi := range fis {
  162. if subDirs[fi.Name()] {
  163. os.Chtimes(filepath.Join(testDir, fi.Name()), now, now) // best-effort
  164. continue
  165. }
  166. if now.Sub(fi.ModTime()) < purgeTimeout {
  167. continue
  168. }
  169. fmt.Printf("delete %v\n", fi.Name())
  170. os.RemoveAll(filepath.Join(testDir, fi.Name())) // best-effort
  171. }
  172. }()
  173. // The bin directory contains symlinks to each tool by version.
  174. // It is safe to delete this directory and run the test script from scratch.
  175. binPath := filepath.Join(testDir, "bin")
  176. check(os.RemoveAll(binPath))
  177. check(os.Mkdir(binPath, 0775))
  178. check(os.Setenv("PATH", binPath+":"+os.Getenv("PATH")))
  179. registerBinary := func(name, path string) {
  180. check(os.Symlink(path, filepath.Join(binPath, name)))
  181. }
  182. // Download and build the protobuf toolchain.
  183. // We avoid downloading the pre-compiled binaries since they do not contain
  184. // the conformance test runner.
  185. workingDir = filepath.Join(testDir, "protobuf-"+protobufVersion)
  186. protobufPath = workingDir
  187. if _, err := os.Stat(protobufPath); err != nil {
  188. fmt.Printf("download %v\n", filepath.Base(protobufPath))
  189. url := fmt.Sprintf("https://github.com/google/protobuf/releases/download/v%v/protobuf-all-%v.tar.gz", protobufVersion, protobufVersion)
  190. downloadArchive(check, protobufPath, url, "protobuf-"+protobufVersion)
  191. fmt.Printf("build %v\n", filepath.Base(protobufPath))
  192. mustRunCommand(t, protobufPath, "./autogen.sh")
  193. mustRunCommand(t, protobufPath, "./configure")
  194. mustRunCommand(t, protobufPath, "make")
  195. mustRunCommand(t, filepath.Join(protobufPath, "conformance"), "make")
  196. }
  197. // The benchmark directory isn't present in the release download,
  198. // so fetch needed files directly.
  199. for _, path := range benchmarkProtos {
  200. src := fmt.Sprintf("https://raw.githubusercontent.com/protocolbuffers/protobuf/v%v/%v", protobufVersion, path)
  201. dst := filepath.Join(protobufPath, path)
  202. if _, err := os.Stat(dst); err != nil {
  203. downloadFile(check, dst, src)
  204. }
  205. }
  206. benchdataPath := filepath.Join(testDir, "benchdata")
  207. for _, path := range []string{
  208. "benchmarks/datasets/google_message1/proto2/dataset.google_message1_proto2.pb",
  209. "benchmarks/datasets/google_message1/proto3/dataset.google_message1_proto3.pb",
  210. "benchmarks/datasets/google_message2/dataset.google_message2.pb",
  211. } {
  212. src := fmt.Sprintf("https://raw.githubusercontent.com/protocolbuffers/protobuf/v%v/%v", protobufVersion, path)
  213. dst := filepath.Join(benchdataPath, filepath.Base(path))
  214. if _, err := os.Stat(dst); err != nil {
  215. downloadFile(check, dst, src)
  216. }
  217. }
  218. patchProtos(check, protobufPath)
  219. check(os.Setenv("PROTOBUF_ROOT", protobufPath)) // for generate-protos
  220. registerBinary("conform-test-runner", filepath.Join(protobufPath, "conformance", "conformance-test-runner"))
  221. registerBinary("protoc", filepath.Join(protobufPath, "src", "protoc"))
  222. workingDir = ""
  223. // Download each Go toolchain version.
  224. for _, v := range golangVersions {
  225. workingDir = filepath.Join(testDir, "go"+v)
  226. if _, err := os.Stat(workingDir); err != nil {
  227. fmt.Printf("download %v\n", filepath.Base(workingDir))
  228. url := fmt.Sprintf("https://dl.google.com/go/go%v.%v-%v.tar.gz", v, runtime.GOOS, runtime.GOARCH)
  229. downloadArchive(check, workingDir, url, "go")
  230. }
  231. registerBinary("go"+v, filepath.Join(workingDir, "bin", "go"))
  232. }
  233. registerBinary("go", filepath.Join(testDir, "go"+golangLatest, "bin", "go"))
  234. registerBinary("gofmt", filepath.Join(testDir, "go"+golangLatest, "bin", "gofmt"))
  235. workingDir = ""
  236. // Travis-CI sets GOROOT, which confuses invocations of the Go toolchain.
  237. // Explicitly clear GOROOT, so each toolchain uses their default GOROOT.
  238. check(os.Unsetenv("GOROOT"))
  239. // Set a cache directory outside the test directory.
  240. check(os.Setenv("GOCACHE", filepath.Join(repoRoot, ".gocache")))
  241. // Setup GOPATH for pre-module support (i.e., go1.10 and earlier).
  242. goPath = filepath.Join(testDir, "gopath")
  243. modulePath = strings.TrimSpace(mustRunCommand(t, testDir, "go", "list", "-m", "-f", "{{.Path}}"))
  244. check(os.RemoveAll(filepath.Join(goPath, "src")))
  245. check(os.MkdirAll(filepath.Join(goPath, "src", filepath.Dir(modulePath)), 0775))
  246. check(os.Symlink(repoRoot, filepath.Join(goPath, "src", modulePath)))
  247. mustRunCommand(t, repoRoot, "go", "mod", "tidy")
  248. mustRunCommand(t, repoRoot, "go", "mod", "vendor")
  249. check(os.Setenv("GOPATH", goPath))
  250. }
  251. func downloadFile(check func(error), dstPath, srcURL string) {
  252. resp, err := http.Get(srcURL)
  253. check(err)
  254. defer resp.Body.Close()
  255. check(os.MkdirAll(filepath.Dir(dstPath), 0775))
  256. f, err := os.Create(dstPath)
  257. check(err)
  258. _, err = io.Copy(f, resp.Body)
  259. check(err)
  260. }
  261. func downloadArchive(check func(error), dstPath, srcURL, skipPrefix string) {
  262. check(os.RemoveAll(dstPath))
  263. resp, err := http.Get(srcURL)
  264. check(err)
  265. defer resp.Body.Close()
  266. zr, err := gzip.NewReader(resp.Body)
  267. check(err)
  268. tr := tar.NewReader(zr)
  269. for {
  270. h, err := tr.Next()
  271. if err == io.EOF {
  272. return
  273. }
  274. check(err)
  275. // Skip directories or files outside the prefix directory.
  276. if len(skipPrefix) > 0 {
  277. if !strings.HasPrefix(h.Name, skipPrefix) {
  278. continue
  279. }
  280. if len(h.Name) > len(skipPrefix) && h.Name[len(skipPrefix)] != '/' {
  281. continue
  282. }
  283. }
  284. path := strings.TrimPrefix(strings.TrimPrefix(h.Name, skipPrefix), "/")
  285. path = filepath.Join(dstPath, filepath.FromSlash(path))
  286. mode := os.FileMode(h.Mode & 0777)
  287. switch h.Typeflag {
  288. case tar.TypeReg:
  289. b, err := ioutil.ReadAll(tr)
  290. check(err)
  291. check(ioutil.WriteFile(path, b, mode))
  292. case tar.TypeDir:
  293. check(os.Mkdir(path, mode))
  294. }
  295. }
  296. }
  297. // patchProtos patches proto files with v2 locations of Go packages.
  298. // TODO: Commit these changes upstream.
  299. func patchProtos(check func(error), repoRoot string) {
  300. javaPackageRx := regexp.MustCompile(`^option\s+java_package\s*=\s*".*"\s*;\s*$`)
  301. goPackageRx := regexp.MustCompile(`^option\s+go_package\s*=\s*".*"\s*;\s*$`)
  302. files := map[string]string{
  303. "src/google/protobuf/any.proto": "google.golang.org/protobuf/types/known/anypb",
  304. "src/google/protobuf/api.proto": "google.golang.org/protobuf/types/known/apipb",
  305. "src/google/protobuf/duration.proto": "google.golang.org/protobuf/types/known/durationpb",
  306. "src/google/protobuf/empty.proto": "google.golang.org/protobuf/types/known/emptypb",
  307. "src/google/protobuf/field_mask.proto": "google.golang.org/protobuf/types/known/fieldmaskpb",
  308. "src/google/protobuf/source_context.proto": "google.golang.org/protobuf/types/known/sourcecontextpb",
  309. "src/google/protobuf/struct.proto": "google.golang.org/protobuf/types/known/structpb",
  310. "src/google/protobuf/timestamp.proto": "google.golang.org/protobuf/types/known/timestamppb",
  311. "src/google/protobuf/type.proto": "google.golang.org/protobuf/types/known/typepb",
  312. "src/google/protobuf/wrappers.proto": "google.golang.org/protobuf/types/known/wrapperspb",
  313. "src/google/protobuf/descriptor.proto": "google.golang.org/protobuf/types/descriptorpb",
  314. "src/google/protobuf/compiler/plugin.proto": "google.golang.org/protobuf/types/pluginpb",
  315. "conformance/conformance.proto": "google.golang.org/protobuf/internal/testprotos/conformance",
  316. "src/google/protobuf/test_messages_proto2.proto": "google.golang.org/protobuf/internal/testprotos/conformance",
  317. "src/google/protobuf/test_messages_proto3.proto": "google.golang.org/protobuf/internal/testprotos/conformance",
  318. }
  319. for _, p := range benchmarkProtos {
  320. files[p] = path.Dir("google.golang.org/protobuf/internal/testprotos/" + p)
  321. }
  322. for pbpath, gopath := range files {
  323. b, err := ioutil.ReadFile(filepath.Join(repoRoot, pbpath))
  324. check(err)
  325. ss := strings.Split(string(b), "\n")
  326. // Locate java_package and (possible) go_package options.
  327. javaPackageIdx, goPackageIdx := -1, -1
  328. for i, s := range ss {
  329. if javaPackageIdx < 0 && javaPackageRx.MatchString(s) {
  330. javaPackageIdx = i
  331. }
  332. if goPackageIdx < 0 && goPackageRx.MatchString(s) {
  333. goPackageIdx = i
  334. }
  335. }
  336. // Ensure the proto file has the correct go_package option.
  337. opt := `option go_package = "` + gopath + `";`
  338. if goPackageIdx >= 0 {
  339. if ss[goPackageIdx] == opt {
  340. continue // no changes needed
  341. }
  342. ss[goPackageIdx] = opt
  343. } else {
  344. // Insert go_package option before java_package option.
  345. ss = append(ss[:javaPackageIdx], append([]string{opt}, ss[javaPackageIdx:]...)...)
  346. }
  347. fmt.Println("patch " + pbpath)
  348. b = []byte(strings.Join(ss, "\n"))
  349. check(ioutil.WriteFile(filepath.Join(repoRoot, pbpath), b, 0664))
  350. }
  351. }
  352. func mustRunCommand(t *testing.T, dir string, args ...string) string {
  353. t.Helper()
  354. stdout := new(bytes.Buffer)
  355. stderr := new(bytes.Buffer)
  356. cmd := exec.Command(args[0], args[1:]...)
  357. cmd.Dir = dir
  358. cmd.Env = append(os.Environ(), "PWD="+dir)
  359. cmd.Stdout = stdout
  360. cmd.Stderr = stderr
  361. if err := cmd.Run(); err != nil {
  362. t.Fatalf("executing (%v): %v\n%s%s", strings.Join(args, " "), err, stdout.String(), stderr.String())
  363. }
  364. return stdout.String()
  365. }
  366. var benchmarkProtos = []string{
  367. "benchmarks/benchmarks.proto",
  368. "benchmarks/datasets/google_message1/proto2/benchmark_message1_proto2.proto",
  369. "benchmarks/datasets/google_message1/proto3/benchmark_message1_proto3.proto",
  370. "benchmarks/datasets/google_message2/benchmark_message2.proto",
  371. "benchmarks/datasets/google_message3/benchmark_message3.proto",
  372. "benchmarks/datasets/google_message3/benchmark_message3_1.proto",
  373. "benchmarks/datasets/google_message3/benchmark_message3_2.proto",
  374. "benchmarks/datasets/google_message3/benchmark_message3_3.proto",
  375. "benchmarks/datasets/google_message3/benchmark_message3_4.proto",
  376. "benchmarks/datasets/google_message3/benchmark_message3_5.proto",
  377. "benchmarks/datasets/google_message3/benchmark_message3_6.proto",
  378. "benchmarks/datasets/google_message3/benchmark_message3_7.proto",
  379. "benchmarks/datasets/google_message3/benchmark_message3_8.proto",
  380. "benchmarks/datasets/google_message4/benchmark_message4.proto",
  381. "benchmarks/datasets/google_message4/benchmark_message4_1.proto",
  382. "benchmarks/datasets/google_message4/benchmark_message4_2.proto",
  383. "benchmarks/datasets/google_message4/benchmark_message4_3.proto",
  384. }