blob: 1afd13b643a5a048fd3e034388c8237b5fe8948c [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"
20 "path/filepath"
Joe Tsai707894e2019-03-01 12:50:52 -080021 "runtime"
22 "strings"
Joe Tsai62200db2019-07-11 17:34:10 -070023 "sync"
Joe Tsai707894e2019-03-01 12:50:52 -080024 "testing"
Joe Tsaif3987842019-03-02 13:35:17 -080025 "time"
Joe Tsai4f3de442019-08-07 19:33:51 -070026
27 "google.golang.org/protobuf/runtime/protoimpl"
Joe Tsai707894e2019-03-01 12:50:52 -080028)
29
30var (
Joe Tsai4f3de442019-08-07 19:33:51 -070031 regenerate = flag.Bool("regenerate", false, "regenerate files")
32 buildRelease = flag.Bool("buildRelease", false, "build release binaries")
Joe Tsai707894e2019-03-01 12:50:52 -080033
Joe Tsaiabd06a82019-08-16 00:39:27 -070034 protobufVersion = "3.9.1"
Herbie Ong39246252019-09-06 11:20:30 -070035 golangVersions = []string{"1.9.7", "1.10.8", "1.11.13", "1.12.9", "1.13"}
Joe Tsai707894e2019-03-01 12:50:52 -080036 golangLatest = golangVersions[len(golangVersions)-1]
37
Joe Tsai9e88bc02019-03-12 01:30:40 -070038 // purgeTimeout determines the maximum age of unused sub-directories.
39 purgeTimeout = 30 * 24 * time.Hour // 1 month
Joe Tsai707894e2019-03-01 12:50:52 -080040
41 // Variables initialized by mustInitDeps.
Herbie Ongd64dceb2019-04-25 01:19:57 -070042 goPath string
43 modulePath string
44 protobufPath string
Joe Tsai707894e2019-03-01 12:50:52 -080045)
46
47func Test(t *testing.T) {
48 mustInitDeps(t)
Joe Tsai4f3de442019-08-07 19:33:51 -070049 mustHandleFlags(t)
Joe Tsai707894e2019-03-01 12:50:52 -080050
Joe Tsai62200db2019-07-11 17:34:10 -070051 var wg sync.WaitGroup
52 sema := make(chan bool, (runtime.NumCPU()+1)/2)
53 for i := range golangVersions {
54 goVersion := golangVersions[i]
55 goLabel := "Go" + goVersion
56 runGo := func(label, workDir string, args ...string) {
57 wg.Add(1)
58 sema <- true
59 go func() {
60 defer wg.Done()
61 defer func() { <-sema }()
62 t.Run(goLabel+"/"+label, func(t *testing.T) {
63 args[0] += goVersion
Joe Tsai7164af52019-08-07 19:27:43 -070064 command{Dir: workDir}.mustRun(t, args...)
Joe Tsai707894e2019-03-01 12:50:52 -080065 })
Joe Tsai62200db2019-07-11 17:34:10 -070066 }()
67 }
68
69 workDir := filepath.Join(goPath, "src", modulePath)
70 runGo("Normal", workDir, "go", "test", "-race", "./...")
71 runGo("PureGo", workDir, "go", "test", "-race", "-tags", "purego", "./...")
72 runGo("Reflect", workDir, "go", "test", "-race", "-tags", "protoreflect", "./...")
73 if goVersion == golangLatest {
Joe Tsai1799d112019-08-08 13:31:59 -070074 runGo("ProtoLegacy", workDir, "go", "test", "-race", "-tags", "protolegacy", "./...")
Joe Tsai62200db2019-07-11 17:34:10 -070075 runGo("ProtocGenGo", "cmd/protoc-gen-go/testdata", "go", "test")
Joe Tsaidd271b62019-08-16 01:09:33 -070076 runGo("Conformance", "internal/conformance", "go", "test", "-execute")
Joe Tsai62200db2019-07-11 17:34:10 -070077 }
Joe Tsai707894e2019-03-01 12:50:52 -080078 }
Joe Tsai62200db2019-07-11 17:34:10 -070079 wg.Wait()
Joe Tsai707894e2019-03-01 12:50:52 -080080
81 t.Run("GeneratedGoFiles", func(t *testing.T) {
Joe Tsai1799d112019-08-08 13:31:59 -070082 diff := mustRunCommand(t, "go", "run", "-tags", "protolegacy", "./internal/cmd/generate-types")
Joe Tsai707894e2019-03-01 12:50:52 -080083 if strings.TrimSpace(diff) != "" {
84 t.Fatalf("stale generated files:\n%v", diff)
85 }
Joe Tsai1799d112019-08-08 13:31:59 -070086 diff = mustRunCommand(t, "go", "run", "-tags", "protolegacy", "./internal/cmd/generate-protos")
Joe Tsai707894e2019-03-01 12:50:52 -080087 if strings.TrimSpace(diff) != "" {
88 t.Fatalf("stale generated files:\n%v", diff)
89 }
90 })
91 t.Run("FormattedGoFiles", func(t *testing.T) {
Joe Tsai7164af52019-08-07 19:27:43 -070092 files := strings.Split(strings.TrimSpace(mustRunCommand(t, "git", "ls-files", "*.go")), "\n")
93 diff := mustRunCommand(t, append([]string{"gofmt", "-d"}, files...)...)
Joe Tsai707894e2019-03-01 12:50:52 -080094 if strings.TrimSpace(diff) != "" {
95 t.Fatalf("unformatted source files:\n%v", diff)
96 }
97 })
98 t.Run("CommittedGitChanges", func(t *testing.T) {
Joe Tsai7164af52019-08-07 19:27:43 -070099 diff := mustRunCommand(t, "git", "diff", "--no-prefix", "HEAD")
Joe Tsai707894e2019-03-01 12:50:52 -0800100 if strings.TrimSpace(diff) != "" {
101 t.Fatalf("uncommitted changes:\n%v", diff)
102 }
103 })
104 t.Run("TrackedGitFiles", func(t *testing.T) {
Joe Tsai7164af52019-08-07 19:27:43 -0700105 diff := mustRunCommand(t, "git", "ls-files", "--others", "--exclude-standard")
Joe Tsai707894e2019-03-01 12:50:52 -0800106 if strings.TrimSpace(diff) != "" {
107 t.Fatalf("untracked files:\n%v", diff)
108 }
109 })
110}
111
112func mustInitDeps(t *testing.T) {
113 check := func(err error) {
114 t.Helper()
115 if err != nil {
116 t.Fatal(err)
117 }
118 }
119
120 // Determine the directory to place the test directory.
121 repoRoot, err := os.Getwd()
122 check(err)
123 testDir := filepath.Join(repoRoot, ".cache")
124 check(os.MkdirAll(testDir, 0775))
125
Joe Tsaif3987842019-03-02 13:35:17 -0800126 // 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
Joe Tsai707894e2019-03-01 12:50:52 -0800145 // Delete the current directory if non-empty,
146 // which only occurs if a dependency failed to initialize properly.
147 var workingDir string
148 defer func() {
149 if workingDir != "" {
150 os.RemoveAll(workingDir) // best-effort
151 }
152 }()
153
154 // Delete other sub-directories that are no longer relevant.
155 defer func() {
156 subDirs := map[string]bool{"bin": true, "gocache": true, "gopath": true}
157 subDirs["protobuf-"+protobufVersion] = true
158 for _, v := range golangVersions {
159 subDirs["go"+v] = true
160 }
Joe Tsai707894e2019-03-01 12:50:52 -0800161
Joe Tsai9e88bc02019-03-12 01:30:40 -0700162 now := time.Now()
Joe Tsai707894e2019-03-01 12:50:52 -0800163 fis, _ := ioutil.ReadDir(testDir)
164 for _, fi := range fis {
Joe Tsai9e88bc02019-03-12 01:30:40 -0700165 if subDirs[fi.Name()] {
166 os.Chtimes(filepath.Join(testDir, fi.Name()), now, now) // best-effort
167 continue
Joe Tsai707894e2019-03-01 12:50:52 -0800168 }
Joe Tsai9e88bc02019-03-12 01:30:40 -0700169 if now.Sub(fi.ModTime()) < purgeTimeout {
170 continue
171 }
172 fmt.Printf("delete %v\n", fi.Name())
173 os.RemoveAll(filepath.Join(testDir, fi.Name())) // best-effort
Joe Tsai707894e2019-03-01 12:50:52 -0800174 }
175 }()
176
177 // The bin directory contains symlinks to each tool by version.
178 // It is safe to delete this directory and run the test script from scratch.
179 binPath := filepath.Join(testDir, "bin")
180 check(os.RemoveAll(binPath))
181 check(os.Mkdir(binPath, 0775))
182 check(os.Setenv("PATH", binPath+":"+os.Getenv("PATH")))
183 registerBinary := func(name, path string) {
184 check(os.Symlink(path, filepath.Join(binPath, name)))
185 }
186
187 // Download and build the protobuf toolchain.
188 // We avoid downloading the pre-compiled binaries since they do not contain
189 // the conformance test runner.
190 workingDir = filepath.Join(testDir, "protobuf-"+protobufVersion)
Herbie Ongd64dceb2019-04-25 01:19:57 -0700191 protobufPath = workingDir
192 if _, err := os.Stat(protobufPath); err != nil {
193 fmt.Printf("download %v\n", filepath.Base(protobufPath))
Joe Tsai707894e2019-03-01 12:50:52 -0800194 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 -0700195 downloadArchive(check, protobufPath, url, "protobuf-"+protobufVersion)
Joe Tsai707894e2019-03-01 12:50:52 -0800196
Herbie Ongd64dceb2019-04-25 01:19:57 -0700197 fmt.Printf("build %v\n", filepath.Base(protobufPath))
Joe Tsai7164af52019-08-07 19:27:43 -0700198 command{Dir: protobufPath}.mustRun(t, "./autogen.sh")
199 command{Dir: protobufPath}.mustRun(t, "./configure")
200 command{Dir: protobufPath}.mustRun(t, "make")
201 command{Dir: filepath.Join(protobufPath, "conformance")}.mustRun(t, "make")
Joe Tsai707894e2019-03-01 12:50:52 -0800202 }
Damien Neila80229e2019-06-20 12:53:48 -0700203 // The benchmark directory isn't present in the release download,
204 // so fetch needed files directly.
205 for _, path := range benchmarkProtos {
206 src := fmt.Sprintf("https://raw.githubusercontent.com/protocolbuffers/protobuf/v%v/%v", protobufVersion, path)
207 dst := filepath.Join(protobufPath, path)
208 if _, err := os.Stat(dst); err != nil {
209 downloadFile(check, dst, src)
210 }
211 }
212 benchdataPath := filepath.Join(testDir, "benchdata")
213 for _, path := range []string{
214 "benchmarks/datasets/google_message1/proto2/dataset.google_message1_proto2.pb",
215 "benchmarks/datasets/google_message1/proto3/dataset.google_message1_proto3.pb",
216 "benchmarks/datasets/google_message2/dataset.google_message2.pb",
217 } {
218 src := fmt.Sprintf("https://raw.githubusercontent.com/protocolbuffers/protobuf/v%v/%v", protobufVersion, path)
219 dst := filepath.Join(benchdataPath, filepath.Base(path))
220 if _, err := os.Stat(dst); err != nil {
221 downloadFile(check, dst, src)
222 }
223 }
Herbie Ongd64dceb2019-04-25 01:19:57 -0700224 check(os.Setenv("PROTOBUF_ROOT", protobufPath)) // for generate-protos
225 registerBinary("conform-test-runner", filepath.Join(protobufPath, "conformance", "conformance-test-runner"))
226 registerBinary("protoc", filepath.Join(protobufPath, "src", "protoc"))
Joe Tsai707894e2019-03-01 12:50:52 -0800227 workingDir = ""
228
229 // Download each Go toolchain version.
230 for _, v := range golangVersions {
231 workingDir = filepath.Join(testDir, "go"+v)
232 if _, err := os.Stat(workingDir); err != nil {
233 fmt.Printf("download %v\n", filepath.Base(workingDir))
234 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 -0800235 downloadArchive(check, workingDir, url, "go")
Joe Tsai707894e2019-03-01 12:50:52 -0800236 }
237 registerBinary("go"+v, filepath.Join(workingDir, "bin", "go"))
238 }
239 registerBinary("go", filepath.Join(testDir, "go"+golangLatest, "bin", "go"))
240 registerBinary("gofmt", filepath.Join(testDir, "go"+golangLatest, "bin", "gofmt"))
241 workingDir = ""
242
243 // Travis-CI sets GOROOT, which confuses invocations of the Go toolchain.
244 // Explicitly clear GOROOT, so each toolchain uses their default GOROOT.
245 check(os.Unsetenv("GOROOT"))
246
Joe Tsai6a2180f2019-07-11 16:34:17 -0700247 // Set a cache directory outside the test directory.
248 check(os.Setenv("GOCACHE", filepath.Join(repoRoot, ".gocache")))
Joe Tsai707894e2019-03-01 12:50:52 -0800249
250 // Setup GOPATH for pre-module support (i.e., go1.10 and earlier).
251 goPath = filepath.Join(testDir, "gopath")
Joe Tsai7164af52019-08-07 19:27:43 -0700252 modulePath = strings.TrimSpace(command{Dir: testDir}.mustRun(t, "go", "list", "-m", "-f", "{{.Path}}"))
Joe Tsai707894e2019-03-01 12:50:52 -0800253 check(os.RemoveAll(filepath.Join(goPath, "src")))
254 check(os.MkdirAll(filepath.Join(goPath, "src", filepath.Dir(modulePath)), 0775))
255 check(os.Symlink(repoRoot, filepath.Join(goPath, "src", modulePath)))
Joe Tsai7164af52019-08-07 19:27:43 -0700256 command{Dir: repoRoot}.mustRun(t, "go", "mod", "tidy")
257 command{Dir: repoRoot}.mustRun(t, "go", "mod", "vendor")
Joe Tsai707894e2019-03-01 12:50:52 -0800258 check(os.Setenv("GOPATH", goPath))
259}
260
Damien Neila80229e2019-06-20 12:53:48 -0700261func downloadFile(check func(error), dstPath, srcURL string) {
262 resp, err := http.Get(srcURL)
263 check(err)
264 defer resp.Body.Close()
265
266 check(os.MkdirAll(filepath.Dir(dstPath), 0775))
267 f, err := os.Create(dstPath)
268 check(err)
269
270 _, err = io.Copy(f, resp.Body)
271 check(err)
272}
273
Joe Tsaif3987842019-03-02 13:35:17 -0800274func downloadArchive(check func(error), dstPath, srcURL, skipPrefix string) {
Joe Tsai707894e2019-03-01 12:50:52 -0800275 check(os.RemoveAll(dstPath))
276
277 resp, err := http.Get(srcURL)
278 check(err)
279 defer resp.Body.Close()
280
281 zr, err := gzip.NewReader(resp.Body)
282 check(err)
283
284 tr := tar.NewReader(zr)
285 for {
286 h, err := tr.Next()
287 if err == io.EOF {
288 return
289 }
290 check(err)
291
Joe Tsaif3987842019-03-02 13:35:17 -0800292 // Skip directories or files outside the prefix directory.
293 if len(skipPrefix) > 0 {
294 if !strings.HasPrefix(h.Name, skipPrefix) {
295 continue
296 }
297 if len(h.Name) > len(skipPrefix) && h.Name[len(skipPrefix)] != '/' {
298 continue
299 }
300 }
301
302 path := strings.TrimPrefix(strings.TrimPrefix(h.Name, skipPrefix), "/")
Joe Tsai707894e2019-03-01 12:50:52 -0800303 path = filepath.Join(dstPath, filepath.FromSlash(path))
304 mode := os.FileMode(h.Mode & 0777)
305 switch h.Typeflag {
306 case tar.TypeReg:
307 b, err := ioutil.ReadAll(tr)
308 check(err)
309 check(ioutil.WriteFile(path, b, mode))
310 case tar.TypeDir:
311 check(os.Mkdir(path, mode))
312 }
313 }
314}
315
Joe Tsai4f3de442019-08-07 19:33:51 -0700316func mustHandleFlags(t *testing.T) {
317 if *regenerate {
318 t.Run("Generate", func(t *testing.T) {
319 fmt.Print(mustRunCommand(t, "go", "run", "-tags", "protolegacy", "./internal/cmd/generate-types", "-execute"))
320 fmt.Print(mustRunCommand(t, "go", "run", "-tags", "protolegacy", "./internal/cmd/generate-protos", "-execute"))
321 files := strings.Split(strings.TrimSpace(mustRunCommand(t, "git", "ls-files", "*.go")), "\n")
322 mustRunCommand(t, append([]string{"gofmt", "-w"}, files...)...)
323 })
324 }
325 if *buildRelease {
326 t.Run("BuildRelease", func(t *testing.T) {
327 v := protoimpl.VersionString()
328 for _, goos := range []string{"linux", "darwin", "windows"} {
329 for _, goarch := range []string{"386", "amd64"} {
330 binPath := filepath.Join("bin", fmt.Sprintf("protoc-gen-go.%v.%v.%v", v, goos, goarch))
331
332 // Build the binary.
333 cmd := command{Env: append(os.Environ(), "GOOS="+goos, "GOARCH="+goarch)}
Joe Tsai576cfb32019-09-04 22:50:42 -0700334 cmd.mustRun(t, "go", "build", "-trimpath", "-ldflags", "-s -w -buildid=", "-o", binPath, "./cmd/protoc-gen-go")
Joe Tsai4f3de442019-08-07 19:33:51 -0700335
336 // Archive and compress the binary.
337 in, err := ioutil.ReadFile(binPath)
338 if err != nil {
339 t.Fatal(err)
340 }
341 out := new(bytes.Buffer)
342 gz, _ := gzip.NewWriterLevel(out, gzip.BestCompression)
343 gz.Comment = fmt.Sprintf("protoc-gen-go VERSION=%v GOOS=%v GOARCH=%v", v, goos, goarch)
344 tw := tar.NewWriter(gz)
345 tw.WriteHeader(&tar.Header{
346 Name: "protoc-gen-go",
347 Mode: int64(0775),
348 Size: int64(len(in)),
349 })
350 tw.Write(in)
351 tw.Close()
352 gz.Close()
353 if err := ioutil.WriteFile(binPath+".tar.gz", out.Bytes(), 0664); err != nil {
354 t.Fatal(err)
355 }
356 }
357 }
358 })
359 }
360 if *regenerate || *buildRelease {
361 t.SkipNow()
362 }
363}
364
Joe Tsai7164af52019-08-07 19:27:43 -0700365type command struct {
366 Dir string
367 Env []string
368}
369
370func (c command) mustRun(t *testing.T, args ...string) string {
Joe Tsai707894e2019-03-01 12:50:52 -0800371 t.Helper()
372 stdout := new(bytes.Buffer)
Herbie Ong4630b3d2019-03-19 16:42:01 -0700373 stderr := new(bytes.Buffer)
Joe Tsai707894e2019-03-01 12:50:52 -0800374 cmd := exec.Command(args[0], args[1:]...)
Joe Tsai7164af52019-08-07 19:27:43 -0700375 cmd.Dir = "."
376 if c.Dir != "" {
377 cmd.Dir = c.Dir
378 }
379 cmd.Env = os.Environ()
380 if c.Env != nil {
381 cmd.Env = c.Env
382 }
383 cmd.Env = append(cmd.Env, "PWD="+cmd.Dir)
Herbie Ong4630b3d2019-03-19 16:42:01 -0700384 cmd.Stdout = stdout
385 cmd.Stderr = stderr
Joe Tsai707894e2019-03-01 12:50:52 -0800386 if err := cmd.Run(); err != nil {
Herbie Ong4630b3d2019-03-19 16:42:01 -0700387 t.Fatalf("executing (%v): %v\n%s%s", strings.Join(args, " "), err, stdout.String(), stderr.String())
Joe Tsai707894e2019-03-01 12:50:52 -0800388 }
389 return stdout.String()
390}
Damien Neila80229e2019-06-20 12:53:48 -0700391
Joe Tsai7164af52019-08-07 19:27:43 -0700392func mustRunCommand(t *testing.T, args ...string) string {
393 t.Helper()
394 return command{}.mustRun(t, args...)
395}
396
Damien Neila80229e2019-06-20 12:53:48 -0700397var benchmarkProtos = []string{
398 "benchmarks/benchmarks.proto",
399 "benchmarks/datasets/google_message1/proto2/benchmark_message1_proto2.proto",
400 "benchmarks/datasets/google_message1/proto3/benchmark_message1_proto3.proto",
401 "benchmarks/datasets/google_message2/benchmark_message2.proto",
402 "benchmarks/datasets/google_message3/benchmark_message3.proto",
403 "benchmarks/datasets/google_message3/benchmark_message3_1.proto",
404 "benchmarks/datasets/google_message3/benchmark_message3_2.proto",
405 "benchmarks/datasets/google_message3/benchmark_message3_3.proto",
406 "benchmarks/datasets/google_message3/benchmark_message3_4.proto",
407 "benchmarks/datasets/google_message3/benchmark_message3_5.proto",
408 "benchmarks/datasets/google_message3/benchmark_message3_6.proto",
409 "benchmarks/datasets/google_message3/benchmark_message3_7.proto",
410 "benchmarks/datasets/google_message3/benchmark_message3_8.proto",
411 "benchmarks/datasets/google_message4/benchmark_message4.proto",
412 "benchmarks/datasets/google_message4/benchmark_message4_1.proto",
413 "benchmarks/datasets/google_message4/benchmark_message4_2.proto",
414 "benchmarks/datasets/google_message4/benchmark_message4_3.proto",
415}