Debian Codegraph @

debian/go/src/golang.org/x/telemetry/internal/testenv/testenv.go

raw symbols SCIP
1 // Copyright 2023 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 "bytes"
11 "fmt"
12 "go/build"
13 "os/exec"
14 "runtime"
15 "sync"
16 "testing"
17
18 "golang.org/x/telemetry/internal/telemetry"
19 )
20
21 // NeedsLocalhostNet skips t if networking does not work for ports opened
22 // with "localhost".
23 func NeedsLocalhostNet(t testing.TB) {
24 switch runtime.GOOS {
25 case "js", "wasip1":
26 t.Skipf(`Listening on "localhost" fails on %s; see https://go.dev/issue/59718`, runtime.GOOS)
27 }
28 }
29
30 var (
31 hasGoOnce sync.Once
32 hasGoErr error
33 )
34
35 // HasGo checks whether the current system has 'go'.
36 func HasGo() error {
37 hasGoOnce.Do(func() {
38 cmd := exec.Command("go", "env", "GOROOT")
39 out, err := cmd.Output()
40 if err != nil { // cannot run go.
41 hasGoErr = fmt.Errorf("%v: %v", cmd, err)
42 return
43 }
44 out = bytes.TrimSpace(out)
45 if len(out) == 0 { // unusual, incomplete go installation.
46 hasGoErr = fmt.Errorf("%v: no GOROOT - incomplete go installation", cmd)
47 }
48 })
49 return hasGoErr
50 }
51
52 // NeedsGo skips t if the current system does not have 'go' or
53 // cannot run them with exec.Command.
54 func NeedsGo(t testing.TB) {
55 if err := HasGo(); err != nil {
56 t.Skipf("skipping test: go is not available - %v", err)
57 }
58 }
59
60 // SkipIfUnsupportedPlatform skips test if the current os/arch
61 // are not support.
62 func SkipIfUnsupportedPlatform(t testing.TB) {
63 t.Helper()
64 if telemetry.DisabledOnPlatform {
65 t.Skip("telemetry is unsupported on this platform")
66 }
67 }
68
69 // MustHaveExec checks that the current system can start new processes
70 // using os.StartProcess or (more commonly) exec.Command.
71 // If not, MustHaveExec calls t.Skip with an explanation.
72 func MustHaveExec(t testing.TB) {
73 switch runtime.GOOS {
74 case "wasip1", "js", "ios":
75 t.Skipf("skipping test: may not be able to exec subprocess on %s/%s", runtime.GOOS, runtime.GOARCH)
76 }
77 }
78
79 // Go1Point returns the x in Go 1.x.
80 func Go1Point() int {
81 for i := len(build.Default.ReleaseTags) - 1; i >= 0; i-- {
82 var version int
83 if _, err := fmt.Sscanf(build.Default.ReleaseTags[i], "go1.%d", &version); err != nil {
84 continue
85 }
86 return version
87 }
88 panic("bad release tags")
89 }
90
91 // NeedsGo1Point skips t if the Go version used to run the test is older than
92 // 1.x.
93 func NeedsGo1Point(t testing.TB, x int) {
94 if Go1Point() < x {
95 t.Helper()
96 t.Skipf("running Go version %q is version 1.%d, older than required 1.%d", runtime.Version(), Go1Point(), x)
97 }
98 }