integration_test.go 15 KB

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