integration_test.go 16 KB

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