Debian Codegraph @

tpl/internal/go_templates/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 "fmt"
18 "github.com/gohugoio/hugo/tpl/internal/go_templates/cfg"
19 "os"
20 "os/exec"
21 "path/filepath"
22 "runtime"
23 "strconv"
24 "strings"
25 "sync"
26 "testing"
27 )
28
29 // Save the original environment during init for use in checks. A test
30 // binary may modify its environment before calling HasExec to change its
31 // behavior (such as mimicking a command-line tool), and that modified
32 // environment might cause environment checks to behave erratically.
33 var origEnv = os.Environ()
34
35 // Builder reports the name of the builder running this test. For example,
36 // "gotip-linux-amd64_avx512-test_only" or "go1.24-windows-arm64" on LUCI,
37 // or "linux-amd64" on our old infrastructure. Prefer using runtime.GOOS,
38 // runtime.GOARCH, race.Enabled, reading the OS version, checking CPU
39 // feature flags with internal/cpu, etc. over parsing builder names when
40 // possible. When matching builder names, prefer a fuzzy match instead
41 // of a strict comparison.
42 // If the test is not running on the build infrastructure,
43 // Builder returns the empty string.
44 func Builder() string {
45 return os.Getenv("GO_BUILDER_NAME")
46 }
47
48 // HasGoBuild reports whether the current system can build programs with “go build”
49 // and then run them with os.StartProcess or exec.Command.
50 func HasGoBuild() bool {
51 if os.Getenv("GO_GCFLAGS") != "" {
52 // It's too much work to require every caller of the go command
53 // to pass along "-gcflags="+os.Getenv("GO_GCFLAGS").
54 // For now, if $GO_GCFLAGS is set, report that we simply can't
55 // run go build.
56 return false
57 }
58
59 return tryGoBuild() == nil
60 }
61
62 var tryGoBuild = sync.OnceValue(func() error {
63 return nil
64 })
65
66 // MustHaveGoBuild checks that the current system can build programs with “go build”
67 // and then run them with os.StartProcess or exec.Command.
68 // If not, MustHaveGoBuild calls t.Skip with an explanation.
69 func MustHaveGoBuild(t testing.TB) {
70 if os.Getenv("GO_GCFLAGS") != "" {
71 t.Helper()
72 t.Skipf("skipping test: 'go build' not compatible with setting $GO_GCFLAGS")
73 }
74 if !HasGoBuild() {
75 t.Helper()
76 t.Skipf("skipping test: 'go build' unavailable: %v", tryGoBuild())
77 }
78 }
79
80 // HasGoRun reports whether the current system can run programs with “go run”.
81 func HasGoRun() bool {
82 // For now, having go run and having go build are the same.
83 return HasGoBuild()
84 }
85
86 // MustHaveGoRun checks that the current system can run programs with “go run”.
87 // If not, MustHaveGoRun calls t.Skip with an explanation.
88 func MustHaveGoRun(t testing.TB) {
89 if !HasGoRun() {
90 t.Helper()
91 t.Skipf("skipping test: 'go run' not available on %s/%s", runtime.GOOS, runtime.GOARCH)
92 }
93 }
94
95 // HasParallelism reports whether the current system can execute multiple
96 // threads in parallel.
97 // There is a copy of this function in cmd/dist/test.go.
98 func HasParallelism() bool {
99 switch runtime.GOOS {
100 case "js", "wasip1":
101 return false
102 }
103 return true
104 }
105
106 // MustHaveParallelism checks that the current system can execute multiple
107 // threads in parallel. If not, MustHaveParallelism calls t.Skip with an explanation.
108 func MustHaveParallelism(t testing.TB) {
109 if !HasParallelism() {
110 t.Helper()
111 t.Skipf("skipping test: no parallelism available on %s/%s", runtime.GOOS, runtime.GOARCH)
112 }
113 }
114
115 // GoToolPath reports the path to the Go tool.
116 // It is a convenience wrapper around GoTool.
117 // If the tool is unavailable GoToolPath calls t.Skip.
118 // If the tool should be available and isn't, GoToolPath calls t.Fatal.
119 func GoToolPath(t testing.TB) string {
120 MustHaveGoBuild(t)
121 path, err := GoTool()
122 if err != nil {
123 t.Fatal(err)
124 }
125 // Add all environment variables that affect the Go command to test metadata.
126 // Cached test results will be invalidate when these variables change.
127 // See golang.org/issue/32285.
128 for _, envVar := range strings.Fields(cfg.KnownEnv) {
129 os.Getenv(envVar)
130 }
131 return path
132 }
133
134 var findGOROOT = sync.OnceValues(func() (path string, err error) {
135 if path := runtime.GOROOT(); path != "" {
136 // If runtime.GOROOT() is non-empty, assume that it is valid.
137 //
138 // (It might not be: for example, the user may have explicitly set GOROOT
139 // to the wrong directory. But this case is
140 // rare, and if that happens the user can fix what they broke.)
141 return path, nil
142 }
143
144 // runtime.GOROOT doesn't know where GOROOT is (perhaps because the test
145 // binary was built with -trimpath).
146 //
147 // Since this is internal/testenv, we can cheat and assume that the caller
148 // is a test of some package in a subdirectory of GOROOT/src. ('go test'
149 // runs the test in the directory containing the packaged under test.) That
150 // means that if we start walking up the tree, we should eventually find
151 // GOROOT/src/go.mod, and we can report the parent directory of that.
152 //
153 // Notably, this works even if we can't run 'go env GOROOT' as a
154 // subprocess.
155
156 cwd, err := os.Getwd()
157 if err != nil {
158 return "", fmt.Errorf("finding GOROOT: %w", err)
159 }
160
161 dir := cwd
162 for {
163 parent := filepath.Dir(dir)
164 if parent == dir {
165 // dir is either "." or only a volume name.
166 return "", fmt.Errorf("failed to locate GOROOT/src in any parent directory")
167 }
168
169 if base := filepath.Base(dir); base != "src" {
170 dir = parent
171 continue // dir cannot be GOROOT/src if it doesn't end in "src".
172 }
173
174 b, err := os.ReadFile(filepath.Join(dir, "go.mod"))
175 if err != nil {
176 if os.IsNotExist(err) {
177 dir = parent
178 continue
179 }
180 return "", fmt.Errorf("finding GOROOT: %w", err)
181 }
182 goMod := string(b)
183
184 for goMod != "" {
185 var line string
186 line, goMod, _ = strings.Cut(goMod, "\n")
187 fields := strings.Fields(line)
188 if len(fields) >= 2 && fields[0] == "module" && fields[1] == "std" {
189 // Found "module std", which is the module declaration in GOROOT/src!
190 return parent, nil
191 }
192 }
193 }
194 })
195
196 // GOROOT reports the path to the directory containing the root of the Go
197 // project source tree. This is normally equivalent to runtime.GOROOT, but
198 // works even if the test binary was built with -trimpath and cannot exec
199 // 'go env GOROOT'.
200 //
201 // If GOROOT cannot be found, GOROOT skips t if t is non-nil,
202 // or panics otherwise.
203 func GOROOT(t testing.TB) string {
204 path, err := findGOROOT()
205 if err != nil {
206 if t == nil {
207 panic(err)
208 }
209 t.Helper()
210 t.Skip(err)
211 }
212 return path
213 }
214
215 // GoTool reports the path to the Go tool.
216 func GoTool() (string, error) {
217 if !HasGoBuild() {
218 return "", errors.New("platform cannot run go tool")
219 }
220 return goTool()
221 }
222
223 var goTool = sync.OnceValues(func() (string, error) {
224 return exec.LookPath("go")
225 })
226
227 // MustHaveSource checks that the entire source tree is available under GOROOT.
228 // If not, it calls t.Skip with an explanation.
229 func MustHaveSource(t testing.TB) {
230 switch runtime.GOOS {
231 case "ios":
232 t.Helper()
233 t.Skip("skipping test: no source tree on " + runtime.GOOS)
234 }
235 }
236
237 // HasExternalNetwork reports whether the current system can use
238 // external (non-localhost) networks.
239 func HasExternalNetwork() bool {
240 return !testing.Short() && runtime.GOOS != "js" && runtime.GOOS != "wasip1"
241 }
242
243 // MustHaveExternalNetwork checks that the current system can use
244 // external (non-localhost) networks.
245 // If not, MustHaveExternalNetwork calls t.Skip with an explanation.
246 func MustHaveExternalNetwork(t testing.TB) {
247 if runtime.GOOS == "js" || runtime.GOOS == "wasip1" {
248 t.Helper()
249 t.Skipf("skipping test: no external network on %s", runtime.GOOS)
250 }
251 if testing.Short() {
252 t.Helper()
253 t.Skipf("skipping test: no external network in -short mode")
254 }
255 }
256
257 // HasCGO reports whether the current system can use cgo.
258 func HasCGO() bool {
259 return hasCgo()
260 }
261
262 var hasCgo = sync.OnceValue(func() bool {
263 goTool, err := goTool()
264 if err != nil {
265 return false
266 }
267 cmd := exec.Command(goTool, "env", "CGO_ENABLED")
268 cmd.Env = origEnv
269 out, err := cmd.Output()
270 if err != nil {
271 panic(fmt.Sprintf("%v: %v", cmd, out))
272 }
273 ok, err := strconv.ParseBool(string(bytes.TrimSpace(out)))
274 if err != nil {
275 panic(fmt.Sprintf("%v: non-boolean output %q", cmd, out))
276 }
277 return ok
278 })
279
280 // MustHaveCGO calls t.Skip if cgo is not available.
281 func MustHaveCGO(t testing.TB) {
282 if !HasCGO() {
283 t.Helper()
284 t.Skipf("skipping test: no cgo")
285 }
286 }
287
288 // CanInternalLink reports whether the current system can link programs with
289 // internal linking.
290 func CanInternalLink(withCgo bool) bool {
291 return false
292 }
293
294 // SpecialBuildTypes are interesting build types that may affect linking.
295 type SpecialBuildTypes struct {
296 Cgo bool
297 Asan bool
298 Msan bool
299 Race bool
300 }
301
302 // NoSpecialBuildTypes indicates a standard, no cgo go build.
303 var NoSpecialBuildTypes SpecialBuildTypes
304
305 // MustInternalLink checks that the current system can link programs with internal
306 // linking.
307 // If not, MustInternalLink calls t.Skip with an explanation.
308 func MustInternalLink(t testing.TB, with SpecialBuildTypes) {
309 if with.Asan || with.Msan || with.Race {
310 t.Skipf("skipping test: internal linking with sanitizers is not supported")
311 }
312 if !CanInternalLink(with.Cgo) {
313 t.Helper()
314 if with.Cgo && CanInternalLink(false) {
315 t.Skipf("skipping test: internal linking on %s/%s is not supported with cgo", runtime.GOOS, runtime.GOARCH)
316 }
317 t.Skipf("skipping test: internal linking on %s/%s is not supported", runtime.GOOS, runtime.GOARCH)
318 }
319 }
320
321 // MustInternalLinkPIE checks whether the current system can link PIE binary using
322 // internal linking.
323 // If not, MustInternalLinkPIE calls t.Skip with an explanation.
324 func MustInternalLinkPIE(t testing.TB) {
325 }
326
327 // MustHaveBuildMode reports whether the current system can build programs in
328 // the given build mode.
329 // If not, MustHaveBuildMode calls t.Skip with an explanation.
330 func MustHaveBuildMode(t testing.TB, buildmode string) {
331 }
332
333 // HasSymlink reports whether the current system can use os.Symlink.
334 func HasSymlink() bool {
335 ok, _ := hasSymlink()
336 return ok
337 }
338
339 // MustHaveSymlink reports whether the current system can use os.Symlink.
340 // If not, MustHaveSymlink calls t.Skip with an explanation.
341 func MustHaveSymlink(t testing.TB) {
342 ok, reason := hasSymlink()
343 if !ok {
344 t.Helper()
345 t.Skipf("skipping test: cannot make symlinks on %s/%s: %s", runtime.GOOS, runtime.GOARCH, reason)
346 }
347 }
348
349 // HasLink reports whether the current system can use os.Link.
350 func HasLink() bool {
351 // From Android release M (Marshmallow), hard linking files is blocked
352 // and an attempt to call link() on a file will return EACCES.
353 // - https://code.google.com/p/android-developer-preview/issues/detail?id=3150
354 return runtime.GOOS != "plan9" && runtime.GOOS != "android"
355 }
356
357 // MustHaveLink reports whether the current system can use os.Link.
358 // If not, MustHaveLink calls t.Skip with an explanation.
359 func MustHaveLink(t testing.TB) {
360 if !HasLink() {
361 t.Helper()
362 t.Skipf("skipping test: hardlinks are not supported on %s/%s", runtime.GOOS, runtime.GOARCH)
363 }
364 }
365
366 var flaky = flag.Bool("flaky", false, "run known-flaky tests too")
367
368 func SkipFlaky(t testing.TB, issue int) {
369 if !*flaky {
370 t.Helper()
371 t.Skipf("skipping known flaky test without the -flaky flag; see golang.org/issue/%d", issue)
372 }
373 }
374
375 func SkipFlakyNet(t testing.TB) {
376 if v, _ := strconv.ParseBool(os.Getenv("GO_BUILDER_FLAKY_NET")); v {
377 t.Helper()
378 t.Skip("skipping test on builder known to have frequent network failures")
379 }
380 }
381
382 // CPUIsSlow reports whether the CPU running the test is suspected to be slow.
383 func CPUIsSlow() bool {
384 switch runtime.GOARCH {
385 case "arm", "mips", "mipsle", "mips64", "mips64le", "wasm":
386 return true
387 }
388 return false
389 }
390
391 // SkipIfShortAndSlow skips t if -short is set and the CPU running the test is
392 // suspected to be slow.
393 //
394 // (This is useful for CPU-intensive tests that otherwise complete quickly.)
395 func SkipIfShortAndSlow(t testing.TB) {
396 if testing.Short() && CPUIsSlow() {
397 t.Helper()
398 t.Skipf("skipping test in -short mode on %s", runtime.GOARCH)
399 }
400 }
401
402 // SkipIfOptimizationOff skips t if optimization is disabled.
403 func SkipIfOptimizationOff(t testing.TB) {
404 if OptimizationOff() {
405 t.Helper()
406 t.Skip("skipping test with optimization disabled")
407 }
408 }
409
410 // WriteImportcfg writes an importcfg file used by the compiler or linker to
411 // dstPath containing entries for the file mappings in packageFiles, as well
412 // as for the packages transitively imported by the package(s) in pkgs.
413 //
414 // pkgs may include any package pattern that is valid to pass to 'go list',
415 // so it may also be a list of Go source files all in the same directory.
416 func WriteImportcfg(t testing.TB, dstPath string, packageFiles map[string]string, pkgs ...string) {
417 t.Helper()
418
419 icfg := new(bytes.Buffer)
420 icfg.WriteString("# import config\n")
421 for k, v := range packageFiles {
422 fmt.Fprintf(icfg, "packagefile %s=%s\n", k, v)
423 }
424
425 if len(pkgs) > 0 {
426 // Use 'go list' to resolve any missing packages and rewrite the import map.
427 cmd := Command(t, GoToolPath(t), "list", "-export", "-deps", "-f", `{{if ne .ImportPath "command-line-arguments"}}{{if .Export}}{{.ImportPath}}={{.Export}}{{end}}{{end}}`)
428 cmd.Args = append(cmd.Args, pkgs...)
429 cmd.Stderr = new(strings.Builder)
430 out, err := cmd.Output()
431 if err != nil {
432 t.Fatalf("%v: %v\n%s", cmd, err, cmd.Stderr)
433 }
434
435 for line := range strings.SplitSeq(string(out), "\n") {
436 if line == "" {
437 continue
438 }
439 importPath, export, ok := strings.Cut(line, "=")
440 if !ok {
441 t.Fatalf("invalid line in output from %v:\n%s", cmd, line)
442 }
443 if packageFiles[importPath] == "" {
444 fmt.Fprintf(icfg, "packagefile %s=%s\n", importPath, export)
445 }
446 }
447 }
448
449 if err := os.WriteFile(dstPath, icfg.Bytes(), 0666); err != nil {
450 t.Fatal(err)
451 }
452 }
453
454 // SyscallIsNotSupported reports whether err may indicate that a system call is
455 // not supported by the current platform or execution environment.
456 func SyscallIsNotSupported(err error) bool {
457 return syscallIsNotSupported(err)
458 }
459
460 // CPUProfilingBroken returns true if CPU profiling has known issues on this
461 // platform.
462 func CPUProfilingBroken() bool {
463 switch runtime.GOOS {
464 case "plan9":
465 // Profiling unimplemented.
466 return true
467 case "aix":
468 // See https://golang.org/issue/45170.
469 return true
470 case "ios", "dragonfly", "netbsd", "illumos", "solaris":
471 // See https://golang.org/issue/13841.
472 return true
473 case "openbsd":
474 if runtime.GOARCH == "arm" || runtime.GOARCH == "arm64" {
475 // See https://golang.org/issue/13841.
476 return true
477 }
478 }
479
480 return false
481 }