Debian Codegraph @

internal/testenv/testenv.go

raw symbols SCIP
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 // Package testenv contains helper functions for skipping tests
6 // based on which tools are present in the environment.
7 package testenv
8
9 import (
10 "bufio"
11 "bytes"
12 "context"
13 "fmt"
14 "go/build"
15 "log"
16 "os"
17 "os/exec"
18 "path/filepath"
19 "runtime"
20 "runtime/debug"
21 "slices"
22 "strings"
23 "sync"
24 "testing"
25 "time"
26
27 "golang.org/x/mod/modfile"
28 "golang.org/x/tools/internal/gocommand"
29 )
30
31 // packageMainIsDevel reports whether the module containing package main
32 // is a development version (if module information is available).
33 func packageMainIsDevel() bool {
34 info, ok := debug.ReadBuildInfo()
35 if !ok {
36 // Most test binaries currently lack build info, but this should become more
37 // permissive once https://golang.org/issue/33976 is fixed.
38 return true
39 }
40
41 // Note: info.Main.Version describes the version of the module containing
42 // package main, not the version of “the main module”.
43 // See https://golang.org/issue/33975.
44 return info.Main.Version == "(devel)"
45 }
46
47 var checkGoBuild struct {
48 once sync.Once
49 err error
50 }
51
52 // HasTool reports an error if the required tool is not available in PATH.
53 //
54 // For certain tools, it checks that the tool executable is correct.
55 func HasTool(tool string) error {
56 if tool == "cgo" {
57 enabled, err := cgoEnabled(false)
58 if err != nil {
59 return fmt.Errorf("checking cgo: %v", err)
60 }
61 if !enabled {
62 return fmt.Errorf("cgo not enabled")
63 }
64 return nil
65 }
66
67 _, err := exec.LookPath(tool)
68 if err != nil {
69 return err
70 }
71
72 switch tool {
73 case "patch":
74 // check that the patch tools supports the -o argument
75 temp, err := os.CreateTemp("", "patch-test")
76 if err != nil {
77 return err
78 }
79 temp.Close()
80 defer os.Remove(temp.Name())
81 cmd := exec.Command(tool, "-o", temp.Name())
82 if err := cmd.Run(); err != nil {
83 return err
84 }
85
86 case "go":
87 checkGoBuild.once.Do(func() {
88 if runtime.GOROOT() != "" {
89 // Ensure that the 'go' command found by exec.LookPath is from the correct
90 // GOROOT. Otherwise, 'some/path/go test ./...' will test against some
91 // version of the 'go' binary other than 'some/path/go', which is almost
92 // certainly not what the user intended.
93 out, err := exec.Command(tool, "env", "GOROOT").Output()
94 if err != nil {
95 if exit, ok := err.(*exec.ExitError); ok && len(exit.Stderr) > 0 {
96 err = fmt.Errorf("%w\nstderr:\n%s)", err, exit.Stderr)
97 }
98 checkGoBuild.err = err
99 return
100 }
101 GOROOT := strings.TrimSpace(string(out))
102 if GOROOT != runtime.GOROOT() {
103 checkGoBuild.err = fmt.Errorf("'go env GOROOT' does not match runtime.GOROOT:\n\tgo env: %s\n\tGOROOT: %s", GOROOT, runtime.GOROOT())
104 return
105 }
106 }
107
108 dir, err := os.MkdirTemp("", "testenv-*")
109 if err != nil {
110 checkGoBuild.err = err
111 return
112 }
113 defer os.RemoveAll(dir)
114
115 mainGo := filepath.Join(dir, "main.go")
116 if err := os.WriteFile(mainGo, []byte("package main\nfunc main() {}\n"), 0644); err != nil {
117 checkGoBuild.err = err
118 return
119 }
120 cmd := exec.Command("go", "build", "-o", os.DevNull, mainGo)
121 cmd.Dir = dir
122 if out, err := cmd.CombinedOutput(); err != nil {
123 if len(out) > 0 {
124 checkGoBuild.err = fmt.Errorf("%v: %v\n%s", cmd, err, out)
125 } else {
126 checkGoBuild.err = fmt.Errorf("%v: %v", cmd, err)
127 }
128 }
129 })
130 if checkGoBuild.err != nil {
131 return checkGoBuild.err
132 }
133
134 case "diff":
135 // Check that diff is the GNU or Apple version, needed for the -u argument and
136 // to report missing newlines at the end of files.
137 out, err := exec.Command(tool, "-version").Output()
138 if err != nil {
139 out, _ = exec.Command(tool, "--version").Output()
140 if bytes.Contains(out, []byte("Apple diff")) {
141 return nil
142 }
143 return err
144 }
145 if !bytes.Contains(out, []byte("GNU diffutils")) {
146 return fmt.Errorf("diff is not the GNU version")
147 }
148 }
149
150 return nil
151 }
152
153 func cgoEnabled(bypassEnvironment bool) (bool, error) {
154 cmd := exec.Command("go", "env", "CGO_ENABLED")
155 if bypassEnvironment {
156 cmd.Env = append(os.Environ(), "CGO_ENABLED=")
157 }
158 out, err := cmd.Output()
159 if err != nil {
160 if exit, ok := err.(*exec.ExitError); ok && len(exit.Stderr) > 0 {
161 err = fmt.Errorf("%w\nstderr:\n%s", err, exit.Stderr)
162 }
163 return false, err
164 }
165 enabled := strings.TrimSpace(string(out))
166 return enabled == "1", nil
167 }
168
169 func allowMissingTool(tool string) bool {
170 switch runtime.GOOS {
171 case "aix", "darwin", "dragonfly", "freebsd", "illumos", "linux", "netbsd", "openbsd", "plan9", "solaris", "windows":
172 // Known non-mobile OS. Expect a reasonably complete environment.
173 default:
174 return true
175 }
176
177 switch tool {
178 case "cgo":
179 if strings.HasSuffix(os.Getenv("GO_BUILDER_NAME"), "-nocgo") {
180 // Explicitly disabled on -nocgo builders.
181 return true
182 }
183 if enabled, err := cgoEnabled(true); err == nil && !enabled {
184 // No platform support.
185 return true
186 }
187 case "go":
188 if os.Getenv("GO_BUILDER_NAME") == "illumos-amd64-joyent" {
189 // Work around a misconfigured builder (see https://golang.org/issue/33950).
190 return true
191 }
192 case "diff":
193 if os.Getenv("GO_BUILDER_NAME") != "" {
194 return true
195 }
196 case "patch":
197 if os.Getenv("GO_BUILDER_NAME") != "" {
198 return true
199 }
200 }
201
202 // If a developer is actively working on this test, we expect them to have all
203 // of its dependencies installed. However, if it's just a dependency of some
204 // other module (for example, being run via 'go test all'), we should be more
205 // tolerant of unusual environments.
206 return !packageMainIsDevel()
207 }
208
209 // NeedsTool skips t if the named tool is not present in the path.
210 // As a special case, "cgo" means "go" is present and can compile cgo programs.
211 func NeedsTool(t testing.TB, tool string) {
212 err := HasTool(tool)
213 if err == nil {
214 return
215 }
216
217 t.Helper()
218 if allowMissingTool(tool) {
219 // TODO(adonovan): if we skip because of (e.g.)
220 // mismatched go env GOROOT and runtime.GOROOT, don't
221 // we risk some users not getting the coverage they expect?
222 // bcmills notes: this shouldn't be a concern as of CL 404134 (Go 1.19).
223 // We could probably safely get rid of that GOPATH consistency
224 // check entirely at this point.
225 t.Skipf("skipping because %s tool not available: %v", tool, err)
226 } else {
227 t.Fatalf("%s tool not available: %v", tool, err)
228 }
229 }
230
231 // NeedsGoPackages skips t if the go/packages driver (or 'go' tool) implied by
232 // the current process environment is not present in the path.
233 func NeedsGoPackages(t testing.TB) {
234 t.Helper()
235
236 tool := os.Getenv("GOPACKAGESDRIVER")
237 switch tool {
238 case "off":
239 // "off" forces go/packages to use the go command.
240 tool = "go"
241 case "":
242 if _, err := exec.LookPath("gopackagesdriver"); err == nil {
243 tool = "gopackagesdriver"
244 } else {
245 tool = "go"
246 }
247 }
248
249 NeedsTool(t, tool)
250 }
251
252 // NeedsGoPackagesEnv skips t if the go/packages driver (or 'go' tool) implied
253 // by env is not present in the path.
254 func NeedsGoPackagesEnv(t testing.TB, env []string) {
255 t.Helper()
256
257 for _, v := range env {
258 if after, ok := strings.CutPrefix(v, "GOPACKAGESDRIVER="); ok {
259 tool := after
260 if tool == "off" {
261 NeedsTool(t, "go")
262 } else {
263 NeedsTool(t, tool)
264 }
265 return
266 }
267 }
268
269 NeedsGoPackages(t)
270 }
271
272 // NeedsGoBuild skips t if the current system can't build programs with “go build”
273 // and then run them with os.StartProcess or exec.Command.
274 // Android doesn't have the userspace go build needs to run,
275 // and js/wasm doesn't support running subprocesses.
276 func NeedsGoBuild(t testing.TB) {
277 t.Helper()
278
279 // This logic was derived from internal/testing.HasGoBuild and
280 // may need to be updated as that function evolves.
281
282 NeedsTool(t, "go")
283 }
284
285 // NeedsDefaultImporter skips t if the test uses the default importer,
286 // returned by [go/importer.Default].
287 func NeedsDefaultImporter(t testing.TB) {
288 t.Helper()
289 // The default importer may call `go list`
290 // (in src/internal/exportdata/exportdata.go:lookupGorootExport),
291 // so check for the go tool.
292 NeedsTool(t, "go")
293 }
294
295 // ExitIfSmallMachine emits a helpful diagnostic and calls os.Exit(0) if the
296 // current machine is a builder known to have scarce resources.
297 //
298 // It should be called from within a TestMain function.
299 func ExitIfSmallMachine() {
300 switch b := os.Getenv("GO_BUILDER_NAME"); b {
301 case "linux-arm-scaleway":
302 // "linux-arm" was renamed to "linux-arm-scaleway" in CL 303230.
303 fmt.Fprintln(os.Stderr, "skipping test: linux-arm-scaleway builder lacks sufficient memory (https://golang.org/issue/32834)")
304 case "plan9-arm":
305 fmt.Fprintln(os.Stderr, "skipping test: plan9-arm builder lacks sufficient memory (https://golang.org/issue/38772)")
306 case "netbsd-arm-bsiegert", "netbsd-arm64-bsiegert":
307 // As of 2021-06-02, these builders are running with GO_TEST_TIMEOUT_SCALE=10,
308 // and there is only one of each. We shouldn't waste those scarce resources
309 // running very slow tests.
310 fmt.Fprintf(os.Stderr, "skipping test: %s builder is very slow\n", b)
311 case "dragonfly-amd64":
312 // As of 2021-11-02, this builder is running with GO_TEST_TIMEOUT_SCALE=2,
313 // and seems to have unusually slow disk performance.
314 fmt.Fprintln(os.Stderr, "skipping test: dragonfly-amd64 has slow disk (https://golang.org/issue/45216)")
315 case "linux-riscv64-unmatched":
316 // As of 2021-11-03, this builder is empirically not fast enough to run
317 // gopls tests. Ideally we should make the tests faster in short mode
318 // and/or fix them to not assume arbitrary deadlines.
319 // For now, we'll skip them instead.
320 fmt.Fprintf(os.Stderr, "skipping test: %s builder is too slow (https://golang.org/issue/49321)\n", b)
321 default:
322 switch runtime.GOOS {
323 case "android", "ios":
324 fmt.Fprintf(os.Stderr, "skipping test: assuming that %s is resource-constrained\n", runtime.GOOS)
325 default:
326 return
327 }
328 }
329 os.Exit(0)
330 }
331
332 // Go1Point returns the x in Go 1.x.
333 func Go1Point() int {
334 for _, tag := range slices.Backward(build.Default.ReleaseTags) {
335 var version int
336 if _, err := fmt.Sscanf(tag, "go1.%d", &version); err != nil {
337 continue
338 }
339 return version
340 }
341 panic("bad release tags")
342 }
343
344 // NeedsGoCommand1Point skips t if the ambient go command version in the PATH
345 // of the current process is older than 1.x.
346 //
347 // NeedsGoCommand1Point memoizes the result of running the go command, so
348 // should be called after all mutations of PATH.
349 func NeedsGoCommand1Point(t testing.TB, x int) {
350 NeedsTool(t, "go")
351 go1point, err := goCommand1Point()
352 if err != nil {
353 panic(fmt.Sprintf("unable to determine go version: %v", err))
354 }
355 if go1point < x {
356 t.Helper()
357 t.Skipf("go command is version 1.%d, older than required 1.%d", go1point, x)
358 }
359 }
360
361 var (
362 goCommand1PointOnce sync.Once
363 goCommand1Point_ int
364 goCommand1PointErr error
365 )
366
367 func goCommand1Point() (int, error) {
368 goCommand1PointOnce.Do(func() {
369 goCommand1Point_, goCommand1PointErr = gocommand.GoVersion(context.Background(), gocommand.Invocation{}, new(gocommand.Runner))
370 })
371 return goCommand1Point_, goCommand1PointErr
372 }
373
374 // NeedsGo1Point skips t if the Go version used to run the test is older than
375 // 1.x.
376 func NeedsGo1Point(t testing.TB, x int) {
377 if Go1Point() < x {
378 t.Helper()
379 t.Skipf("running Go version %q is version 1.%d, older than required 1.%d", runtime.Version(), Go1Point(), x)
380 }
381 }
382
383 // SkipAfterGoCommand1Point skips t if the ambient go command version in the PATH of
384 // the current process is newer than 1.x.
385 //
386 // SkipAfterGoCommand1Point memoizes the result of running the go command, so
387 // should be called after any mutation of PATH.
388 func SkipAfterGoCommand1Point(t testing.TB, x int) {
389 NeedsTool(t, "go")
390 go1point, err := goCommand1Point()
391 if err != nil {
392 panic(fmt.Sprintf("unable to determine go version: %v", err))
393 }
394 if go1point > x {
395 t.Helper()
396 t.Skipf("go command is version 1.%d, newer than maximum 1.%d", go1point, x)
397 }
398 }
399
400 // SkipAfterGo1Point skips t if the Go version used to run the test is newer than
401 // 1.x.
402 func SkipAfterGo1Point(t testing.TB, x int) {
403 if Go1Point() > x {
404 t.Helper()
405 t.Skipf("running Go version %q is version 1.%d, newer than maximum 1.%d", runtime.Version(), Go1Point(), x)
406 }
407 }
408
409 // NeedsLocalhostNet skips t if networking does not work for ports opened
410 // with "localhost".
411 func NeedsLocalhostNet(t testing.TB) {
412 switch runtime.GOOS {
413 case "js", "wasip1":
414 t.Skipf(`Listening on "localhost" fails on %s; see https://go.dev/issue/59718`, runtime.GOOS)
415 }
416 }
417
418 // Deadline returns the deadline of t, if known,
419 // using the Deadline method added in Go 1.15.
420 func Deadline(t testing.TB) (time.Time, bool) {
421 td, ok := t.(interface {
422 Deadline() (time.Time, bool)
423 })
424 if !ok {
425 return time.Time{}, false
426 }
427 return td.Deadline()
428 }
429
430 var (
431 gorootOnce sync.Once
432 gorootPath string
433 gorootErr error
434 )
435
436 func findGOROOT() (string, error) {
437 gorootOnce.Do(func() {
438 gorootPath = runtime.GOROOT()
439 if gorootPath != "" {
440 // If runtime.GOROOT() is non-empty, assume that it is valid. (It might
441 // not be: for example, the user may have explicitly set GOROOT
442 // to the wrong directory.)
443 return
444 }
445
446 cmd := exec.Command("go", "env", "GOROOT")
447 out, err := cmd.Output()
448 if err != nil {
449 gorootErr = fmt.Errorf("%v: %v", cmd, err)
450 }
451 gorootPath = strings.TrimSpace(string(out))
452 })
453
454 return gorootPath, gorootErr
455 }
456
457 // GOROOT reports the path to the directory containing the root of the Go
458 // project source tree. This is normally equivalent to runtime.GOROOT, but
459 // works even if the test binary was built with -trimpath.
460 //
461 // If GOROOT cannot be found, GOROOT skips t if t is non-nil,
462 // or panics otherwise.
463 func GOROOT(t testing.TB) string {
464 path, err := findGOROOT()
465 if err != nil {
466 if t == nil {
467 panic(err)
468 }
469 t.Helper()
470 t.Skip(err)
471 }
472 return path
473 }
474
475 // NeedsLocalXTools skips t if the golang.org/x/tools module is replaced and
476 // its replacement directory does not exist (or does not contain the module).
477 func NeedsLocalXTools(t testing.TB) {
478 t.Helper()
479
480 NeedsTool(t, "go")
481
482 cmd := Command(t, "go", "list", "-f", "{{with .Replace}}{{.Dir}}{{end}}", "-m", "golang.org/x/tools")
483 out, err := cmd.Output()
484 if err != nil {
485 if ee, ok := err.(*exec.ExitError); ok && len(ee.Stderr) > 0 {
486 t.Skipf("skipping test: %v: %v\n%s", cmd, err, ee.Stderr)
487 }
488 t.Skipf("skipping test: %v: %v", cmd, err)
489 }
490
491 dir := string(bytes.TrimSpace(out))
492 if dir == "" {
493 // No replacement directory, and (since we didn't set -e) no error either.
494 // Maybe x/tools isn't replaced at all (as in a gopls release, or when
495 // using a go.work file that includes the x/tools module).
496 return
497 }
498
499 // We found the directory where x/tools would exist if we're in a clone of the
500 // repo. Is it there? (If not, we're probably in the module cache instead.)
501 modFilePath := filepath.Join(dir, "go.mod")
502 b, err := os.ReadFile(modFilePath)
503 if err != nil {
504 t.Skipf("skipping test: x/tools replacement not found: %v", err)
505 }
506 modulePath := modfile.ModulePath(b)
507
508 if want := "golang.org/x/tools"; modulePath != want {
509 t.Skipf("skipping test: %s module path is %q, not %q", modFilePath, modulePath, want)
510 }
511 }
512
513 // NeedsGoExperiment skips t if the current process environment does not
514 // have a GOEXPERIMENT flag set.
515 func NeedsGoExperiment(t testing.TB, flag string) {
516 t.Helper()
517
518 goexp := os.Getenv("GOEXPERIMENT")
519 set := false
520 for f := range strings.SplitSeq(goexp, ",") {
521 if f == "" {
522 continue
523 }
524 if f == "none" {
525 // GOEXPERIMENT=none disables all experiment flags.
526 set = false
527 break
528 }
529 val := true
530 if strings.HasPrefix(f, "no") {
531 f, val = f[2:], false
532 }
533 if f == flag {
534 set = val
535 }
536 }
537 if !set {
538 t.Skipf("skipping test: flag %q is not set in GOEXPERIMENT=%q", flag, goexp)
539 }
540 }
541
542 // NeedsGOROOTDir skips the test if GOROOT/dir does not exist, and GOROOT is a
543 // released version of Go (=has a VERSION file). Some GOROOT directories are
544 // removed by cmd/distpack.
545 //
546 // See also golang/go#70081.
547 func NeedsGOROOTDir(t *testing.T, dir string) {
548 gorootTest := filepath.Join(GOROOT(t), dir)
549 if _, err := os.Stat(gorootTest); os.IsNotExist(err) {
550 if _, err := os.Stat(filepath.Join(GOROOT(t), "VERSION")); err == nil {
551 t.Skipf("skipping: GOROOT/%s not present", dir)
552 }
553 }
554 }
555
556 // RedirectStderr causes os.Stderr (and the global logger) to be
557 // temporarily replaced so that writes to it are sent to t.Log.
558 // It is restored at test cleanup.
559 func RedirectStderr(t testing.TB) {
560 t.Setenv("RedirectStderr", "") // side effect: assert t.Parallel wasn't called
561
562 // TODO(adonovan): if https://go.dev/issue/59928 is accepted,
563 // simply set w = t.Output() and dispense with the pipe.
564 r, w, err := os.Pipe()
565 if err != nil {
566 t.Fatalf("pipe: %v", err)
567 }
568 done := make(chan struct{})
569 go func() {
570 for sc := bufio.NewScanner(r); sc.Scan(); {
571 t.Log(sc.Text())
572 }
573 r.Close()
574 close(done)
575 }()
576
577 // Also do the same for the global logger.
578 savedWriter, savedPrefix, savedFlags := log.Writer(), log.Prefix(), log.Flags()
579 log.SetPrefix("log: ")
580 log.SetOutput(w)
581 log.SetFlags(0)
582
583 oldStderr := os.Stderr
584 os.Stderr = w
585 t.Cleanup(func() {
586 w.Close() // ignore error
587 os.Stderr = oldStderr
588
589 log.SetOutput(savedWriter)
590 log.SetPrefix(savedPrefix)
591 log.SetFlags(savedFlags)
592
593 // Don't let test finish before final t.Log.
594 <-done
595 })
596 }