Debian Codegraph @

libgo/go/internal/testenv/testenv.go

raw
1 // Copyright 2015 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 // Package testenv provides information about what functionality
6 // is available in different testing environments run by the Go team.
7 //
8 // It is an internal package because these details are specific
9 // to the Go team's test setup (on build.golang.org) and not
10 // fundamental to tests in general.
11 package testenv
12
13 import (
14 "bytes"
15 "errors"
16 "flag"
17 "internal/cfg"
18 "os"
19 "os/exec"
20 "path/filepath"
21 "runtime"
22 "strconv"
23 "strings"
24 "sync"
25 "testing"
26 "time"
27 )
28
29 // testingGotools reports whether we are testing the gotools directory
30 // that is part of GCC. We just use an environment variable set by the
31 // gotools check target.
32 func testingGotools() bool {
33 return os.Getenv("GO_TESTING_GOTOOLS") != ""
34 }
35
36 // Builder reports the name of the builder running this test
37 // (for example, "linux-amd64" or "windows-386-gce").
38 // If the test is not running on the build infrastructure,
39 // Builder returns the empty string.
40 func Builder() string {
41 return os.Getenv("GO_BUILDER_NAME")
42 }
43
44 // HasGoBuild reports whether the current system can build programs with ``go build''
45 // and then run them with os.StartProcess or exec.Command.
46 func HasGoBuild() bool {
47 if os.Getenv("GO_GCFLAGS") != "" {
48 // It's too much work to require every caller of the go command
49 // to pass along "-gcflags="+os.Getenv("GO_GCFLAGS").
50 // For now, if $GO_GCFLAGS is set, report that we simply can't
51 // run go build.
52 return false
53 }
54 switch runtime.GOOS {
55 case "android", "js", "ios":
56 return false
57 }
58 // gccgo tests can not run "go build".
59 return testingGotools()
60 }
61
62 // MustHaveGoBuild checks that the current system can build programs with ``go build''
63 // and then run them with os.StartProcess or exec.Command.
64 // If not, MustHaveGoBuild calls t.Skip with an explanation.
65 func MustHaveGoBuild(t testing.TB) {
66 if !testingGotools() {
67 t.Skip("skipping test: 'go build' not available for gccgo tests")
68 }
69 if os.Getenv("GO_GCFLAGS") != "" {
70 t.Skipf("skipping test: 'go build' not compatible with setting $GO_GCFLAGS")
71 }
72 if !HasGoBuild() {
73 t.Skipf("skipping test: 'go build' not available on %s/%s", runtime.GOOS, runtime.GOARCH)
74 }
75 }
76
77 // HasGoRun reports whether the current system can run programs with ``go run.''
78 func HasGoRun() bool {
79 // For now, having go run and having go build are the same.
80 return HasGoBuild()
81 }
82
83 // MustHaveGoRun checks that the current system can run programs with ``go run.''
84 // If not, MustHaveGoRun calls t.Skip with an explanation.
85 func MustHaveGoRun(t testing.TB) {
86 if !testingGotools() {
87 t.Skip("skipping test: 'go run' not available for gccgo tests")
88 }
89 if !HasGoRun() {
90 t.Skipf("skipping test: 'go run' not available on %s/%s", runtime.GOOS, runtime.GOARCH)
91 }
92 }
93
94 // GoToolPath reports the path to the Go tool.
95 // It is a convenience wrapper around GoTool.
96 // If the tool is unavailable GoToolPath calls t.Skip.
97 // If the tool should be available and isn't, GoToolPath calls t.Fatal.
98 func GoToolPath(t testing.TB) string {
99 MustHaveGoBuild(t)
100 path, err := GoTool()
101 if err != nil {
102 t.Fatal(err)
103 }
104 // Add all environment variables that affect the Go command to test metadata.
105 // Cached test results will be invalidate when these variables change.
106 // See golang.org/issue/32285.
107 for _, envVar := range strings.Fields(cfg.KnownEnv) {
108 os.Getenv(envVar)
109 }
110 return path
111 }
112
113 // GoTool reports the path to the Go tool.
114 func GoTool() (string, error) {
115 if !HasGoBuild() {
116 return "", errors.New("platform cannot run go tool")
117 }
118 var exeSuffix string
119 if runtime.GOOS == "windows" {
120 exeSuffix = ".exe"
121 }
122 path := filepath.Join(runtime.GOROOT(), "bin", "go"+exeSuffix)
123 if _, err := os.Stat(path); err == nil {
124 return path, nil
125 }
126 goBin, err := exec.LookPath("go" + exeSuffix)
127 if err != nil {
128 return "", errors.New("cannot find go tool: " + err.Error())
129 }
130 return goBin, nil
131 }
132
133 // HasExec reports whether the current system can start new processes
134 // using os.StartProcess or (more commonly) exec.Command.
135 func HasExec() bool {
136 switch runtime.GOOS {
137 case "js", "ios":
138 return false
139 }
140 return true
141 }
142
143 // HasSrc reports whether the entire source tree is available under GOROOT.
144 func HasSrc() bool {
145 switch runtime.GOOS {
146 case "ios":
147 return false
148 }
149 if runtime.Compiler == "gccgo" {
150 return false
151 }
152 return true
153 }
154
155 // MustHaveExec checks that the current system can start new processes
156 // using os.StartProcess or (more commonly) exec.Command.
157 // If not, MustHaveExec calls t.Skip with an explanation.
158 func MustHaveExec(t testing.TB) {
159 if !HasExec() {
160 t.Skipf("skipping test: cannot exec subprocess on %s/%s", runtime.GOOS, runtime.GOARCH)
161 }
162 }
163
164 var execPaths sync.Map // path -> error
165
166 // MustHaveExecPath checks that the current system can start the named executable
167 // using os.StartProcess or (more commonly) exec.Command.
168 // If not, MustHaveExecPath calls t.Skip with an explanation.
169 func MustHaveExecPath(t testing.TB, path string) {
170 MustHaveExec(t)
171
172 err, found := execPaths.Load(path)
173 if !found {
174 _, err = exec.LookPath(path)
175 err, _ = execPaths.LoadOrStore(path, err)
176 }
177 if err != nil {
178 t.Skipf("skipping test: %s: %s", path, err)
179 }
180 }
181
182 // HasExternalNetwork reports whether the current system can use
183 // external (non-localhost) networks.
184 func HasExternalNetwork() bool {
185 return !testing.Short() && runtime.GOOS != "js"
186 }
187
188 // MustHaveExternalNetwork checks that the current system can use
189 // external (non-localhost) networks.
190 // If not, MustHaveExternalNetwork calls t.Skip with an explanation.
191 func MustHaveExternalNetwork(t testing.TB) {
192 if runtime.GOOS == "js" {
193 t.Skipf("skipping test: no external network on %s", runtime.GOOS)
194 }
195 if testing.Short() {
196 t.Skipf("skipping test: no external network in -short mode")
197 }
198 }
199
200 var haveCGO bool
201
202 // HasCGO reports whether the current system can use cgo.
203 func HasCGO() bool {
204 return haveCGO
205 }
206
207 // MustHaveCGO calls t.Skip if cgo is not available.
208 func MustHaveCGO(t testing.TB) {
209 if !haveCGO {
210 t.Skipf("skipping test: no cgo")
211 }
212 }
213
214 // CanInternalLink reports whether the current system can link programs with
215 // internal linking.
216 // (This is the opposite of cmd/internal/sys.MustLinkExternal. Keep them in sync.)
217 func CanInternalLink() bool {
218 switch runtime.GOOS {
219 case "android":
220 if runtime.GOARCH != "arm64" {
221 return false
222 }
223 case "ios":
224 if runtime.GOARCH == "arm64" {
225 return false
226 }
227 }
228 return true
229 }
230
231 // MustInternalLink checks that the current system can link programs with internal
232 // linking.
233 // If not, MustInternalLink calls t.Skip with an explanation.
234 func MustInternalLink(t testing.TB) {
235 if !CanInternalLink() {
236 t.Skipf("skipping test: internal linking on %s/%s is not supported", runtime.GOOS, runtime.GOARCH)
237 }
238 }
239
240 // HasSymlink reports whether the current system can use os.Symlink.
241 func HasSymlink() bool {
242 ok, _ := hasSymlink()
243 return ok
244 }
245
246 // MustHaveSymlink reports whether the current system can use os.Symlink.
247 // If not, MustHaveSymlink calls t.Skip with an explanation.
248 func MustHaveSymlink(t testing.TB) {
249 ok, reason := hasSymlink()
250 if !ok {
251 t.Skipf("skipping test: cannot make symlinks on %s/%s%s", runtime.GOOS, runtime.GOARCH, reason)
252 }
253 }
254
255 // HasLink reports whether the current system can use os.Link.
256 func HasLink() bool {
257 // From Android release M (Marshmallow), hard linking files is blocked
258 // and an attempt to call link() on a file will return EACCES.
259 // - https://code.google.com/p/android-developer-preview/issues/detail?id=3150
260 return runtime.GOOS != "plan9" && runtime.GOOS != "android"
261 }
262
263 // MustHaveLink reports whether the current system can use os.Link.
264 // If not, MustHaveLink calls t.Skip with an explanation.
265 func MustHaveLink(t testing.TB) {
266 if !HasLink() {
267 t.Skipf("skipping test: hardlinks are not supported on %s/%s", runtime.GOOS, runtime.GOARCH)
268 }
269 }
270
271 var flaky = flag.Bool("flaky", false, "run known-flaky tests too")
272
273 func SkipFlaky(t testing.TB, issue int) {
274 t.Helper()
275 if !*flaky {
276 t.Skipf("skipping known flaky test without the -flaky flag; see golang.org/issue/%d", issue)
277 }
278 }
279
280 func SkipFlakyNet(t testing.TB) {
281 t.Helper()
282 if v, _ := strconv.ParseBool(os.Getenv("GO_BUILDER_FLAKY_NET")); v {
283 t.Skip("skipping test on builder known to have frequent network failures")
284 }
285 }
286
287 // CleanCmdEnv will fill cmd.Env with the environment, excluding certain
288 // variables that could modify the behavior of the Go tools such as
289 // GODEBUG and GOTRACEBACK.
290 func CleanCmdEnv(cmd *exec.Cmd) *exec.Cmd {
291 if cmd.Env != nil {
292 panic("environment already set")
293 }
294 for _, env := range os.Environ() {
295 // Exclude GODEBUG from the environment to prevent its output
296 // from breaking tests that are trying to parse other command output.
297 if strings.HasPrefix(env, "GODEBUG=") {
298 continue
299 }
300 // Exclude GOTRACEBACK for the same reason.
301 if strings.HasPrefix(env, "GOTRACEBACK=") {
302 continue
303 }
304 cmd.Env = append(cmd.Env, env)
305 }
306 return cmd
307 }
308
309 // CPUIsSlow reports whether the CPU running the test is suspected to be slow.
310 func CPUIsSlow() bool {
311 switch runtime.GOARCH {
312 case "arm", "mips", "mipsle", "mips64", "mips64le":
313 return true
314 }
315 return false
316 }
317
318 // SkipIfShortAndSlow skips t if -short is set and the CPU running the test is
319 // suspected to be slow.
320 //
321 // (This is useful for CPU-intensive tests that otherwise complete quickly.)
322 func SkipIfShortAndSlow(t testing.TB) {
323 if testing.Short() && CPUIsSlow() {
324 t.Helper()
325 t.Skipf("skipping test in -short mode on %s", runtime.GOARCH)
326 }
327 }
328
329 // RunWithTimeout runs cmd and returns its combined output. If the
330 // subprocess exits with a non-zero status, it will log that status
331 // and return a non-nil error, but this is not considered fatal.
332 func RunWithTimeout(t testing.TB, cmd *exec.Cmd) ([]byte, error) {
333 args := cmd.Args
334 if args == nil {
335 args = []string{cmd.Path}
336 }
337
338 var b bytes.Buffer
339 cmd.Stdout = &b
340 cmd.Stderr = &b
341 if err := cmd.Start(); err != nil {
342 t.Fatalf("starting %s: %v", args, err)
343 }
344
345 // If the process doesn't complete within 1 minute,
346 // assume it is hanging and kill it to get a stack trace.
347 p := cmd.Process
348 done := make(chan bool)
349 go func() {
350 scale := 1
351 // This GOARCH/GOOS test is copied from cmd/dist/test.go.
352 // TODO(iant): Have cmd/dist update the environment variable.
353 if runtime.GOARCH == "arm" || runtime.GOOS == "windows" {
354 scale = 2
355 }
356 if s := os.Getenv("GO_TEST_TIMEOUT_SCALE"); s != "" {
357 if sc, err := strconv.Atoi(s); err == nil {
358 scale = sc
359 }
360 }
361
362 select {
363 case <-done:
364 case <-time.After(time.Duration(scale) * time.Minute):
365 p.Signal(Sigquit)
366 // If SIGQUIT doesn't do it after a little
367 // while, kill the process.
368 select {
369 case <-done:
370 case <-time.After(time.Duration(scale) * 30 * time.Second):
371 p.Signal(os.Kill)
372 }
373 }
374 }()
375
376 err := cmd.Wait()
377 if err != nil {
378 t.Logf("%s exit status: %v", args, err)
379 }
380 close(done)
381
382 return b.Bytes(), err
383 }