blob: 7dd6b240adc54b00f746387e9f6a2f431f86cf5b [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.
39 goPath string
40 modulePath string
41)
42
43func Test(t *testing.T) {
44 mustInitDeps(t)
45
46 if *regenerate {
47 t.Run("Generate", func(t *testing.T) {
48 fmt.Print(mustRunCommand(t, ".", "go", "run", "./internal/cmd/generate-types", "-execute"))
49 fmt.Print(mustRunCommand(t, ".", "go", "run", "./internal/cmd/generate-protos", "-execute"))
50 files := strings.Split(strings.TrimSpace(mustRunCommand(t, ".", "git", "ls-files", "*.go")), "\n")
51 mustRunCommand(t, ".", append([]string{"gofmt", "-w"}, files...)...)
52 })
53 t.SkipNow()
54 }
55
56 for _, v := range golangVersions {
57 t.Run("Go"+v, func(t *testing.T) {
Joe Tsaid56458e2019-03-01 18:11:42 -080058 runGo := func(label, workDir string, args ...string) {
Joe Tsai707894e2019-03-01 12:50:52 -080059 args[0] += v
60 t.Run(label, func(t *testing.T) {
61 t.Parallel()
Joe Tsaid56458e2019-03-01 18:11:42 -080062 mustRunCommand(t, workDir, args...)
Joe Tsai707894e2019-03-01 12:50:52 -080063 })
64 }
Joe Tsaid56458e2019-03-01 18:11:42 -080065 workDir := filepath.Join(goPath, "src", modulePath)
66 runGo("Build", workDir, "go", "build", "./...")
67 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
78 t.Run("GeneratedGoFiles", func(t *testing.T) {
79 diff := mustRunCommand(t, ".", "go", "run", "./internal/cmd/generate-types")
80 if strings.TrimSpace(diff) != "" {
81 t.Fatalf("stale generated files:\n%v", diff)
82 }
83 diff = mustRunCommand(t, ".", "go", "run", "./internal/cmd/generate-protos")
84 if strings.TrimSpace(diff) != "" {
85 t.Fatalf("stale generated files:\n%v", diff)
86 }
87 })
88 t.Run("FormattedGoFiles", func(t *testing.T) {
89 files := strings.Split(strings.TrimSpace(mustRunCommand(t, ".", "git", "ls-files", "*.go")), "\n")
90 diff := mustRunCommand(t, ".", append([]string{"gofmt", "-d"}, files...)...)
91 if strings.TrimSpace(diff) != "" {
92 t.Fatalf("unformatted source files:\n%v", diff)
93 }
94 })
95 t.Run("CommittedGitChanges", func(t *testing.T) {
96 diff := mustRunCommand(t, ".", "git", "diff", "--no-prefix", "HEAD")
97 if strings.TrimSpace(diff) != "" {
98 t.Fatalf("uncommitted changes:\n%v", diff)
99 }
100 })
101 t.Run("TrackedGitFiles", func(t *testing.T) {
102 diff := mustRunCommand(t, ".", "git", "ls-files", "--others", "--exclude-standard")
103 if strings.TrimSpace(diff) != "" {
104 t.Fatalf("untracked files:\n%v", diff)
105 }
106 })
107}
108
109func mustInitDeps(t *testing.T) {
110 check := func(err error) {
111 t.Helper()
112 if err != nil {
113 t.Fatal(err)
114 }
115 }
116
117 // Determine the directory to place the test directory.
118 repoRoot, err := os.Getwd()
119 check(err)
120 testDir := filepath.Join(repoRoot, ".cache")
121 check(os.MkdirAll(testDir, 0775))
122
Joe Tsaif3987842019-03-02 13:35:17 -0800123 // Travis-CI has a hard-coded timeout where it kills the test after
124 // 10 minutes of a lack of activity on stdout.
125 // We work around this restriction by periodically printing the timestamp.
126 ticker := time.NewTicker(5 * time.Minute)
127 done := make(chan struct{})
128 go func() {
129 now := time.Now()
130 for {
131 select {
132 case t := <-ticker.C:
133 fmt.Printf("\tt=%0.fmin\n", t.Sub(now).Minutes())
134 case <-done:
135 return
136 }
137 }
138 }()
139 defer close(done)
140 defer ticker.Stop()
141
Joe Tsai707894e2019-03-01 12:50:52 -0800142 // Delete the current directory if non-empty,
143 // which only occurs if a dependency failed to initialize properly.
144 var workingDir string
145 defer func() {
146 if workingDir != "" {
147 os.RemoveAll(workingDir) // best-effort
148 }
149 }()
150
151 // Delete other sub-directories that are no longer relevant.
152 defer func() {
153 subDirs := map[string]bool{"bin": true, "gocache": true, "gopath": true}
154 subDirs["protobuf-"+protobufVersion] = true
155 for _, v := range golangVersions {
156 subDirs["go"+v] = true
157 }
Joe Tsai707894e2019-03-01 12:50:52 -0800158
Joe Tsai9e88bc02019-03-12 01:30:40 -0700159 now := time.Now()
Joe Tsai707894e2019-03-01 12:50:52 -0800160 fis, _ := ioutil.ReadDir(testDir)
161 for _, fi := range fis {
Joe Tsai9e88bc02019-03-12 01:30:40 -0700162 if subDirs[fi.Name()] {
163 os.Chtimes(filepath.Join(testDir, fi.Name()), now, now) // best-effort
164 continue
Joe Tsai707894e2019-03-01 12:50:52 -0800165 }
Joe Tsai9e88bc02019-03-12 01:30:40 -0700166 if now.Sub(fi.ModTime()) < purgeTimeout {
167 continue
168 }
169 fmt.Printf("delete %v\n", fi.Name())
170 os.RemoveAll(filepath.Join(testDir, fi.Name())) // best-effort
Joe Tsai707894e2019-03-01 12:50:52 -0800171 }
172 }()
173
174 // The bin directory contains symlinks to each tool by version.
175 // It is safe to delete this directory and run the test script from scratch.
176 binPath := filepath.Join(testDir, "bin")
177 check(os.RemoveAll(binPath))
178 check(os.Mkdir(binPath, 0775))
179 check(os.Setenv("PATH", binPath+":"+os.Getenv("PATH")))
180 registerBinary := func(name, path string) {
181 check(os.Symlink(path, filepath.Join(binPath, name)))
182 }
183
184 // Download and build the protobuf toolchain.
185 // We avoid downloading the pre-compiled binaries since they do not contain
186 // the conformance test runner.
187 workingDir = filepath.Join(testDir, "protobuf-"+protobufVersion)
188 if _, err := os.Stat(workingDir); err != nil {
189 fmt.Printf("download %v\n", filepath.Base(workingDir))
190 url := fmt.Sprintf("https://github.com/google/protobuf/releases/download/v%v/protobuf-all-%v.tar.gz", protobufVersion, protobufVersion)
Joe Tsaif3987842019-03-02 13:35:17 -0800191 downloadArchive(check, workingDir, url, "protobuf-"+protobufVersion)
Joe Tsai707894e2019-03-01 12:50:52 -0800192
193 fmt.Printf("build %v\n", filepath.Base(workingDir))
Joe Tsaif3987842019-03-02 13:35:17 -0800194 mustRunCommand(t, workingDir, "./autogen.sh")
Joe Tsai707894e2019-03-01 12:50:52 -0800195 mustRunCommand(t, workingDir, "./configure")
196 mustRunCommand(t, workingDir, "make")
197 mustRunCommand(t, filepath.Join(workingDir, "conformance"), "make")
198 }
199 patchProtos(check, workingDir)
200 check(os.Setenv("PROTOBUF_ROOT", workingDir)) // for generate-protos
201 registerBinary("conform-test-runner", filepath.Join(workingDir, "conformance", "conformance-test-runner"))
202 registerBinary("protoc", filepath.Join(workingDir, "src", "protoc"))
203 workingDir = ""
204
205 // Download each Go toolchain version.
206 for _, v := range golangVersions {
207 workingDir = filepath.Join(testDir, "go"+v)
208 if _, err := os.Stat(workingDir); err != nil {
209 fmt.Printf("download %v\n", filepath.Base(workingDir))
210 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 -0800211 downloadArchive(check, workingDir, url, "go")
Joe Tsai707894e2019-03-01 12:50:52 -0800212 }
213 registerBinary("go"+v, filepath.Join(workingDir, "bin", "go"))
214 }
215 registerBinary("go", filepath.Join(testDir, "go"+golangLatest, "bin", "go"))
216 registerBinary("gofmt", filepath.Join(testDir, "go"+golangLatest, "bin", "gofmt"))
217 workingDir = ""
218
219 // Travis-CI sets GOROOT, which confuses invocations of the Go toolchain.
220 // Explicitly clear GOROOT, so each toolchain uses their default GOROOT.
221 check(os.Unsetenv("GOROOT"))
222
223 // Set a cache directory within the test directory.
224 check(os.Setenv("GOCACHE", filepath.Join(testDir, "gocache")))
225
226 // Setup GOPATH for pre-module support (i.e., go1.10 and earlier).
227 goPath = filepath.Join(testDir, "gopath")
228 modulePath = strings.TrimSpace(mustRunCommand(t, testDir, "go", "list", "-m", "-f", "{{.Path}}"))
229 check(os.RemoveAll(filepath.Join(goPath, "src")))
230 check(os.MkdirAll(filepath.Join(goPath, "src", filepath.Dir(modulePath)), 0775))
231 check(os.Symlink(repoRoot, filepath.Join(goPath, "src", modulePath)))
232 mustRunCommand(t, repoRoot, "go", "mod", "tidy")
233 mustRunCommand(t, repoRoot, "go", "mod", "vendor")
234 check(os.Setenv("GOPATH", goPath))
235}
236
Joe Tsaif3987842019-03-02 13:35:17 -0800237func downloadArchive(check func(error), dstPath, srcURL, skipPrefix string) {
Joe Tsai707894e2019-03-01 12:50:52 -0800238 check(os.RemoveAll(dstPath))
239
240 resp, err := http.Get(srcURL)
241 check(err)
242 defer resp.Body.Close()
243
244 zr, err := gzip.NewReader(resp.Body)
245 check(err)
246
247 tr := tar.NewReader(zr)
248 for {
249 h, err := tr.Next()
250 if err == io.EOF {
251 return
252 }
253 check(err)
254
Joe Tsaif3987842019-03-02 13:35:17 -0800255 // Skip directories or files outside the prefix directory.
256 if len(skipPrefix) > 0 {
257 if !strings.HasPrefix(h.Name, skipPrefix) {
258 continue
259 }
260 if len(h.Name) > len(skipPrefix) && h.Name[len(skipPrefix)] != '/' {
261 continue
262 }
263 }
264
265 path := strings.TrimPrefix(strings.TrimPrefix(h.Name, skipPrefix), "/")
Joe Tsai707894e2019-03-01 12:50:52 -0800266 path = filepath.Join(dstPath, filepath.FromSlash(path))
267 mode := os.FileMode(h.Mode & 0777)
268 switch h.Typeflag {
269 case tar.TypeReg:
270 b, err := ioutil.ReadAll(tr)
271 check(err)
272 check(ioutil.WriteFile(path, b, mode))
273 case tar.TypeDir:
274 check(os.Mkdir(path, mode))
275 }
276 }
277}
278
279// patchProtos patches proto files with v2 locations of Go packages.
280// TODO: Commit these changes upstream.
281func patchProtos(check func(error), repoRoot string) {
282 javaPackageRx := regexp.MustCompile(`^option\s+java_package\s*=\s*".*"\s*;\s*$`)
283 goPackageRx := regexp.MustCompile(`^option\s+go_package\s*=\s*".*"\s*;\s*$`)
284 files := map[string]string{
285 "src/google/protobuf/any.proto": "github.com/golang/protobuf/v2/types/known;known_proto",
286 "src/google/protobuf/api.proto": "github.com/golang/protobuf/v2/types/known;known_proto",
287 "src/google/protobuf/duration.proto": "github.com/golang/protobuf/v2/types/known;known_proto",
288 "src/google/protobuf/empty.proto": "github.com/golang/protobuf/v2/types/known;known_proto",
289 "src/google/protobuf/field_mask.proto": "github.com/golang/protobuf/v2/types/known;known_proto",
290 "src/google/protobuf/source_context.proto": "github.com/golang/protobuf/v2/types/known;known_proto",
291 "src/google/protobuf/struct.proto": "github.com/golang/protobuf/v2/types/known;known_proto",
292 "src/google/protobuf/timestamp.proto": "github.com/golang/protobuf/v2/types/known;known_proto",
293 "src/google/protobuf/type.proto": "github.com/golang/protobuf/v2/types/known;known_proto",
294 "src/google/protobuf/wrappers.proto": "github.com/golang/protobuf/v2/types/known;known_proto",
295 "src/google/protobuf/descriptor.proto": "github.com/golang/protobuf/v2/types/descriptor;descriptor_proto",
296 "src/google/protobuf/compiler/plugin.proto": "github.com/golang/protobuf/v2/types/plugin;plugin_proto",
297 "conformance/conformance.proto": "github.com/golang/protobuf/v2/internal/testprotos/conformance;conformance_proto",
298 }
299 for pbpath, gopath := range files {
300 b, err := ioutil.ReadFile(filepath.Join(repoRoot, pbpath))
301 check(err)
302 ss := strings.Split(string(b), "\n")
303
304 // Locate java_package and (possible) go_package options.
305 javaPackageIdx, goPackageIdx := -1, -1
306 for i, s := range ss {
307 if javaPackageIdx < 0 && javaPackageRx.MatchString(s) {
308 javaPackageIdx = i
309 }
310 if goPackageIdx < 0 && goPackageRx.MatchString(s) {
311 goPackageIdx = i
312 }
313 }
314
315 // Ensure the proto file has the correct go_package option.
316 opt := `option go_package = "` + gopath + `";`
317 if goPackageIdx >= 0 {
318 if ss[goPackageIdx] == opt {
319 continue // no changes needed
320 }
321 ss[goPackageIdx] = opt
322 } else {
323 // Insert go_package option before java_package option.
324 ss = append(ss[:javaPackageIdx], append([]string{opt}, ss[javaPackageIdx:]...)...)
325 }
326
327 fmt.Println("patch " + pbpath)
328 b = []byte(strings.Join(ss, "\n"))
329 check(ioutil.WriteFile(filepath.Join(repoRoot, pbpath), b, 0664))
330 }
331}
332
333func mustRunCommand(t *testing.T, dir string, args ...string) string {
334 t.Helper()
335 stdout := new(bytes.Buffer)
Herbie Ong4630b3d2019-03-19 16:42:01 -0700336 stderr := new(bytes.Buffer)
Joe Tsai707894e2019-03-01 12:50:52 -0800337 cmd := exec.Command(args[0], args[1:]...)
338 cmd.Dir = dir
339 cmd.Env = append(os.Environ(), "PWD="+dir)
Herbie Ong4630b3d2019-03-19 16:42:01 -0700340 cmd.Stdout = stdout
341 cmd.Stderr = stderr
Joe Tsai707894e2019-03-01 12:50:52 -0800342 if err := cmd.Run(); err != nil {
Herbie Ong4630b3d2019-03-19 16:42:01 -0700343 t.Fatalf("executing (%v): %v\n%s%s", strings.Join(args, " "), err, stdout.String(), stderr.String())
Joe Tsai707894e2019-03-01 12:50:52 -0800344 }
345 return stdout.String()
346}