blob: eb1b7a4afbf7ada508bb7ada11f8978da6c79eda [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) {
60 runGo := func(label string, args ...string) {
61 args[0] += v
62 t.Run(label, func(t *testing.T) {
63 t.Parallel()
64 mustRunCommand(t, filepath.Join(goPath, "src", modulePath), args...)
65 })
66 }
67 // TODO: "go build" does not descend into testdata,
68 // which means that generated .pb.go files are not being built.
69 runGo("Build", "go", "build", "./...")
70 runGo("TestNormal", "go", "test", "-race", "./...")
71 runGo("TestPureGo", "go", "test", "-race", "-tags", "purego", "./...")
72 if v == golangLatest {
73 runGo("TestLegacy", "go", "test", "-race", "-tags", "proto1_legacy", "./...")
74 }
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 }
158 for _, d := range keepDirs {
159 subDirs[d] = true
160 }
161
162 fis, _ := ioutil.ReadDir(testDir)
163 for _, fi := range fis {
164 if !subDirs[fi.Name()] {
165 fmt.Printf("delete %v\n", fi.Name())
166 os.RemoveAll(filepath.Join(testDir, fi.Name())) // best-effort
167 }
168 }
169 }()
170
171 // The bin directory contains symlinks to each tool by version.
172 // It is safe to delete this directory and run the test script from scratch.
173 binPath := filepath.Join(testDir, "bin")
174 check(os.RemoveAll(binPath))
175 check(os.Mkdir(binPath, 0775))
176 check(os.Setenv("PATH", binPath+":"+os.Getenv("PATH")))
177 registerBinary := func(name, path string) {
178 check(os.Symlink(path, filepath.Join(binPath, name)))
179 }
180
181 // Download and build the protobuf toolchain.
182 // We avoid downloading the pre-compiled binaries since they do not contain
183 // the conformance test runner.
184 workingDir = filepath.Join(testDir, "protobuf-"+protobufVersion)
185 if _, err := os.Stat(workingDir); err != nil {
186 fmt.Printf("download %v\n", filepath.Base(workingDir))
187 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 -0800188 downloadArchive(check, workingDir, url, "protobuf-"+protobufVersion)
Joe Tsai707894e2019-03-01 12:50:52 -0800189
190 fmt.Printf("build %v\n", filepath.Base(workingDir))
Joe Tsaif3987842019-03-02 13:35:17 -0800191 mustRunCommand(t, workingDir, "./autogen.sh")
Joe Tsai707894e2019-03-01 12:50:52 -0800192 mustRunCommand(t, workingDir, "./configure")
193 mustRunCommand(t, workingDir, "make")
194 mustRunCommand(t, filepath.Join(workingDir, "conformance"), "make")
195 }
196 patchProtos(check, workingDir)
197 check(os.Setenv("PROTOBUF_ROOT", workingDir)) // for generate-protos
198 registerBinary("conform-test-runner", filepath.Join(workingDir, "conformance", "conformance-test-runner"))
199 registerBinary("protoc", filepath.Join(workingDir, "src", "protoc"))
200 workingDir = ""
201
202 // Download each Go toolchain version.
203 for _, v := range golangVersions {
204 workingDir = filepath.Join(testDir, "go"+v)
205 if _, err := os.Stat(workingDir); err != nil {
206 fmt.Printf("download %v\n", filepath.Base(workingDir))
207 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 -0800208 downloadArchive(check, workingDir, url, "go")
Joe Tsai707894e2019-03-01 12:50:52 -0800209 }
210 registerBinary("go"+v, filepath.Join(workingDir, "bin", "go"))
211 }
212 registerBinary("go", filepath.Join(testDir, "go"+golangLatest, "bin", "go"))
213 registerBinary("gofmt", filepath.Join(testDir, "go"+golangLatest, "bin", "gofmt"))
214 workingDir = ""
215
216 // Travis-CI sets GOROOT, which confuses invocations of the Go toolchain.
217 // Explicitly clear GOROOT, so each toolchain uses their default GOROOT.
218 check(os.Unsetenv("GOROOT"))
219
220 // Set a cache directory within the test directory.
221 check(os.Setenv("GOCACHE", filepath.Join(testDir, "gocache")))
222
223 // Setup GOPATH for pre-module support (i.e., go1.10 and earlier).
224 goPath = filepath.Join(testDir, "gopath")
225 modulePath = strings.TrimSpace(mustRunCommand(t, testDir, "go", "list", "-m", "-f", "{{.Path}}"))
226 check(os.RemoveAll(filepath.Join(goPath, "src")))
227 check(os.MkdirAll(filepath.Join(goPath, "src", filepath.Dir(modulePath)), 0775))
228 check(os.Symlink(repoRoot, filepath.Join(goPath, "src", modulePath)))
229 mustRunCommand(t, repoRoot, "go", "mod", "tidy")
230 mustRunCommand(t, repoRoot, "go", "mod", "vendor")
231 check(os.Setenv("GOPATH", goPath))
232}
233
Joe Tsaif3987842019-03-02 13:35:17 -0800234func downloadArchive(check func(error), dstPath, srcURL, skipPrefix string) {
Joe Tsai707894e2019-03-01 12:50:52 -0800235 check(os.RemoveAll(dstPath))
236
237 resp, err := http.Get(srcURL)
238 check(err)
239 defer resp.Body.Close()
240
241 zr, err := gzip.NewReader(resp.Body)
242 check(err)
243
244 tr := tar.NewReader(zr)
245 for {
246 h, err := tr.Next()
247 if err == io.EOF {
248 return
249 }
250 check(err)
251
Joe Tsaif3987842019-03-02 13:35:17 -0800252 // Skip directories or files outside the prefix directory.
253 if len(skipPrefix) > 0 {
254 if !strings.HasPrefix(h.Name, skipPrefix) {
255 continue
256 }
257 if len(h.Name) > len(skipPrefix) && h.Name[len(skipPrefix)] != '/' {
258 continue
259 }
260 }
261
262 path := strings.TrimPrefix(strings.TrimPrefix(h.Name, skipPrefix), "/")
Joe Tsai707894e2019-03-01 12:50:52 -0800263 path = filepath.Join(dstPath, filepath.FromSlash(path))
264 mode := os.FileMode(h.Mode & 0777)
265 switch h.Typeflag {
266 case tar.TypeReg:
267 b, err := ioutil.ReadAll(tr)
268 check(err)
269 check(ioutil.WriteFile(path, b, mode))
270 case tar.TypeDir:
271 check(os.Mkdir(path, mode))
272 }
273 }
274}
275
276// patchProtos patches proto files with v2 locations of Go packages.
277// TODO: Commit these changes upstream.
278func patchProtos(check func(error), repoRoot string) {
279 javaPackageRx := regexp.MustCompile(`^option\s+java_package\s*=\s*".*"\s*;\s*$`)
280 goPackageRx := regexp.MustCompile(`^option\s+go_package\s*=\s*".*"\s*;\s*$`)
281 files := map[string]string{
282 "src/google/protobuf/any.proto": "github.com/golang/protobuf/v2/types/known;known_proto",
283 "src/google/protobuf/api.proto": "github.com/golang/protobuf/v2/types/known;known_proto",
284 "src/google/protobuf/duration.proto": "github.com/golang/protobuf/v2/types/known;known_proto",
285 "src/google/protobuf/empty.proto": "github.com/golang/protobuf/v2/types/known;known_proto",
286 "src/google/protobuf/field_mask.proto": "github.com/golang/protobuf/v2/types/known;known_proto",
287 "src/google/protobuf/source_context.proto": "github.com/golang/protobuf/v2/types/known;known_proto",
288 "src/google/protobuf/struct.proto": "github.com/golang/protobuf/v2/types/known;known_proto",
289 "src/google/protobuf/timestamp.proto": "github.com/golang/protobuf/v2/types/known;known_proto",
290 "src/google/protobuf/type.proto": "github.com/golang/protobuf/v2/types/known;known_proto",
291 "src/google/protobuf/wrappers.proto": "github.com/golang/protobuf/v2/types/known;known_proto",
292 "src/google/protobuf/descriptor.proto": "github.com/golang/protobuf/v2/types/descriptor;descriptor_proto",
293 "src/google/protobuf/compiler/plugin.proto": "github.com/golang/protobuf/v2/types/plugin;plugin_proto",
294 "conformance/conformance.proto": "github.com/golang/protobuf/v2/internal/testprotos/conformance;conformance_proto",
295 }
296 for pbpath, gopath := range files {
297 b, err := ioutil.ReadFile(filepath.Join(repoRoot, pbpath))
298 check(err)
299 ss := strings.Split(string(b), "\n")
300
301 // Locate java_package and (possible) go_package options.
302 javaPackageIdx, goPackageIdx := -1, -1
303 for i, s := range ss {
304 if javaPackageIdx < 0 && javaPackageRx.MatchString(s) {
305 javaPackageIdx = i
306 }
307 if goPackageIdx < 0 && goPackageRx.MatchString(s) {
308 goPackageIdx = i
309 }
310 }
311
312 // Ensure the proto file has the correct go_package option.
313 opt := `option go_package = "` + gopath + `";`
314 if goPackageIdx >= 0 {
315 if ss[goPackageIdx] == opt {
316 continue // no changes needed
317 }
318 ss[goPackageIdx] = opt
319 } else {
320 // Insert go_package option before java_package option.
321 ss = append(ss[:javaPackageIdx], append([]string{opt}, ss[javaPackageIdx:]...)...)
322 }
323
324 fmt.Println("patch " + pbpath)
325 b = []byte(strings.Join(ss, "\n"))
326 check(ioutil.WriteFile(filepath.Join(repoRoot, pbpath), b, 0664))
327 }
328}
329
330func mustRunCommand(t *testing.T, dir string, args ...string) string {
331 t.Helper()
332 stdout := new(bytes.Buffer)
333 combined := new(bytes.Buffer)
334 cmd := exec.Command(args[0], args[1:]...)
335 cmd.Dir = dir
336 cmd.Env = append(os.Environ(), "PWD="+dir)
337 cmd.Stdout = io.MultiWriter(stdout, combined)
338 cmd.Stderr = combined
339 if err := cmd.Run(); err != nil {
340 t.Fatalf("executing (%v): %v\n%s", strings.Join(args, " "), err, combined.String())
341 }
342 return stdout.String()
343}