blob: a18c1050a992074f82fdab16bec6140e3454c3a8 [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"
21 "regexp"
22 "runtime"
23 "strings"
24 "testing"
Joe Tsaif3987842019-03-02 13:35:17 -080025 "time"
Joe Tsai707894e2019-03-01 12:50:52 -080026)
27
28var (
29 regenerate = flag.Bool("regenerate", false, "regenerate files")
30
Joe Tsai9d19e5c2019-04-03 15:44:11 -070031 protobufVersion = "3.7.1"
32 golangVersions = []string{"1.9.7", "1.10.8", "1.11.6", "1.12.1"}
Joe Tsai707894e2019-03-01 12:50:52 -080033 golangLatest = golangVersions[len(golangVersions)-1]
34
Joe Tsai9e88bc02019-03-12 01:30:40 -070035 // purgeTimeout determines the maximum age of unused sub-directories.
36 purgeTimeout = 30 * 24 * time.Hour // 1 month
Joe Tsai707894e2019-03-01 12:50:52 -080037
38 // Variables initialized by mustInitDeps.
Herbie Ongd64dceb2019-04-25 01:19:57 -070039 goPath string
40 modulePath string
41 protobufPath string
Joe Tsai707894e2019-03-01 12:50:52 -080042)
43
44func Test(t *testing.T) {
45 mustInitDeps(t)
46
47 if *regenerate {
48 t.Run("Generate", func(t *testing.T) {
49 fmt.Print(mustRunCommand(t, ".", "go", "run", "./internal/cmd/generate-types", "-execute"))
50 fmt.Print(mustRunCommand(t, ".", "go", "run", "./internal/cmd/generate-protos", "-execute"))
51 files := strings.Split(strings.TrimSpace(mustRunCommand(t, ".", "git", "ls-files", "*.go")), "\n")
52 mustRunCommand(t, ".", append([]string{"gofmt", "-w"}, files...)...)
53 })
54 t.SkipNow()
55 }
56
57 for _, v := range golangVersions {
58 t.Run("Go"+v, func(t *testing.T) {
Joe Tsaid56458e2019-03-01 18:11:42 -080059 runGo := func(label, workDir string, args ...string) {
Joe Tsai707894e2019-03-01 12:50:52 -080060 args[0] += v
61 t.Run(label, func(t *testing.T) {
62 t.Parallel()
Joe Tsaid56458e2019-03-01 18:11:42 -080063 mustRunCommand(t, workDir, args...)
Joe Tsai707894e2019-03-01 12:50:52 -080064 })
65 }
Joe Tsaid56458e2019-03-01 18:11:42 -080066 workDir := filepath.Join(goPath, "src", modulePath)
Joe Tsaid56458e2019-03-01 18:11:42 -080067 runGo("TestNormal", workDir, "go", "test", "-race", "./...")
68 runGo("TestPureGo", workDir, "go", "test", "-race", "-tags", "purego", "./...")
Damien Neilcc2b0782019-04-05 14:33:10 -070069 runGo("TestReflect", workDir, "go", "test", "-race", "-tags", "protoreflect", "./...")
Joe Tsai707894e2019-03-01 12:50:52 -080070 if v == golangLatest {
Joe Tsaid56458e2019-03-01 18:11:42 -080071 runGo("TestProto1Legacy", workDir, "go", "test", "-race", "-tags", "proto1_legacy", "./...")
72 runGo("TestProtocGenGo", "cmd/protoc-gen-go/testdata", "go", "test")
73 runGo("TestProtocGenGoGRPC", "cmd/protoc-gen-go-grpc/testdata", "go", "test")
Joe Tsai707894e2019-03-01 12:50:52 -080074 }
75 })
76 }
77
Herbie Ongd64dceb2019-04-25 01:19:57 -070078 t.Run("ConformanceTests", func(t *testing.T) {
79 driverPath := filepath.Join("internal", "cmd", "conformance")
80 driver := filepath.Join(driverPath, "conformance.sh")
81 failureList := filepath.Join(driverPath, "failure_list_go.txt")
82 runner := filepath.Join(protobufPath, "conformance", "conformance-test-runner")
83 mustRunCommand(t, ".", runner, "--failure_list", failureList, "--enforce_recommended", driver)
84 })
Joe Tsai707894e2019-03-01 12:50:52 -080085 t.Run("GeneratedGoFiles", func(t *testing.T) {
86 diff := mustRunCommand(t, ".", "go", "run", "./internal/cmd/generate-types")
87 if strings.TrimSpace(diff) != "" {
88 t.Fatalf("stale generated files:\n%v", diff)
89 }
90 diff = mustRunCommand(t, ".", "go", "run", "./internal/cmd/generate-protos")
91 if strings.TrimSpace(diff) != "" {
92 t.Fatalf("stale generated files:\n%v", diff)
93 }
94 })
95 t.Run("FormattedGoFiles", func(t *testing.T) {
96 files := strings.Split(strings.TrimSpace(mustRunCommand(t, ".", "git", "ls-files", "*.go")), "\n")
97 diff := mustRunCommand(t, ".", append([]string{"gofmt", "-d"}, files...)...)
98 if strings.TrimSpace(diff) != "" {
99 t.Fatalf("unformatted source files:\n%v", diff)
100 }
101 })
102 t.Run("CommittedGitChanges", func(t *testing.T) {
103 diff := mustRunCommand(t, ".", "git", "diff", "--no-prefix", "HEAD")
104 if strings.TrimSpace(diff) != "" {
105 t.Fatalf("uncommitted changes:\n%v", diff)
106 }
107 })
108 t.Run("TrackedGitFiles", func(t *testing.T) {
109 diff := mustRunCommand(t, ".", "git", "ls-files", "--others", "--exclude-standard")
110 if strings.TrimSpace(diff) != "" {
111 t.Fatalf("untracked files:\n%v", diff)
112 }
113 })
114}
115
116func mustInitDeps(t *testing.T) {
117 check := func(err error) {
118 t.Helper()
119 if err != nil {
120 t.Fatal(err)
121 }
122 }
123
124 // Determine the directory to place the test directory.
125 repoRoot, err := os.Getwd()
126 check(err)
127 testDir := filepath.Join(repoRoot, ".cache")
128 check(os.MkdirAll(testDir, 0775))
129
Joe Tsaif3987842019-03-02 13:35:17 -0800130 // Travis-CI has a hard-coded timeout where it kills the test after
131 // 10 minutes of a lack of activity on stdout.
132 // We work around this restriction by periodically printing the timestamp.
133 ticker := time.NewTicker(5 * time.Minute)
134 done := make(chan struct{})
135 go func() {
136 now := time.Now()
137 for {
138 select {
139 case t := <-ticker.C:
140 fmt.Printf("\tt=%0.fmin\n", t.Sub(now).Minutes())
141 case <-done:
142 return
143 }
144 }
145 }()
146 defer close(done)
147 defer ticker.Stop()
148
Joe Tsai707894e2019-03-01 12:50:52 -0800149 // Delete the current directory if non-empty,
150 // which only occurs if a dependency failed to initialize properly.
151 var workingDir string
152 defer func() {
153 if workingDir != "" {
154 os.RemoveAll(workingDir) // best-effort
155 }
156 }()
157
158 // Delete other sub-directories that are no longer relevant.
159 defer func() {
160 subDirs := map[string]bool{"bin": true, "gocache": true, "gopath": true}
161 subDirs["protobuf-"+protobufVersion] = true
162 for _, v := range golangVersions {
163 subDirs["go"+v] = true
164 }
Joe Tsai707894e2019-03-01 12:50:52 -0800165
Joe Tsai9e88bc02019-03-12 01:30:40 -0700166 now := time.Now()
Joe Tsai707894e2019-03-01 12:50:52 -0800167 fis, _ := ioutil.ReadDir(testDir)
168 for _, fi := range fis {
Joe Tsai9e88bc02019-03-12 01:30:40 -0700169 if subDirs[fi.Name()] {
170 os.Chtimes(filepath.Join(testDir, fi.Name()), now, now) // best-effort
171 continue
Joe Tsai707894e2019-03-01 12:50:52 -0800172 }
Joe Tsai9e88bc02019-03-12 01:30:40 -0700173 if now.Sub(fi.ModTime()) < purgeTimeout {
174 continue
175 }
176 fmt.Printf("delete %v\n", fi.Name())
177 os.RemoveAll(filepath.Join(testDir, fi.Name())) // best-effort
Joe Tsai707894e2019-03-01 12:50:52 -0800178 }
179 }()
180
181 // The bin directory contains symlinks to each tool by version.
182 // It is safe to delete this directory and run the test script from scratch.
183 binPath := filepath.Join(testDir, "bin")
184 check(os.RemoveAll(binPath))
185 check(os.Mkdir(binPath, 0775))
186 check(os.Setenv("PATH", binPath+":"+os.Getenv("PATH")))
187 registerBinary := func(name, path string) {
188 check(os.Symlink(path, filepath.Join(binPath, name)))
189 }
190
191 // Download and build the protobuf toolchain.
192 // We avoid downloading the pre-compiled binaries since they do not contain
193 // the conformance test runner.
194 workingDir = filepath.Join(testDir, "protobuf-"+protobufVersion)
Herbie Ongd64dceb2019-04-25 01:19:57 -0700195 protobufPath = workingDir
196 if _, err := os.Stat(protobufPath); err != nil {
197 fmt.Printf("download %v\n", filepath.Base(protobufPath))
Joe Tsai707894e2019-03-01 12:50:52 -0800198 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 -0700199 downloadArchive(check, protobufPath, url, "protobuf-"+protobufVersion)
Joe Tsai707894e2019-03-01 12:50:52 -0800200
Herbie Ongd64dceb2019-04-25 01:19:57 -0700201 fmt.Printf("build %v\n", filepath.Base(protobufPath))
202 mustRunCommand(t, protobufPath, "./autogen.sh")
203 mustRunCommand(t, protobufPath, "./configure")
204 mustRunCommand(t, protobufPath, "make")
205 mustRunCommand(t, filepath.Join(protobufPath, "conformance"), "make")
Joe Tsai707894e2019-03-01 12:50:52 -0800206 }
Herbie Ongd64dceb2019-04-25 01:19:57 -0700207 patchProtos(check, protobufPath)
208 check(os.Setenv("PROTOBUF_ROOT", protobufPath)) // for generate-protos
209 registerBinary("conform-test-runner", filepath.Join(protobufPath, "conformance", "conformance-test-runner"))
210 registerBinary("protoc", filepath.Join(protobufPath, "src", "protoc"))
Joe Tsai707894e2019-03-01 12:50:52 -0800211 workingDir = ""
212
213 // Download each Go toolchain version.
214 for _, v := range golangVersions {
215 workingDir = filepath.Join(testDir, "go"+v)
216 if _, err := os.Stat(workingDir); err != nil {
217 fmt.Printf("download %v\n", filepath.Base(workingDir))
218 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 -0800219 downloadArchive(check, workingDir, url, "go")
Joe Tsai707894e2019-03-01 12:50:52 -0800220 }
221 registerBinary("go"+v, filepath.Join(workingDir, "bin", "go"))
222 }
223 registerBinary("go", filepath.Join(testDir, "go"+golangLatest, "bin", "go"))
224 registerBinary("gofmt", filepath.Join(testDir, "go"+golangLatest, "bin", "gofmt"))
225 workingDir = ""
226
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
231 // Set a cache directory within the test directory.
232 check(os.Setenv("GOCACHE", filepath.Join(testDir, "gocache")))
233
234 // Setup GOPATH for pre-module support (i.e., go1.10 and earlier).
235 goPath = filepath.Join(testDir, "gopath")
236 modulePath = strings.TrimSpace(mustRunCommand(t, testDir, "go", "list", "-m", "-f", "{{.Path}}"))
237 check(os.RemoveAll(filepath.Join(goPath, "src")))
238 check(os.MkdirAll(filepath.Join(goPath, "src", filepath.Dir(modulePath)), 0775))
239 check(os.Symlink(repoRoot, filepath.Join(goPath, "src", modulePath)))
240 mustRunCommand(t, repoRoot, "go", "mod", "tidy")
241 mustRunCommand(t, repoRoot, "go", "mod", "vendor")
242 check(os.Setenv("GOPATH", goPath))
243}
244
Joe Tsaif3987842019-03-02 13:35:17 -0800245func downloadArchive(check func(error), dstPath, srcURL, skipPrefix string) {
Joe Tsai707894e2019-03-01 12:50:52 -0800246 check(os.RemoveAll(dstPath))
247
248 resp, err := http.Get(srcURL)
249 check(err)
250 defer resp.Body.Close()
251
252 zr, err := gzip.NewReader(resp.Body)
253 check(err)
254
255 tr := tar.NewReader(zr)
256 for {
257 h, err := tr.Next()
258 if err == io.EOF {
259 return
260 }
261 check(err)
262
Joe Tsaif3987842019-03-02 13:35:17 -0800263 // 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
273 path := strings.TrimPrefix(strings.TrimPrefix(h.Name, skipPrefix), "/")
Joe Tsai707894e2019-03-01 12:50:52 -0800274 path = filepath.Join(dstPath, filepath.FromSlash(path))
275 mode := os.FileMode(h.Mode & 0777)
276 switch h.Typeflag {
277 case tar.TypeReg:
278 b, err := ioutil.ReadAll(tr)
279 check(err)
280 check(ioutil.WriteFile(path, b, mode))
281 case tar.TypeDir:
282 check(os.Mkdir(path, mode))
283 }
284 }
285}
286
287// patchProtos patches proto files with v2 locations of Go packages.
288// TODO: Commit these changes upstream.
289func patchProtos(check func(error), repoRoot string) {
290 javaPackageRx := regexp.MustCompile(`^option\s+java_package\s*=\s*".*"\s*;\s*$`)
291 goPackageRx := regexp.MustCompile(`^option\s+go_package\s*=\s*".*"\s*;\s*$`)
292 files := map[string]string{
Damien Neile89e6242019-05-13 23:55:40 -0700293 "src/google/protobuf/any.proto": "google.golang.org/protobuf/types/known;known_proto",
294 "src/google/protobuf/api.proto": "google.golang.org/protobuf/types/known;known_proto",
295 "src/google/protobuf/duration.proto": "google.golang.org/protobuf/types/known;known_proto",
296 "src/google/protobuf/empty.proto": "google.golang.org/protobuf/types/known;known_proto",
297 "src/google/protobuf/field_mask.proto": "google.golang.org/protobuf/types/known;known_proto",
298 "src/google/protobuf/source_context.proto": "google.golang.org/protobuf/types/known;known_proto",
299 "src/google/protobuf/struct.proto": "google.golang.org/protobuf/types/known;known_proto",
300 "src/google/protobuf/timestamp.proto": "google.golang.org/protobuf/types/known;known_proto",
301 "src/google/protobuf/type.proto": "google.golang.org/protobuf/types/known;known_proto",
302 "src/google/protobuf/wrappers.proto": "google.golang.org/protobuf/types/known;known_proto",
303 "src/google/protobuf/descriptor.proto": "google.golang.org/protobuf/types/descriptor;descriptor_proto",
304 "src/google/protobuf/compiler/plugin.proto": "google.golang.org/protobuf/types/plugin;plugin_proto",
305 "conformance/conformance.proto": "google.golang.org/protobuf/internal/testprotos/conformance;conformance",
306 "src/google/protobuf/test_messages_proto2.proto": "google.golang.org/protobuf/internal/testprotos/conformance;conformance",
307 "src/google/protobuf/test_messages_proto3.proto": "google.golang.org/protobuf/internal/testprotos/conformance;conformance",
Joe Tsai707894e2019-03-01 12:50:52 -0800308 }
309 for pbpath, gopath := range files {
310 b, err := ioutil.ReadFile(filepath.Join(repoRoot, pbpath))
311 check(err)
312 ss := strings.Split(string(b), "\n")
313
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
325 // Ensure the proto file has the correct go_package option.
326 opt := `option go_package = "` + gopath + `";`
327 if goPackageIdx >= 0 {
328 if ss[goPackageIdx] == opt {
329 continue // no changes needed
330 }
331 ss[goPackageIdx] = opt
332 } else {
333 // Insert go_package option before java_package option.
334 ss = append(ss[:javaPackageIdx], append([]string{opt}, ss[javaPackageIdx:]...)...)
335 }
336
337 fmt.Println("patch " + pbpath)
338 b = []byte(strings.Join(ss, "\n"))
339 check(ioutil.WriteFile(filepath.Join(repoRoot, pbpath), b, 0664))
340 }
341}
342
343func mustRunCommand(t *testing.T, dir string, args ...string) string {
344 t.Helper()
345 stdout := new(bytes.Buffer)
Herbie Ong4630b3d2019-03-19 16:42:01 -0700346 stderr := new(bytes.Buffer)
Joe Tsai707894e2019-03-01 12:50:52 -0800347 cmd := exec.Command(args[0], args[1:]...)
348 cmd.Dir = dir
349 cmd.Env = append(os.Environ(), "PWD="+dir)
Herbie Ong4630b3d2019-03-19 16:42:01 -0700350 cmd.Stdout = stdout
351 cmd.Stderr = stderr
Joe Tsai707894e2019-03-01 12:50:52 -0800352 if err := cmd.Run(); err != nil {
Herbie Ong4630b3d2019-03-19 16:42:01 -0700353 t.Fatalf("executing (%v): %v\n%s%s", strings.Join(args, " "), err, stdout.String(), stderr.String())
Joe Tsai707894e2019-03-01 12:50:52 -0800354 }
355 return stdout.String()
356}