Skip to content

Commit f41bc14

Browse files
committed
test.bash: re-write integration test as a Go test
This change: * upgrades the v2 dependency to the latest version * copies integration_test.go from v2 and deletes irrelevant code. * copies internal/cmd/generate-protos from v2 and deletes irrelevant code and modifies generateLocalProtos accordingly * deletes protoc-gen-go/testdata since this is covered in v2 * uses import public to alias the v2 version of the well-known types, plugin proto, and descriptor proto Change-Id: Ib1d4280afaca8a811b9ff57792e02b15b3b8f0ec Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/167141 Reviewed-by: Herbie Ong <[email protected]>
1 parent e581f92 commit f41bc14

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

86 files changed

+2227
-13490
lines changed

Makefile

-22
This file was deleted.

go.mod

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
module github.com/golang/protobuf
22

3-
require github.com/golang/protobuf/v2 v2.0.0-20190311234237-8692540cce25
3+
require github.com/golang/protobuf/v2 v2.0.0-20190312230405-4989810018b7

go.sum

+4-4
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
github.com/golang/protobuf v1.2.1-0.20190311233832-968e039ade03/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
2-
github.com/golang/protobuf/v2 v2.0.0-20190311234237-8692540cce25 h1:OPot/6pIGOXutoEWwijGIyc0s72oha4VMKjoMKgSD84=
3-
github.com/golang/protobuf/v2 v2.0.0-20190311234237-8692540cce25/go.mod h1:JBgB92qSNOVlmhtPbF3BkMlBy5KGJj+k0lo1MaNJhxE=
4-
github.com/google/go-cmp v0.2.0 h1:+dTQ8DZQJz0Mb/HjFlkptS1FeQ4cWSnN941F8aEG4SQ=
5-
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
2+
github.com/golang/protobuf/v2 v2.0.0-20190312230405-4989810018b7 h1:aQENkYDAn/68ZfghmurTBhR18Q7/XWx1JpMaqFtP1GM=
3+
github.com/golang/protobuf/v2 v2.0.0-20190312230405-4989810018b7/go.mod h1:euNorOscCho6jibQUfcx8TAp5HZXU5/+1xMsdtkc8lo=
4+
github.com/google/go-cmp v0.2.1-0.20190228024137-c81281657ad9 h1:GDk30QdVXDf6i734280OeWAO9UCCjXLeWkLLyHQGUkI=
5+
github.com/google/go-cmp v0.2.1-0.20190228024137-c81281657ad9/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=

integration_test.go

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

0 commit comments

Comments
 (0)