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