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