1
2
3
4
5 package test
6
7 import (
8 "bytes"
9 "context"
10 "errors"
11 "fmt"
12 "internal/coverage"
13 "internal/platform"
14 "io"
15 "io/fs"
16 "maps"
17 "os"
18 "os/exec"
19 "path/filepath"
20 "regexp"
21 "runtime"
22 "slices"
23 "strconv"
24 "strings"
25 "sync"
26 "sync/atomic"
27 "time"
28
29 "cmd/go/internal/base"
30 "cmd/go/internal/cache"
31 "cmd/go/internal/cfg"
32 "cmd/go/internal/load"
33 "cmd/go/internal/lockedfile"
34 "cmd/go/internal/modload"
35 "cmd/go/internal/search"
36 "cmd/go/internal/str"
37 "cmd/go/internal/trace"
38 "cmd/go/internal/work"
39 "cmd/internal/par"
40 "cmd/internal/test2json"
41
42 "golang.org/x/mod/module"
43 )
44
45
46 func init() {
47 CmdTest.Run = runTest
48 }
49
50 const testUsage = "go test [build/test flags] [packages] [build/test flags & test binary flags]"
51
52 var CmdTest = &base.Command{
53 CustomFlags: true,
54 UsageLine: testUsage,
55 Short: "test packages",
56 Long: `
57 'Go test' automates testing the packages named by the import paths.
58 It prints a summary of the test results in the format:
59
60 ok archive/tar 0.011s
61 FAIL archive/zip 0.022s
62 ok compress/gzip 0.033s
63 ...
64
65 followed by detailed output for each failed package.
66
67 'Go test' recompiles each package along with any files with names matching
68 the file pattern "*_test.go".
69 These additional files can contain test functions, benchmark functions, fuzz
70 tests and example functions. See 'go help testfunc' for more.
71 Each listed package causes the execution of a separate test binary.
72 Files whose names begin with "_" (including "_test.go") or "." are ignored.
73
74 Test files that declare a package with the suffix "_test" will be compiled as a
75 separate package, and then linked and run with the main test binary.
76
77 The go tool will ignore a directory named "testdata", making it available
78 to hold ancillary data needed by the tests.
79
80 As part of building a test binary, go test runs go vet on the package
81 and its test source files to identify significant problems. If go vet
82 finds any problems, go test reports those and does not run the test
83 binary. Only a high-confidence subset of the default go vet checks are
84 used. That subset is: atomic, bools, buildtag, directive, errorsas,
85 ifaceassert, nilfunc, printf, slog, stdversion, stringintconv, and tests.
86 You can see the documentation for these and other vet tests via
87 "go doc cmd/vet". To disable the running of go vet, use the -vet=off flag.
88 To run all checks, use the -vet=all flag.
89
90 All test output and summary lines are printed to the go command's
91 standard output, even if the test printed them to its own standard
92 error. (The go command's standard error is reserved for printing
93 errors building the tests.)
94
95 The go command places $GOROOT/bin at the beginning of $PATH
96 in the test's environment, so that tests that execute
97 'go' commands use the same 'go' as the parent 'go test' command.
98
99 Go test runs in two different modes:
100
101 The first, called local directory mode, occurs when go test is
102 invoked with no package arguments (for example, 'go test' or 'go
103 test -v'). In this mode, go test compiles the package sources and
104 tests found in the current directory and then runs the resulting
105 test binary. In this mode, caching (discussed below) is disabled.
106 After the package test finishes, go test prints a summary line
107 showing the test status ('ok' or 'FAIL'), package name, and elapsed
108 time.
109
110 The second, called package list mode, occurs when go test is invoked
111 with explicit package arguments (for example 'go test math', 'go
112 test ./...', and even 'go test .'). In this mode, go test compiles
113 and tests each of the packages listed on the command line. If a
114 package test passes, go test prints only the final 'ok' summary
115 line. If a package test fails, go test prints the full test output.
116 If invoked with the -bench or -v flag, go test prints the full
117 output even for passing package tests, in order to display the
118 requested benchmark results or verbose logging. After the package
119 tests for all of the listed packages finish, and their output is
120 printed, go test prints a final 'FAIL' status if any package test
121 has failed.
122
123 In package list mode only, go test caches successful package test
124 results to avoid unnecessary repeated running of tests. When the
125 result of a test can be recovered from the cache, go test will
126 redisplay the previous output instead of running the test binary
127 again. When this happens, go test prints '(cached)' in place of the
128 elapsed time in the summary line.
129
130 The rule for a match in the cache is that the run involves the same
131 test binary and the flags on the command line come entirely from a
132 restricted set of 'cacheable' test flags, defined as -benchtime,
133 -coverprofile, -cpu, -failfast, -fullpath, -list, -outputdir, -parallel,
134 -run, -short, -skip, -timeout and -v.
135 If a run of go test has any test or non-test flags outside this set,
136 the result is not cached. To disable test caching, use any test flag
137 or argument other than the cacheable flags. The idiomatic way to disable
138 test caching explicitly is to use -count=1. Tests that open files within
139 the package's module or that consult environment variables only
140 match future runs in which the files and environment variables are
141 unchanged. A cached test result is treated as executing in no time
142 at all, so a successful package test result will be cached and
143 reused regardless of -timeout setting.
144
145 In addition to the build flags, the flags handled by 'go test' itself are:
146
147 -args
148 Pass the remainder of the command line (everything after -args)
149 to the test binary, uninterpreted and unchanged.
150 Because this flag consumes the remainder of the command line,
151 the package list (if present) must appear before this flag.
152
153 -c
154 Compile the test binary to pkg.test in the current directory but do not run it
155 (where pkg is the last element of the package's import path).
156 The file name or target directory can be changed with the -o flag.
157
158 -exec xprog
159 Run the test binary using xprog. The behavior is the same as
160 in 'go run'. See 'go help run' for details.
161
162 -json
163 Convert test output to JSON suitable for automated processing.
164 See 'go doc test2json' for the encoding details.
165 Also emits build output in JSON. See 'go help buildjson'.
166
167 -o file
168 Save a copy of the test binary to the named file.
169 The test still runs (unless -c is specified).
170 If file ends in a slash or names an existing directory,
171 the test is written to pkg.test in that directory.
172
173 The test binary also accepts flags that control execution of the test; these
174 flags are also accessible by 'go test'. See 'go help testflag' for details.
175
176 For more about build flags, see 'go help build'.
177 For more about specifying packages, see 'go help packages'.
178
179 See also: go build, go vet.
180 `,
181 }
182
183 var HelpTestflag = &base.Command{
184 UsageLine: "testflag",
185 Short: "testing flags",
186 Long: `
187 The 'go test' command takes both flags that apply to 'go test' itself
188 and flags that apply to the resulting test binary.
189
190 Several of the flags control profiling and write an execution profile
191 suitable for "go tool pprof"; run "go tool pprof -h" for more
192 information. The -sample_index=alloc_space, -sample_index=alloc_objects,
193 and -show_bytes options of pprof control how the information is presented.
194
195 The following flags are recognized by the 'go test' command and
196 control the execution of any test:
197
198 -artifacts
199 Save test artifacts in the directory specified by -outputdir.
200 See 'go doc testing.T.ArtifactDir'.
201
202 -bench regexp
203 Run only those benchmarks matching a regular expression.
204 By default, no benchmarks are run.
205 To run all benchmarks, use '-bench .' or '-bench=.'.
206 The regular expression is split by unbracketed slash (/)
207 characters into a sequence of regular expressions, and each
208 part of a benchmark's identifier must match the corresponding
209 element in the sequence, if any. Possible parents of matches
210 are run with b.N=1 to identify sub-benchmarks. For example,
211 given -bench=X/Y, top-level benchmarks matching X are run
212 with b.N=1 to find any sub-benchmarks matching Y, which are
213 then run in full.
214
215 -benchtime t
216 Run enough iterations of each benchmark to take t, specified
217 as a time.Duration (for example, -benchtime 1h30s).
218 The default is 1 second (1s).
219 The special syntax Nx means to run the benchmark N times
220 (for example, -benchtime 100x).
221
222 -count n
223 Run each test, benchmark, and fuzz seed n times (default 1).
224 If -cpu is set, run n times for each GOMAXPROCS value.
225 Examples are always run once. -count does not apply to
226 fuzz tests matched by -fuzz.
227
228 -cover
229 Enable coverage analysis.
230 Note that because coverage works by annotating the source
231 code before compilation, compilation and test failures with
232 coverage enabled may report line numbers that don't correspond
233 to the original sources.
234
235 -covermode set,count,atomic
236 Set the mode for coverage analysis for the package[s]
237 being tested. The default is "set" unless -race is enabled,
238 in which case it is "atomic".
239 The values:
240 set: bool: does this statement run?
241 count: int: how many times does this statement run?
242 atomic: int: count, but correct in multithreaded tests;
243 significantly more expensive.
244 Sets -cover.
245
246 -coverpkg pattern1,pattern2,pattern3
247 Apply coverage analysis in each test to packages whose import paths
248 match the patterns. The default is for each test to analyze only
249 the package being tested. See 'go help packages' for a description
250 of package patterns. Sets -cover.
251
252 -cpu 1,2,4
253 Specify a list of GOMAXPROCS values for which the tests, benchmarks or
254 fuzz tests should be executed. The default is the current value
255 of GOMAXPROCS. -cpu does not apply to fuzz tests matched by -fuzz.
256
257 -failfast
258 Do not start new tests after the first test failure.
259
260 -fullpath
261 Show full file names in the error messages.
262
263 -fuzz regexp
264 Run the fuzz test matching the regular expression. When specified,
265 the command line argument must match exactly one package within the
266 main module, and regexp must match exactly one fuzz test within
267 that package. Fuzzing will occur after tests, benchmarks, seed corpora
268 of other fuzz tests, and examples have completed. See the Fuzzing
269 section of the testing package documentation for details.
270
271 -fuzztime t
272 Run enough iterations of the fuzz target during fuzzing to take t,
273 specified as a time.Duration (for example, -fuzztime 1h30s).
274 The default is to run forever.
275 The special syntax Nx means to run the fuzz target N times
276 (for example, -fuzztime 1000x).
277
278 -fuzzminimizetime t
279 Run enough iterations of the fuzz target during each minimization
280 attempt to take t, as specified as a time.Duration (for example,
281 -fuzzminimizetime 30s).
282 The default is 60s.
283 The special syntax Nx means to run the fuzz target N times
284 (for example, -fuzzminimizetime 100x).
285
286 -json
287 Log verbose output and test results in JSON. This presents the
288 same information as the -v flag in a machine-readable format.
289
290 -list regexp
291 List tests, benchmarks, fuzz tests, or examples matching the regular
292 expression. No tests, benchmarks, fuzz tests, or examples will be run.
293 This will only list top-level tests. No subtest or subbenchmarks will be
294 shown.
295
296 -outputdir directory
297 Place output files from profiling and test artifacts in the
298 specified directory, by default the directory in which "go test" is running.
299
300 -parallel n
301 Allow parallel execution of test functions that call t.Parallel, and
302 fuzz targets that call t.Parallel when running the seed corpus.
303 The value of this flag is the maximum number of tests to run
304 simultaneously.
305 While fuzzing, the value of this flag is the maximum number of
306 subprocesses that may call the fuzz function simultaneously, regardless of
307 whether T.Parallel is called.
308 By default, -parallel is set to the value of GOMAXPROCS.
309 Setting -parallel to values higher than GOMAXPROCS may cause degraded
310 performance due to CPU contention, especially when fuzzing.
311 Note that -parallel only applies within a single test binary.
312 The 'go test' command may run tests for different packages
313 in parallel as well, according to the setting of the -p flag
314 (see 'go help build').
315
316 -run regexp
317 Run only those tests, examples, and fuzz tests matching the regular
318 expression. For tests, the regular expression is split by unbracketed
319 slash (/) characters into a sequence of regular expressions, and each
320 part of a test's identifier must match the corresponding element in
321 the sequence, if any. Note that possible parents of matches are
322 run too, so that -run=X/Y matches and runs and reports the result
323 of all tests matching X, even those without sub-tests matching Y,
324 because it must run them to look for those sub-tests.
325 See also -skip.
326
327 -short
328 Tell long-running tests to shorten their run time.
329 It is off by default but set during all.bash so that installing
330 the Go tree can run a sanity check but not spend time running
331 exhaustive tests.
332
333 -shuffle off,on,N
334 Randomize the execution order of tests and benchmarks.
335 It is off by default. If -shuffle is set to on, then it will seed
336 the randomizer using the system clock. If -shuffle is set to an
337 integer N, then N will be used as the seed value. In both cases,
338 the seed will be reported for reproducibility.
339
340 -skip regexp
341 Run only those tests, examples, fuzz tests, and benchmarks that
342 do not match the regular expression. Like for -run and -bench,
343 for tests and benchmarks, the regular expression is split by unbracketed
344 slash (/) characters into a sequence of regular expressions, and each
345 part of a test's identifier must match the corresponding element in
346 the sequence, if any.
347
348 -timeout d
349 If a test binary runs longer than duration d, panic.
350 If d is 0, the timeout is disabled.
351 The default is 10 minutes (10m).
352
353 -v
354 Verbose output: log all tests as they are run. Also print all
355 text from Log and Logf calls even if the test succeeds.
356
357 -vet list
358 Configure the invocation of "go vet" during "go test"
359 to use the comma-separated list of vet checks.
360 If list is empty, "go test" runs "go vet" with a curated list of
361 checks believed to be always worth addressing.
362 If list is "off", "go test" does not run "go vet" at all.
363
364 The following flags are also recognized by 'go test' and can be used to
365 profile the tests during execution:
366
367 -benchmem
368 Print memory allocation statistics for benchmarks.
369 Allocations made in C or using C.malloc are not counted.
370
371 -blockprofile block.out
372 Write a goroutine blocking profile to the specified file
373 when all tests are complete.
374 Writes test binary as -c would.
375
376 -blockprofilerate n
377 Control the detail provided in goroutine blocking profiles by
378 calling runtime.SetBlockProfileRate with n.
379 See 'go doc runtime.SetBlockProfileRate'.
380 The profiler aims to sample, on average, one blocking event every
381 n nanoseconds the program spends blocked. By default,
382 if -test.blockprofile is set without this flag, all blocking events
383 are recorded, equivalent to -test.blockprofilerate=1.
384
385 -coverprofile cover.out
386 Write a coverage profile to the file after all tests have passed.
387 Sets -cover.
388
389 -cpuprofile cpu.out
390 Write a CPU profile to the specified file before exiting.
391 Writes test binary as -c would.
392
393 -memprofile mem.out
394 Write an allocation profile to the file after all tests have passed.
395 Writes test binary as -c would.
396
397 -memprofilerate n
398 Enable more precise (and expensive) memory allocation profiles by
399 setting runtime.MemProfileRate. See 'go doc runtime.MemProfileRate'.
400 To profile all memory allocations, use -test.memprofilerate=1.
401
402 -mutexprofile mutex.out
403 Write a mutex contention profile to the specified file
404 when all tests are complete.
405 Writes test binary as -c would.
406
407 -mutexprofilefraction n
408 Sample 1 in n stack traces of goroutines holding a
409 contended mutex.
410
411 -trace trace.out
412 Write an execution trace to the specified file before exiting.
413
414 Each of these flags is also recognized with an optional 'test.' prefix,
415 as in -test.v. When invoking the generated test binary (the result of
416 'go test -c') directly, however, the prefix is mandatory.
417
418 The 'go test' command rewrites or removes recognized flags,
419 as appropriate, both before and after the optional package list,
420 before invoking the test binary.
421
422 For instance, the command
423
424 go test -v -myflag testdata -cpuprofile=prof.out -x
425
426 will compile the test binary and then run it as
427
428 pkg.test -test.v -myflag testdata -test.cpuprofile=prof.out
429
430 (The -x flag is removed because it applies only to the go command's
431 execution, not to the test itself.)
432
433 The test flags that generate profiles (other than for coverage) also
434 leave the test binary in pkg.test for use when analyzing the profiles.
435
436 When 'go test' runs a test binary, it does so from within the
437 corresponding package's source code directory. Depending on the test,
438 it may be necessary to do the same when invoking a generated test
439 binary directly. Because that directory may be located within the
440 module cache, which may be read-only and is verified by checksums, the
441 test must not write to it or any other directory within the module
442 unless explicitly requested by the user (such as with the -fuzz flag,
443 which writes failures to testdata/fuzz).
444
445 The command-line package list, if present, must appear before any
446 flag not known to the go test command. Continuing the example above,
447 the package list would have to appear before -myflag, but could appear
448 on either side of -v.
449
450 When 'go test' runs in package list mode, 'go test' caches successful
451 package test results to avoid unnecessary repeated running of tests. To
452 disable test caching, use any test flag or argument other than the
453 cacheable flags. The idiomatic way to disable test caching explicitly
454 is to use -count=1.
455
456 To keep an argument for a test binary from being interpreted as a
457 known flag or a package name, use -args (see 'go help test') which
458 passes the remainder of the command line through to the test binary
459 uninterpreted and unaltered.
460
461 For instance, the command
462
463 go test -v -args -x -v
464
465 will compile the test binary and then run it as
466
467 pkg.test -test.v -x -v
468
469 Similarly,
470
471 go test -args math
472
473 will compile the test binary and then run it as
474
475 pkg.test math
476
477 In the first example, the -x and the second -v are passed through to the
478 test binary unchanged and with no effect on the go command itself.
479 In the second example, the argument math is passed through to the test
480 binary, instead of being interpreted as the package list.
481 `,
482 }
483
484 var HelpTestfunc = &base.Command{
485 UsageLine: "testfunc",
486 Short: "testing functions",
487 Long: `
488 The 'go test' command expects to find test, benchmark, and example functions
489 in the "*_test.go" files corresponding to the package under test.
490
491 A test function is one named TestXxx (where Xxx does not start with a
492 lower case letter) and should have the signature,
493
494 func TestXxx(t *testing.T) { ... }
495
496 A benchmark function is one named BenchmarkXxx and should have the signature,
497
498 func BenchmarkXxx(b *testing.B) { ... }
499
500 A fuzz test is one named FuzzXxx and should have the signature,
501
502 func FuzzXxx(f *testing.F) { ... }
503
504 An example function is similar to a test function but, instead of using
505 *testing.T to report success or failure, prints output to os.Stdout.
506 If the last comment in the function starts with "Output:" then the output
507 is compared exactly against the comment (see examples below). If the last
508 comment begins with "Unordered output:" then the output is compared to the
509 comment, however the order of the lines is ignored. An example with no such
510 comment is compiled but not executed. An example with no text after
511 "Output:" is compiled, executed, and expected to produce no output.
512
513 Godoc displays the body of ExampleXxx to demonstrate the use
514 of the function, constant, or variable Xxx. An example of a method M with
515 receiver type T or *T is named ExampleT_M. There may be multiple examples
516 for a given function, constant, or variable, distinguished by a trailing _xxx,
517 where xxx is a suffix not beginning with an upper case letter.
518
519 Here is an example of an example:
520
521 func ExamplePrintln() {
522 Println("The output of\nthis example.")
523 // Output: The output of
524 // this example.
525 }
526
527 Here is another example where the ordering of the output is ignored:
528
529 func ExamplePerm() {
530 for _, value := range Perm(4) {
531 fmt.Println(value)
532 }
533
534 // Unordered output: 4
535 // 2
536 // 1
537 // 3
538 // 0
539 }
540
541 The entire test file is presented as the example when it contains a single
542 example function, at least one other function, type, variable, or constant
543 declaration, and no tests, benchmarks, or fuzz tests.
544
545 See the documentation of the testing package for more information.
546 `,
547 }
548
549 var (
550 testArtifacts bool
551 testBench string
552 testC bool
553 testCoverPkgs []*load.Package
554 testCoverProfile string
555 testFailFast bool
556 testFuzz string
557 testJSON bool
558 testList string
559 testO string
560 testOutputDir outputdirFlag
561 testShuffle shuffleFlag
562 testTimeout time.Duration
563 testV testVFlag
564 testVet = vetFlag{flags: defaultVetFlags}
565 )
566
567 type testVFlag struct {
568 on bool
569 json bool
570 }
571
572 func (*testVFlag) IsBoolFlag() bool { return true }
573
574 func (f *testVFlag) Set(arg string) error {
575 if v, err := strconv.ParseBool(arg); err == nil {
576 f.on = v
577 f.json = false
578 return nil
579 }
580 if arg == "test2json" {
581 f.on = true
582 f.json = true
583 return nil
584 }
585 return fmt.Errorf("invalid flag -test.v=%s", arg)
586 }
587
588 func (f *testVFlag) String() string {
589 if f.json {
590 return "test2json"
591 }
592 if f.on {
593 return "true"
594 }
595 return "false"
596 }
597
598 var (
599 testArgs []string
600 pkgArgs []string
601 pkgs []*load.Package
602
603 testHelp bool
604
605 testKillTimeout = 100 * 365 * 24 * time.Hour
606 testWaitDelay time.Duration
607 testCacheExpire time.Time
608 testShouldFailFast atomic.Bool
609
610 testBlockProfile, testCPUProfile, testMemProfile, testMutexProfile, testTrace string
611
612 testODir = false
613 )
614
615
616
617 func testProfile() string {
618 switch {
619 case testBlockProfile != "":
620 return "-blockprofile"
621 case testCPUProfile != "":
622 return "-cpuprofile"
623 case testMemProfile != "":
624 return "-memprofile"
625 case testMutexProfile != "":
626 return "-mutexprofile"
627 case testTrace != "":
628 return "-trace"
629 default:
630 return ""
631 }
632 }
633
634
635 func testNeedBinary() bool {
636 switch {
637 case testBlockProfile != "":
638 return true
639 case testCPUProfile != "":
640 return true
641 case testMemProfile != "":
642 return true
643 case testMutexProfile != "":
644 return true
645 case testO != "":
646 return true
647 default:
648 return false
649 }
650 }
651
652
653 func testShowPass() bool {
654 return testV.on || testList != "" || testHelp
655 }
656
657 var defaultVetFlags = []string{
658
659
660
661
662
663 "-atomic",
664 "-bools",
665 "-buildtag",
666
667
668
669
670 "-directive",
671 "-errorsas",
672
673
674
675 "-ifaceassert",
676
677
678 "-nilfunc",
679 "-printf",
680
681
682 "-slog",
683
684 "-stdversion",
685 "-stringintconv",
686
687
688 "-tests",
689
690
691
692
693
694
695 }
696
697 func runTest(ctx context.Context, cmd *base.Command, args []string) {
698 moduleLoader := modload.NewLoader()
699 pkgArgs, testArgs = testFlags(args)
700 moduleLoader.InitWorkfile()
701
702 if cfg.DebugTrace != "" {
703 var close func() error
704 var err error
705 ctx, close, err = trace.Start(ctx, cfg.DebugTrace)
706 if err != nil {
707 base.Fatalf("failed to start trace: %v", err)
708 }
709 defer func() {
710 if err := close(); err != nil {
711 base.Fatalf("failed to stop trace: %v", err)
712 }
713 }()
714 }
715
716 ctx, span := trace.StartSpan(ctx, fmt.Sprint("Running ", cmd.Name(), " command"))
717 defer span.Done()
718
719 work.FindExecCmd()
720
721 work.BuildInit(moduleLoader)
722 work.VetFlags = testVet.flags
723 work.VetExplicit = testVet.explicit
724 work.VetTool = base.Tool("vet")
725
726 pkgOpts := load.PackageOpts{ModResolveTests: true}
727 pkgs = load.PackagesAndErrors(moduleLoader, ctx, pkgOpts, pkgArgs)
728
729
730 if len(pkgs) == 0 {
731 base.Fatalf("no packages to test")
732 }
733
734 if testFuzz != "" {
735 if !platform.FuzzSupported(cfg.Goos, cfg.Goarch) {
736 base.Fatalf("-fuzz flag is not supported on %s/%s", cfg.Goos, cfg.Goarch)
737 }
738 if len(pkgs) != 1 {
739 base.Fatalf("cannot use -fuzz flag with multiple packages")
740 }
741 if testCoverProfile != "" {
742 base.Fatalf("cannot use -coverprofile flag with -fuzz flag")
743 }
744 if profileFlag := testProfile(); profileFlag != "" {
745 base.Fatalf("cannot use %s flag with -fuzz flag", profileFlag)
746 }
747
748
749
750
751
752
753 mainMods := moduleLoader.MainModules
754 if m := pkgs[0].Module; m != nil && m.Path != "" {
755 if !mainMods.Contains(m.Path) {
756 base.Fatalf("cannot use -fuzz flag on package outside the main module")
757 }
758 } else if pkgs[0].Standard && moduleLoader.Enabled() {
759
760
761
762
763
764
765
766
767
768
769 if strings.HasPrefix(pkgs[0].ImportPath, "cmd/") {
770 if !mainMods.Contains("cmd") || !mainMods.InGorootSrc(module.Version{Path: "cmd"}) {
771 base.Fatalf("cannot use -fuzz flag on package outside the main module")
772 }
773 } else {
774 if !mainMods.Contains("std") || !mainMods.InGorootSrc(module.Version{Path: "std"}) {
775 base.Fatalf("cannot use -fuzz flag on package outside the main module")
776 }
777 }
778 }
779 }
780 if testProfile() != "" && len(pkgs) != 1 {
781 base.Fatalf("cannot use %s flag with multiple packages", testProfile())
782 }
783
784 if testO != "" {
785 if strings.HasSuffix(testO, "/") || strings.HasSuffix(testO, string(os.PathSeparator)) {
786 testODir = true
787 } else if fi, err := os.Stat(testO); err == nil && fi.IsDir() {
788 testODir = true
789 }
790 }
791
792 if len(pkgs) > 1 && (testC || testO != "") && !base.IsNull(testO) {
793 if testO != "" && !testODir {
794 base.Fatalf("with multiple packages, -o must refer to a directory or %s", os.DevNull)
795 }
796
797 pkgsForBinary := map[string][]*load.Package{}
798
799 for _, p := range pkgs {
800 testBinary := testBinaryName(p)
801 pkgsForBinary[testBinary] = append(pkgsForBinary[testBinary], p)
802 }
803
804 for testBinary, pkgs := range pkgsForBinary {
805 if len(pkgs) > 1 {
806 var buf strings.Builder
807 for _, pkg := range pkgs {
808 buf.WriteString(pkg.ImportPath)
809 buf.WriteString("\n")
810 }
811
812 base.Errorf("cannot write test binary %s for multiple packages:\n%s", testBinary, buf.String())
813 }
814 }
815
816 base.ExitIfErrors()
817 }
818
819 initCoverProfile()
820 defer closeCoverProfile()
821
822
823
824
825
826
827
828 if testTimeout > 0 && testFuzz == "" && testBench == "" {
829
830
831
832
833
834
835
836
837
838
839 if wd := testTimeout / 10; wd < 5*time.Second {
840 testWaitDelay = 5 * time.Second
841 } else {
842 testWaitDelay = wd
843 }
844
845
846
847
848
849
850
851
852
853 if testWaitDelay < 1*time.Minute {
854 testKillTimeout = testTimeout + 1*time.Minute
855 } else {
856 testKillTimeout = testTimeout + testWaitDelay
857 }
858 }
859
860
861
862
863 if dir, _, _ := cache.DefaultDir(); dir != "off" {
864 if data, _ := lockedfile.Read(filepath.Join(dir, "testexpire.txt")); len(data) > 0 && data[len(data)-1] == '\n' {
865 if t, err := strconv.ParseInt(string(data[:len(data)-1]), 10, 64); err == nil {
866 testCacheExpire = time.Unix(0, t)
867 }
868 }
869 }
870
871 b := work.NewBuilder("", moduleLoader.VendorDirOrEmpty)
872 defer func() {
873 if err := b.Close(); err != nil {
874 base.Fatal(err)
875 }
876 }()
877
878 var builds, runs, prints []*work.Action
879 var writeCoverMetaAct *work.Action
880
881 if cfg.BuildCoverPkg != nil {
882 match := make([]func(*modload.Loader, *load.Package) bool, len(cfg.BuildCoverPkg))
883 for i := range cfg.BuildCoverPkg {
884 match[i] = load.MatchPackage(cfg.BuildCoverPkg[i], base.Cwd())
885 }
886
887
888
889 plist := load.TestPackageList(moduleLoader, ctx, pkgOpts, pkgs)
890 testCoverPkgs = load.SelectCoverPackages(moduleLoader, plist, match, "test")
891 if len(testCoverPkgs) > 0 {
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937 writeCoverMetaAct = &work.Action{
938 Mode: "write coverage meta-data file",
939 Actor: work.ActorFunc(work.WriteCoverMetaFilesFile),
940 Objdir: b.NewObjdir(),
941 }
942 for _, p := range testCoverPkgs {
943 p.Internal.Cover.GenMeta = true
944 }
945 }
946 }
947
948
949
950 if testFuzz != "" {
951
952
953
954 var skipInstrumentation = map[string]bool{
955 "context": true,
956 "internal/fuzz": true,
957 "internal/godebug": true,
958 "internal/runtime/maps": true,
959 "internal/sync": true,
960 "reflect": true,
961 "runtime": true,
962 "sync": true,
963 "sync/atomic": true,
964 "syscall": true,
965 "testing": true,
966 "time": true,
967 }
968 for _, p := range load.TestPackageList(moduleLoader, ctx, pkgOpts, pkgs) {
969 if !skipInstrumentation[p.ImportPath] {
970 p.Internal.FuzzInstrument = true
971 }
972 }
973 }
974
975
976 allImports := make(map[*load.Package]bool)
977 for _, p := range pkgs {
978 if p.Error != nil && p.Error.IsImportCycle {
979 continue
980 }
981 for _, p1 := range p.Internal.Imports {
982 allImports[p1] = true
983 }
984 }
985
986 if cfg.BuildCover {
987 for _, p := range pkgs {
988
989
990
991
992
993
994
995
996
997 if cfg.BuildCoverMode == "atomic" && p.ImportPath != "sync/atomic" {
998 load.EnsureImport(moduleLoader, p, "sync/atomic")
999 }
1000
1001
1002
1003
1004
1005
1006
1007
1008 if len(p.TestGoFiles)+len(p.XTestGoFiles) == 0 && cfg.BuildCoverPkg == nil {
1009 p.Internal.Cover.GenMeta = true
1010 }
1011
1012
1013
1014
1015 if cfg.BuildCover {
1016 if p.Internal.Cover.GenMeta {
1017 p.Internal.Cover.Mode = cfg.BuildCoverMode
1018 }
1019 }
1020 }
1021 }
1022
1023
1024 for _, p := range pkgs {
1025 reportErr := func(perr *load.Package, err error) {
1026 str := err.Error()
1027 if p.ImportPath != "" {
1028 load.DefaultPrinter().Errorf(perr, "# %s\n%s", p.ImportPath, str)
1029 } else {
1030 load.DefaultPrinter().Errorf(perr, "%s", str)
1031 }
1032 }
1033 reportSetupFailed := func(perr *load.Package, err error) {
1034 var stdout io.Writer = os.Stdout
1035 if testJSON {
1036 json := test2json.NewConverter(stdout, p.ImportPath, test2json.Timestamp)
1037 defer func() {
1038 json.Exited(err)
1039 json.Close()
1040 }()
1041 if gotestjsonbuildtext.Value() == "1" {
1042
1043
1044 gotestjsonbuildtext.IncNonDefault()
1045 } else {
1046 json.SetFailedBuild(perr.Desc())
1047 }
1048 stdout = json
1049 }
1050 fmt.Fprintf(stdout, "FAIL\t%s [setup failed]\n", p.ImportPath)
1051 base.SetExitStatus(1)
1052 }
1053
1054 var firstErrPkg *load.Package
1055 load.PackageErrors([]*load.Package{p}, func(p *load.Package) {
1056 reportErr(p, p.Error)
1057 if firstErrPkg == nil {
1058 firstErrPkg = p
1059 }
1060 })
1061 if firstErrPkg != nil {
1062 reportSetupFailed(firstErrPkg, firstErrPkg.Error)
1063 continue
1064 }
1065 buildTest, runTest, printTest, perr, err := builderTest(moduleLoader, b, ctx, pkgOpts, p, allImports[p], writeCoverMetaAct)
1066 if err != nil {
1067 reportErr(perr, err)
1068 reportSetupFailed(perr, err)
1069 continue
1070 }
1071 builds = append(builds, buildTest)
1072 runs = append(runs, runTest)
1073 prints = append(prints, printTest)
1074 }
1075
1076
1077 if cfg.Experiment.VetFiles {
1078 buildAnalysisTool(moduleLoader, ctx, b, pkgOpts)
1079 }
1080
1081
1082
1083
1084
1085
1086 var prevBarrier *work.Action
1087 ch := make(chan struct{})
1088 close(ch)
1089 for _, a := range runs {
1090 if r, ok := a.Actor.(*runTestActor); ok {
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101 barrier := &work.Action{
1102 Mode: "test barrier",
1103 Deps: slices.Clip(a.Deps),
1104 }
1105 if prevBarrier != nil {
1106 barrier.Deps = append(barrier.Deps, prevBarrier)
1107 }
1108 a.Deps = []*work.Action{barrier}
1109 prevBarrier = barrier
1110
1111 r.prev = ch
1112 ch = make(chan struct{})
1113 r.next = ch
1114 }
1115 }
1116
1117
1118 root := &work.Action{Mode: "go test", Actor: work.ActorFunc(printExitStatus), Deps: prints}
1119
1120
1121
1122 for i, a := range prints {
1123 if i > 0 {
1124 a.Deps = append(a.Deps, prints[i-1])
1125 }
1126 }
1127
1128
1129 if !testC && (testBench != "") {
1130
1131
1132 for i, run := range runs {
1133 if i == 0 {
1134 run.Deps = append(run.Deps, builds...)
1135 } else {
1136 run.Deps = append(run.Deps, prints[i-1])
1137 }
1138 }
1139 }
1140
1141 b.Do(ctx, root)
1142 }
1143
1144 var windowsBadWords = []string{
1145 "install",
1146 "patch",
1147 "setup",
1148 "update",
1149 }
1150
1151 func builderTest(ld *modload.Loader, b *work.Builder, ctx context.Context, pkgOpts load.PackageOpts, p *load.Package, imported bool, writeCoverMetaAct *work.Action) (buildAction, runAction, printAction *work.Action, perr *load.Package, err error) {
1152 if len(p.TestGoFiles)+len(p.XTestGoFiles) == 0 {
1153 build := b.CompileAction(work.ModeBuild, work.ModeBuild, p)
1154 run := &work.Action{
1155 Mode: "test run",
1156 Actor: new(runTestActor),
1157 Deps: []*work.Action{build},
1158 Objdir: b.NewObjdir(),
1159 Package: p,
1160 IgnoreFail: true,
1161 }
1162 if writeCoverMetaAct != nil && build.Actor != nil {
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176 run.Deps = append(run.Deps, writeCoverMetaAct)
1177 writeCoverMetaAct.Deps = append(writeCoverMetaAct.Deps, build)
1178 }
1179 addTestVet(ld, b, p, run, nil)
1180 print := &work.Action{
1181 Mode: "test print",
1182 Actor: work.ActorFunc(builderPrintTest),
1183 Deps: []*work.Action{run},
1184 Package: p,
1185 IgnoreFail: true,
1186 }
1187 return build, run, print, nil, nil
1188 }
1189
1190
1191
1192
1193
1194 var cover *load.TestCover
1195 if cfg.BuildCover {
1196 cover = &load.TestCover{
1197 Mode: cfg.BuildCoverMode,
1198 Local: cfg.BuildCoverPkg == nil,
1199 Pkgs: testCoverPkgs,
1200 Paths: cfg.BuildCoverPkg,
1201 }
1202 }
1203 pmain, ptest, pxtest, perr := load.TestPackagesFor(ld, ctx, pkgOpts, p, cover)
1204 if perr != nil {
1205 return nil, nil, nil, perr, perr.Error
1206 }
1207
1208
1209
1210
1211
1212 if imported && ptest != p {
1213 exportTest := b.BuildExportAction(work.ModeBuild, work.ModeBuild, ptest)
1214 exportP := b.BuildExportAction(work.ModeBuild, work.ModeBuild, p)
1215 exportTest.Deps = append(exportTest.Deps, exportP)
1216 }
1217
1218 testBinary := testBinaryName(p)
1219
1220
1221
1222 testDir := b.CompileAction(work.ModeBuild, work.ModeBuild, pmain).Objdir
1223 if err := b.BackgroundShell().Mkdir(testDir); err != nil {
1224 return nil, nil, nil, nil, err
1225 }
1226
1227 pmain.Dir = testDir
1228 pmain.Internal.OmitDebug = !testC && !testNeedBinary()
1229 if pmain.ImportPath == "runtime.test" {
1230
1231
1232 pmain.Internal.OmitDebug = false
1233 }
1234
1235 if !cfg.BuildN {
1236
1237
1238 if err := os.WriteFile(testDir+"_testmain.go", *pmain.Internal.TestmainGo, 0666); err != nil {
1239 return nil, nil, nil, nil, err
1240 }
1241 }
1242
1243 a := b.LinkAction(ld, work.ModeBuild, work.ModeBuild, pmain)
1244 a.Target = testDir + testBinary + cfg.ExeSuffix
1245 if cfg.Goos == "windows" {
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268 for _, bad := range windowsBadWords {
1269 if strings.Contains(testBinary, bad) {
1270 a.Target = testDir + "test.test" + cfg.ExeSuffix
1271 break
1272 }
1273 }
1274 }
1275 buildAction = a
1276 var installAction, cleanAction *work.Action
1277 if testC || testNeedBinary() {
1278
1279 target := filepath.Join(base.Cwd(), testBinary+cfg.ExeSuffix)
1280 isNull := false
1281
1282 if testO != "" {
1283 target = testO
1284
1285 if testODir {
1286 if filepath.IsAbs(target) {
1287 target = filepath.Join(target, testBinary+cfg.ExeSuffix)
1288 } else {
1289 target = filepath.Join(base.Cwd(), target, testBinary+cfg.ExeSuffix)
1290 }
1291 } else {
1292 if base.IsNull(target) {
1293 isNull = true
1294 } else if !filepath.IsAbs(target) {
1295 target = filepath.Join(base.Cwd(), target)
1296 }
1297 }
1298 }
1299
1300 if isNull {
1301 runAction = buildAction
1302 } else {
1303 pmain.Target = target
1304 installAction = &work.Action{
1305 Mode: "test build",
1306 Actor: work.ActorFunc(work.BuildInstallFunc),
1307 Deps: []*work.Action{buildAction},
1308 Package: pmain,
1309 Target: target,
1310 }
1311 runAction = installAction
1312 }
1313 }
1314
1315 var vetRunAction *work.Action
1316 if testC {
1317 printAction = &work.Action{
1318 Mode: "test print (nop)",
1319 Package: p,
1320 Deps: []*work.Action{runAction},
1321 IgnoreFail: true,
1322 Actor: work.ActorFunc(func(b *work.Builder, ctx context.Context, a *work.Action) error {
1323 if buildAction.Failed == nil {
1324 for _, dep := range a.Deps {
1325 if dep.Mode == "vet" && dep.Failed != nil {
1326 b.ReportDeferredVetError(dep.Failed)
1327 }
1328 }
1329 }
1330 return nil
1331 }),
1332 }
1333 vetRunAction = printAction
1334 } else {
1335
1336 rta := &runTestActor{
1337 writeCoverMetaAct: writeCoverMetaAct,
1338 }
1339 runAction = &work.Action{
1340 Mode: "test run",
1341 Actor: rta,
1342 Deps: []*work.Action{buildAction},
1343 Package: p,
1344 IgnoreFail: true,
1345 TryCache: rta.c.tryCache,
1346 }
1347 if writeCoverMetaAct != nil {
1348
1349
1350
1351
1352
1353 runAction.Deps = append(runAction.Deps, writeCoverMetaAct)
1354
1355
1356
1357
1358
1359
1360 buildAction.Deps = append(buildAction.Deps, writeCoverMetaAct)
1361 if !p.IsTestOnly() {
1362
1363
1364
1365
1366
1367 compileAction := b.CompileAction(work.ModeBuild, work.ModeBuild, p)
1368 writeCoverMetaAct.Deps = append(writeCoverMetaAct.Deps, compileAction)
1369 }
1370 }
1371 runAction.Objdir = testDir
1372 vetRunAction = runAction
1373 cleanAction = &work.Action{
1374 Mode: "test clean",
1375 Actor: work.ActorFunc(builderCleanTest),
1376 Deps: []*work.Action{runAction},
1377 Package: p,
1378 IgnoreFail: true,
1379 Objdir: testDir,
1380 }
1381 printAction = &work.Action{
1382 Mode: "test print",
1383 Actor: work.ActorFunc(builderPrintTest),
1384 Deps: []*work.Action{cleanAction},
1385 Package: p,
1386 IgnoreFail: true,
1387 }
1388 }
1389
1390 if len(ptest.GoFiles)+len(ptest.CgoFiles) > 0 {
1391 addTestVet(ld, b, ptest, vetRunAction, installAction)
1392 }
1393 if pxtest != nil {
1394 addTestVet(ld, b, pxtest, vetRunAction, installAction)
1395 }
1396
1397 if installAction != nil {
1398 if runAction != installAction {
1399 installAction.Deps = append(installAction.Deps, runAction)
1400 }
1401 if cleanAction != nil {
1402 cleanAction.Deps = append(cleanAction.Deps, installAction)
1403 }
1404 }
1405
1406 return buildAction, runAction, printAction, nil, nil
1407 }
1408
1409 func addTestVet(ld *modload.Loader, b *work.Builder, p *load.Package, runAction, installAction *work.Action) {
1410 if testVet.off {
1411 return
1412 }
1413 if cfg.Experiment.VetFiles && !analysisUsesCmdVet() {
1414
1415 addTestAnalysis(ld, b, p, runAction, installAction)
1416 return
1417 }
1418
1419 vet := b.VetAction(p, false)
1420 runAction.Deps = append(runAction.Deps, vet)
1421
1422 if installAction != nil {
1423 installAction.Deps = append(installAction.Deps, vet)
1424 }
1425 }
1426
1427 var noTestsToRun = []byte("\ntesting: warning: no tests to run\n")
1428 var noFuzzTestsToFuzz = []byte("\ntesting: warning: no fuzz tests to fuzz\n")
1429 var tooManyFuzzTestsToFuzz = []byte("\ntesting: warning: -fuzz matches more than one fuzz test, won't fuzz\n")
1430
1431
1432 type runTestActor struct {
1433 c runCache
1434
1435
1436
1437
1438
1439 writeCoverMetaAct *work.Action
1440
1441
1442 prev <-chan struct{}
1443 next chan<- struct{}
1444 }
1445
1446
1447 type runCache struct {
1448 disableCache bool
1449
1450 buf *bytes.Buffer
1451 id1 cache.ActionID
1452 id2 cache.ActionID
1453 covMeta cache.ActionID
1454 }
1455
1456 func coverProfTempFile(a *work.Action) string {
1457 if a.Objdir == "" {
1458 panic("internal error: objdir not set in coverProfTempFile")
1459 }
1460 return a.Objdir + "_cover_.out"
1461 }
1462
1463
1464
1465
1466
1467
1468 var stdoutMu sync.Mutex
1469
1470 type lockedStdout struct{}
1471
1472 func (lockedStdout) Write(b []byte) (int, error) {
1473 stdoutMu.Lock()
1474 defer stdoutMu.Unlock()
1475 return os.Stdout.Write(b)
1476 }
1477
1478 func (r *runTestActor) Act(b *work.Builder, ctx context.Context, a *work.Action) error {
1479 sh := b.Shell(a)
1480 barrierAction := a.Deps[0]
1481 buildAction := barrierAction.Deps[0]
1482
1483
1484 select {
1485 case <-r.prev:
1486
1487 if testShouldFailFast.Load() {
1488 close(r.next)
1489 return nil
1490 }
1491 case <-base.Interrupted:
1492
1493
1494
1495 base.SetExitStatus(1)
1496 return nil
1497 }
1498
1499
1500
1501
1502 streamOutput := len(pkgArgs) == 0 || testBench != "" || testFuzz != ""
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518 streamAndCacheOutput := testShowPass() && (len(pkgs) == 1 || cfg.BuildP == 1) || testJSON
1519
1520 var stdout io.Writer = os.Stdout
1521 var err error
1522 var json *test2json.Converter
1523 if testJSON {
1524 json = test2json.NewConverter(lockedStdout{}, a.Package.ImportPath, test2json.Timestamp)
1525 defer func() {
1526 json.Exited(err)
1527 json.Close()
1528 }()
1529 stdout = json
1530 }
1531
1532 var buf bytes.Buffer
1533 if streamOutput {
1534
1535 } else if streamAndCacheOutput {
1536
1537
1538 stdout = io.MultiWriter(stdout, &buf)
1539 } else {
1540 stdout = &buf
1541 }
1542
1543
1544 close(r.next)
1545
1546 if a.Failed != nil {
1547 if buildAction.Failed == nil {
1548 for _, dep := range barrierAction.Deps {
1549 if dep.Mode == "vet" && dep.Failed != nil {
1550 b.ReportDeferredVetError(dep.Failed)
1551 }
1552 }
1553 } else {
1554 a.Failed = buildAction.Failed
1555 }
1556
1557 if json != nil && a.Failed.Package != nil {
1558 if gotestjsonbuildtext.Value() == "1" {
1559 gotestjsonbuildtext.IncNonDefault()
1560 } else {
1561 json.SetFailedBuild(a.Failed.Package.Desc())
1562 }
1563 }
1564 a.Failed = nil
1565 fmt.Fprintf(stdout, "FAIL\t%s [build failed]\n", a.Package.ImportPath)
1566
1567 err = errors.New("build failed")
1568 base.SetExitStatus(1)
1569 if stdout == &buf {
1570 a.TestOutput = &buf
1571 }
1572 return nil
1573 }
1574
1575 if p := a.Package; len(p.TestGoFiles)+len(p.XTestGoFiles) == 0 {
1576 reportNoTestFiles := true
1577 if cfg.BuildCover && p.Internal.Cover.GenMeta {
1578 if err := sh.Mkdir(a.Objdir); err != nil {
1579 return err
1580 }
1581 mf, err := work.BuildActionCoverMetaFile(a)
1582 if err != nil {
1583 return err
1584 } else if mf != "" {
1585 reportNoTestFiles = false
1586
1587 if err := work.WriteCoveragePercent(b, a, mf, stdout); err != nil {
1588 return err
1589 }
1590
1591
1592
1593 if coverMerge.f != nil {
1594 cp := coverProfTempFile(a)
1595 if err := work.WriteCoverageProfile(b, a, mf, cp, stdout); err != nil {
1596 return err
1597 }
1598 mergeCoverProfile(cp)
1599 }
1600 }
1601 }
1602 if reportNoTestFiles {
1603 fmt.Fprintf(stdout, "? \t%s\t[no test files]\n", p.ImportPath)
1604 }
1605 if stdout == &buf {
1606 a.TestOutput = &buf
1607 }
1608 return nil
1609 }
1610
1611 if r.c.buf == nil {
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621 r.c.tryCacheWithID(b, a, buildAction.BuildContentID())
1622 }
1623 if r.c.buf != nil {
1624 if stdout != &buf {
1625 stdout.Write(r.c.buf.Bytes())
1626 r.c.buf.Reset()
1627 }
1628 a.TestOutput = r.c.buf
1629 return nil
1630 }
1631
1632 execCmd := work.FindExecCmd()
1633 testlogArg := []string{}
1634 if !r.c.disableCache && len(execCmd) == 0 {
1635 testlogArg = []string{"-test.testlogfile=" + a.Objdir + "testlog.txt"}
1636 }
1637 panicArg := "-test.paniconexit0"
1638 fuzzArg := []string{}
1639 if testFuzz != "" {
1640 fuzzCacheDir := filepath.Join(cache.Default().FuzzDir(), a.Package.ImportPath)
1641 fuzzArg = []string{"-test.fuzzcachedir=" + fuzzCacheDir}
1642 }
1643 coverdirArg := []string{}
1644 addToEnv := ""
1645 if cfg.BuildCover {
1646 gcd := filepath.Join(a.Objdir, "gocoverdir")
1647 if err := sh.Mkdir(gcd); err != nil {
1648
1649
1650
1651
1652
1653 base.Fatalf("failed to create temporary dir: %v", err)
1654 }
1655 coverdirArg = append(coverdirArg, "-test.gocoverdir="+gcd)
1656 if r.writeCoverMetaAct != nil {
1657
1658
1659
1660 src := r.writeCoverMetaAct.Objdir + coverage.MetaFilesFileName
1661 dst := filepath.Join(gcd, coverage.MetaFilesFileName)
1662 if err := sh.CopyFile(dst, src, 0666, false); err != nil {
1663 return err
1664 }
1665 }
1666
1667
1668
1669
1670 addToEnv = "GOCOVERDIR=" + gcd
1671 }
1672 args := str.StringList(execCmd, buildAction.BuiltTarget(), testlogArg, panicArg, fuzzArg, coverdirArg, testArgs)
1673
1674 if testCoverProfile != "" {
1675
1676 for i, arg := range args {
1677 if strings.HasPrefix(arg, "-test.coverprofile=") {
1678 args[i] = "-test.coverprofile=" + coverProfTempFile(a)
1679 }
1680 }
1681 }
1682
1683 if cfg.BuildN || cfg.BuildX {
1684 sh.ShowCmd("", "%s", strings.Join(args, " "))
1685 if cfg.BuildN {
1686 return nil
1687 }
1688 }
1689
1690
1691
1692 ctx, cancel := context.WithTimeout(ctx, testKillTimeout)
1693 defer cancel()
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706 var (
1707 cmd *exec.Cmd
1708 t0 time.Time
1709 cancelKilled = false
1710 cancelSignaled = false
1711 )
1712 for {
1713 cmd = exec.CommandContext(ctx, args[0], args[1:]...)
1714 cmd.Dir = a.Package.Dir
1715
1716 env := slices.Clip(cfg.OrigEnv)
1717 env = base.AppendPATH(env)
1718 env = base.AppendPWD(env, cmd.Dir)
1719 cmd.Env = env
1720 if addToEnv != "" {
1721 cmd.Env = append(cmd.Env, addToEnv)
1722 }
1723
1724 cmd.Stdout = stdout
1725 cmd.Stderr = stdout
1726
1727 cmd.Cancel = func() error {
1728 if base.SignalTrace == nil {
1729 err := cmd.Process.Kill()
1730 if err == nil {
1731 cancelKilled = true
1732 }
1733 return err
1734 }
1735
1736
1737
1738 err := cmd.Process.Signal(base.SignalTrace)
1739 if err == nil {
1740 cancelSignaled = true
1741 }
1742 return err
1743 }
1744 cmd.WaitDelay = testWaitDelay
1745
1746 base.StartSigHandlers()
1747 t0 = time.Now()
1748 err = cmd.Run()
1749
1750 if !base.IsETXTBSY(err) {
1751
1752
1753 break
1754 }
1755 }
1756
1757 out := buf.Bytes()
1758 a.TestOutput = &buf
1759 t := fmt.Sprintf("%.3fs", time.Since(t0).Seconds())
1760
1761 mergeCoverProfile(coverProfTempFile(a))
1762
1763 if err == nil {
1764 norun := ""
1765 if !testShowPass() && !testJSON {
1766 buf.Reset()
1767 }
1768 if bytes.HasPrefix(out, noTestsToRun[1:]) || bytes.Contains(out, noTestsToRun) {
1769 norun = " [no tests to run]"
1770 }
1771 if bytes.HasPrefix(out, noFuzzTestsToFuzz[1:]) || bytes.Contains(out, noFuzzTestsToFuzz) {
1772 norun = " [no fuzz tests to fuzz]"
1773 }
1774 if bytes.HasPrefix(out, tooManyFuzzTestsToFuzz[1:]) || bytes.Contains(out, tooManyFuzzTestsToFuzz) {
1775 norun = "[-fuzz matches more than one fuzz test, won't fuzz]"
1776 }
1777
1778
1779
1780
1781 if buf.Len() > 0 && !bytes.HasSuffix(buf.Bytes(), []byte("\n")) {
1782 cmd.Stdout.Write([]byte("\n"))
1783 }
1784 fmt.Fprintf(cmd.Stdout, "ok \t%s\t%s%s%s\n", a.Package.ImportPath, t, coveragePercentage(out), norun)
1785 r.c.saveOutput(a)
1786 } else {
1787 if testFailFast {
1788 testShouldFailFast.Store(true)
1789 }
1790
1791 base.SetExitStatus(1)
1792 if cancelSignaled {
1793 fmt.Fprintf(cmd.Stdout, "*** Test killed with %v: ran too long (%v).\n", base.SignalTrace, testKillTimeout)
1794 } else if cancelKilled {
1795 fmt.Fprintf(cmd.Stdout, "*** Test killed: ran too long (%v).\n", testKillTimeout)
1796 } else if errors.Is(err, exec.ErrWaitDelay) {
1797 fmt.Fprintf(cmd.Stdout, "*** Test I/O incomplete %v after exiting.\n", cmd.WaitDelay)
1798 }
1799 if ee, ok := errors.AsType[*exec.ExitError](err); !ok || !ee.Exited() || len(out) == 0 {
1800
1801
1802 fmt.Fprintf(cmd.Stdout, "%s\n", err)
1803 } else if !bytes.HasSuffix(out, []byte("\n")) {
1804
1805
1806 cmd.Stdout.Write([]byte("\n"))
1807 }
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817 prefix := ""
1818 if testJSON || testV.json {
1819 prefix = "\x16"
1820 }
1821 fmt.Fprintf(cmd.Stdout, "%sFAIL\t%s\t%s\n", prefix, a.Package.ImportPath, t)
1822 }
1823
1824 if cmd.Stdout != &buf {
1825 buf.Reset()
1826 }
1827 return nil
1828 }
1829
1830
1831
1832
1833 func (c *runCache) tryCache(b *work.Builder, a *work.Action, linkAction *work.Action) bool {
1834 return c.tryCacheWithID(b, a, linkAction.BuildActionID())
1835 }
1836
1837 func (c *runCache) tryCacheWithID(b *work.Builder, a *work.Action, id string) bool {
1838 if len(pkgArgs) == 0 {
1839
1840
1841 if cache.DebugTest {
1842 fmt.Fprintf(os.Stderr, "testcache: caching disabled in local directory mode\n")
1843 }
1844 c.disableCache = true
1845 return false
1846 }
1847
1848 if a.Package.Root == "" {
1849
1850 if cache.DebugTest {
1851 fmt.Fprintf(os.Stderr, "testcache: caching disabled for package outside of module root, GOPATH, or GOROOT: %s\n", a.Package.ImportPath)
1852 }
1853 c.disableCache = true
1854 return false
1855 }
1856
1857
1858
1859
1860
1861
1862
1863
1864 if len(testCoverPkgs) != 0 {
1865 searchDeps := a.Deps
1866 for _, dep := range a.Deps {
1867 if dep.Mode == "test barrier" {
1868 searchDeps = dep.Deps
1869 break
1870 }
1871 }
1872 for _, dep := range searchDeps {
1873 if dep.Mode == "write coverage meta-data file" {
1874 h := cache.NewHash("covermeta")
1875 for _, metaDep := range dep.Deps {
1876 if aid := metaDep.BuildActionID(); aid != "" {
1877 fmt.Fprintf(h, "dep %s\n", aid)
1878 }
1879 }
1880 c.covMeta = h.Sum()
1881 break
1882 }
1883 }
1884 }
1885
1886 var cacheArgs []string
1887 for _, arg := range testArgs {
1888 i := strings.Index(arg, "=")
1889 if i < 0 || !strings.HasPrefix(arg, "-test.") {
1890 if cache.DebugTest {
1891 fmt.Fprintf(os.Stderr, "testcache: caching disabled for test argument: %s\n", arg)
1892 }
1893 c.disableCache = true
1894 return false
1895 }
1896 switch arg[:i] {
1897 case "-test.benchtime",
1898 "-test.cpu",
1899 "-test.list",
1900 "-test.parallel",
1901 "-test.run",
1902 "-test.short",
1903 "-test.skip",
1904 "-test.timeout",
1905 "-test.failfast",
1906 "-test.v",
1907 "-test.fullpath":
1908
1909
1910
1911 cacheArgs = append(cacheArgs, arg)
1912 case "-test.coverprofile",
1913 "-test.outputdir":
1914
1915
1916
1917 default:
1918
1919 if cache.DebugTest {
1920 fmt.Fprintf(os.Stderr, "testcache: caching disabled for test argument: %s\n", arg)
1921 }
1922 c.disableCache = true
1923 return false
1924 }
1925 }
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952 h := cache.NewHash("testResult")
1953 fmt.Fprintf(h, "test binary %s args %q execcmd %q", id, cacheArgs, work.ExecCmd)
1954 testID := h.Sum()
1955 if c.id1 == (cache.ActionID{}) {
1956 c.id1 = testID
1957 } else {
1958 c.id2 = testID
1959 }
1960 if cache.DebugTest {
1961 fmt.Fprintf(os.Stderr, "testcache: %s: test ID %x => %x\n", a.Package.ImportPath, id, testID)
1962 }
1963
1964
1965
1966 data, entry, err := cache.GetBytes(cache.Default(), testID)
1967 if !bytes.HasPrefix(data, testlogMagic) || data[len(data)-1] != '\n' {
1968 if cache.DebugTest {
1969 if err != nil {
1970 fmt.Fprintf(os.Stderr, "testcache: %s: input list not found: %v\n", a.Package.ImportPath, err)
1971 } else {
1972 fmt.Fprintf(os.Stderr, "testcache: %s: input list malformed\n", a.Package.ImportPath)
1973 }
1974 }
1975 return false
1976 }
1977 testInputsID, err := computeTestInputsID(a, data, nil)
1978 if err != nil {
1979 return false
1980 }
1981 if cache.DebugTest {
1982 fmt.Fprintf(os.Stderr, "testcache: %s: test ID %x => input ID %x => %x\n", a.Package.ImportPath, testID, testInputsID, testAndInputKey(testID, testInputsID))
1983 }
1984
1985
1986
1987 data, entry, err = cache.GetBytes(cache.Default(), testAndInputKey(testID, testInputsID))
1988
1989
1990 if testCoverProfile != "" {
1991
1992 cpData, _, err := cache.GetFile(cache.Default(), coverProfileAndInputKey(testID, testInputsID, c.covMeta))
1993 if err != nil {
1994 if cache.DebugTest {
1995 fmt.Fprintf(os.Stderr, "testcache: %s: cached cover profile missing: %v\n", a.Package.ImportPath, err)
1996 }
1997 return false
1998 }
1999 mergeCoverProfile(cpData)
2000 } else if c.covMeta != (cache.ActionID{}) {
2001
2002
2003
2004
2005 _, _, err := cache.GetFile(cache.Default(), coverProfileAndInputKey(testID, testInputsID, c.covMeta))
2006 if err != nil {
2007 if cache.DebugTest {
2008 fmt.Fprintf(os.Stderr, "testcache: %s: coverage metadata changed, re-running test: %v\n", a.Package.ImportPath, err)
2009 }
2010 return false
2011 }
2012 }
2013
2014 if len(data) == 0 || data[len(data)-1] != '\n' {
2015 if cache.DebugTest {
2016 if err != nil {
2017 fmt.Fprintf(os.Stderr, "testcache: %s: test output not found: %v\n", a.Package.ImportPath, err)
2018 } else {
2019 fmt.Fprintf(os.Stderr, "testcache: %s: test output malformed\n", a.Package.ImportPath)
2020 }
2021 }
2022 return false
2023 }
2024 if entry.Time.Before(testCacheExpire) {
2025 if cache.DebugTest {
2026 fmt.Fprintf(os.Stderr, "testcache: %s: test output expired due to go clean -testcache\n", a.Package.ImportPath)
2027 }
2028 return false
2029 }
2030 i := bytes.LastIndexByte(data[:len(data)-1], '\n') + 1
2031 if !bytes.HasPrefix(data[i:], []byte("ok \t")) {
2032 if cache.DebugTest {
2033 fmt.Fprintf(os.Stderr, "testcache: %s: test output malformed\n", a.Package.ImportPath)
2034 }
2035 return false
2036 }
2037 j := bytes.IndexByte(data[i+len("ok \t"):], '\t')
2038 if j < 0 {
2039 if cache.DebugTest {
2040 fmt.Fprintf(os.Stderr, "testcache: %s: test output malformed\n", a.Package.ImportPath)
2041 }
2042 return false
2043 }
2044 j += i + len("ok \t") + 1
2045
2046
2047 c.buf = new(bytes.Buffer)
2048 c.buf.Write(data[:j])
2049 c.buf.WriteString("(cached)")
2050 for j < len(data) && ('0' <= data[j] && data[j] <= '9' || data[j] == '.' || data[j] == 's') {
2051 j++
2052 }
2053 c.buf.Write(data[j:])
2054 return true
2055 }
2056
2057 var errBadTestInputs = errors.New("error parsing test inputs")
2058 var errFileNotInRoot = errors.New("file used as input is not in package root")
2059 var testlogMagic = []byte("# test log\n")
2060
2061
2062 type logOp struct {
2063 op string
2064 name string
2065 }
2066
2067
2068 var testInputsQueue = par.NewQueue(runtime.GOMAXPROCS(0))
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078 func computeTestInputsID(a *work.Action, testlog []byte, inputs *bytes.Buffer) (cache.ActionID, error) {
2079 testlog = bytes.TrimPrefix(testlog, testlogMagic)
2080 h := cache.NewHash("testInputs")
2081
2082 fmt.Fprintf(h, "getenv GODEBUG %x\n", hashGetenv("GODEBUG"))
2083 pwd := a.Package.Dir
2084
2085
2086
2087
2088
2089
2090
2091 var logOps []logOp
2092 var logOpCache par.ErrCache[logOp, cache.ActionID]
2093 work := make(map[logOp]func())
2094 add := func(op, name string, f func() (cache.ActionID, error)) {
2095 logOp := logOp{op: op, name: name}
2096 logOps = append(logOps, logOp)
2097 work[logOp] = func() { logOpCache.Do(logOp, f) }
2098 }
2099 for _, line := range bytes.Split(testlog, []byte("\n")) {
2100 if len(line) == 0 {
2101 continue
2102 }
2103 s := string(line)
2104 op, name, found := strings.Cut(s, " ")
2105 if !found {
2106 if cache.DebugTest {
2107 fmt.Fprintf(os.Stderr, "testcache: %s: input list malformed (%q)\n", a.Package.ImportPath, line)
2108 }
2109 return cache.ActionID{}, errBadTestInputs
2110 }
2111 switch op {
2112 default:
2113 if cache.DebugTest {
2114 fmt.Fprintf(os.Stderr, "testcache: %s: input list malformed (%q)\n", a.Package.ImportPath, line)
2115 }
2116 return cache.ActionID{}, errBadTestInputs
2117 case "getenv":
2118 add(op, name, func() (cache.ActionID, error) {
2119 return hashGetenv(name), nil
2120 })
2121 case "chdir":
2122 pwd = name
2123 add(op, name, func() (cache.ActionID, error) {
2124 return hashStat(name), nil
2125 })
2126 case "stat":
2127 if !filepath.IsAbs(name) {
2128 name = filepath.Join(pwd, name)
2129 }
2130 add(op, name, func() (cache.ActionID, error) {
2131 if a.Package.Root == "" || search.InDir(name, a.Package.Root) == "" {
2132
2133 return cache.ActionID{}, errFileNotInRoot
2134 }
2135 return hashStat(name), nil
2136 })
2137 case "open":
2138 if !filepath.IsAbs(name) {
2139 name = filepath.Join(pwd, name)
2140 }
2141 add(op, name, func() (cache.ActionID, error) {
2142 if a.Package.Root == "" || search.InDir(name, a.Package.Root) == "" {
2143
2144 return cache.ActionID{}, errFileNotInRoot
2145 }
2146 return hashOpen(name)
2147 })
2148 }
2149 }
2150
2151
2152
2153 chunkCount := 10 * runtime.GOMAXPROCS(0)
2154 chunkSize := max((len(work)+chunkCount-1)/chunkCount, 1)
2155 var wg sync.WaitGroup
2156 for chunk := range slices.Chunk(slices.Collect(maps.Values(work)), chunkSize) {
2157 wg.Add(1)
2158 testInputsQueue.Add(func() {
2159 defer wg.Done()
2160 for _, f := range chunk {
2161 f()
2162 }
2163 })
2164 }
2165 wg.Wait()
2166
2167
2168
2169 if inputs != nil {
2170 inputs.Write(testlogMagic)
2171 }
2172 for _, l := range logOps {
2173 op, name := l.op, l.name
2174 actionID, err := logOpCache.Get(logOp{op: op, name: name})
2175 switch {
2176 case errors.Is(err, par.ErrCacheEntryNotFound):
2177 panic("failed to find expected test log cache result")
2178 case errors.Is(err, errFileNotInRoot):
2179 continue
2180 case err != nil:
2181 if cache.DebugTest {
2182 fmt.Fprintf(os.Stderr, "testcache: %s: input file %s: %s\n", a.Package.ImportPath, name, err)
2183 }
2184 return cache.ActionID{}, err
2185 }
2186
2187 fmt.Fprintf(h, "%s %s %x\n", op, name, actionID)
2188 if inputs != nil {
2189 fmt.Fprintf(inputs, "%s %s\n", op, name)
2190 }
2191 }
2192
2193 sum := h.Sum()
2194 return sum, nil
2195 }
2196
2197 func hashGetenv(name string) cache.ActionID {
2198 h := cache.NewHash("getenv")
2199 v, ok := os.LookupEnv(name)
2200 if !ok {
2201 h.Write([]byte{0})
2202 } else {
2203 h.Write([]byte{1})
2204 h.Write([]byte(v))
2205 }
2206 return h.Sum()
2207 }
2208
2209 const modTimeCutoff = 2 * time.Second
2210
2211 var errFileTooNew = errors.New("file used as input is too new")
2212
2213 func hashOpen(name string) (cache.ActionID, error) {
2214 h := cache.NewHash("open")
2215 info, err := os.Stat(name)
2216 if err != nil {
2217 fmt.Fprintf(h, "err %v\n", err)
2218 return h.Sum(), nil
2219 }
2220 hashWriteStat(h, info)
2221 if info.IsDir() {
2222 files, err := os.ReadDir(name)
2223 if err != nil {
2224 fmt.Fprintf(h, "err %v\n", err)
2225 }
2226 for _, f := range files {
2227 fmt.Fprintf(h, "file %s ", f.Name())
2228 finfo, err := f.Info()
2229 if err != nil {
2230 fmt.Fprintf(h, "err %v\n", err)
2231 } else {
2232 hashWriteStat(h, finfo)
2233 }
2234 }
2235 } else if info.Mode().IsRegular() {
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245 if time.Since(info.ModTime()) < modTimeCutoff {
2246 return cache.ActionID{}, errFileTooNew
2247 }
2248 }
2249 return h.Sum(), nil
2250 }
2251
2252 func hashStat(name string) cache.ActionID {
2253 h := cache.NewHash("stat")
2254 if info, err := os.Stat(name); err != nil {
2255 fmt.Fprintf(h, "err %v\n", err)
2256 } else {
2257 hashWriteStat(h, info)
2258 }
2259 if info, err := os.Lstat(name); err != nil {
2260 fmt.Fprintf(h, "err %v\n", err)
2261 } else {
2262 hashWriteStat(h, info)
2263 }
2264 return h.Sum()
2265 }
2266
2267 func hashWriteStat(h io.Writer, info fs.FileInfo) {
2268 fmt.Fprintf(h, "stat %d %x %v %v\n", info.Size(), uint64(info.Mode()), info.ModTime(), info.IsDir())
2269 }
2270
2271
2272 func testAndInputKey(testID, testInputsID cache.ActionID) cache.ActionID {
2273 return cache.Subkey(testID, fmt.Sprintf("inputs:%x", testInputsID))
2274 }
2275
2276
2277
2278
2279 func coverProfileAndInputKey(testID, testInputsID, covMetaID cache.ActionID) cache.ActionID {
2280 key := testAndInputKey(testID, testInputsID)
2281 if covMetaID != (cache.ActionID{}) {
2282 key = cache.Subkey(key, fmt.Sprintf("coverdeps:%x", covMetaID))
2283 }
2284 return cache.Subkey(key, "coverprofile")
2285 }
2286
2287 func (c *runCache) saveOutput(a *work.Action) {
2288 if c.id1 == (cache.ActionID{}) && c.id2 == (cache.ActionID{}) {
2289 return
2290 }
2291
2292
2293 testlog, err := os.ReadFile(a.Objdir + "testlog.txt")
2294 if err != nil || !bytes.HasPrefix(testlog, testlogMagic) || testlog[len(testlog)-1] != '\n' {
2295 if cache.DebugTest {
2296 if err != nil {
2297 fmt.Fprintf(os.Stderr, "testcache: %s: reading testlog: %v\n", a.Package.ImportPath, err)
2298 } else {
2299 fmt.Fprintf(os.Stderr, "testcache: %s: reading testlog: malformed\n", a.Package.ImportPath)
2300 }
2301 }
2302 return
2303 }
2304
2305
2306
2307 var inputs bytes.Buffer
2308 testInputsID, err := computeTestInputsID(a, testlog, &inputs)
2309 if err != nil {
2310 return
2311 }
2312 testlog = inputs.Bytes()
2313 var coverProfile []byte
2314 if testCoverProfile != "" {
2315 coverProfile, err = os.ReadFile(coverProfTempFile(a))
2316 if err != nil {
2317 if cache.DebugTest {
2318 fmt.Fprintf(os.Stderr, "testcache: %s: reading cover profile: %v\n", a.Package.ImportPath, err)
2319 }
2320 return
2321 }
2322 }
2323 if c.id1 != (cache.ActionID{}) {
2324 if cache.DebugTest {
2325 fmt.Fprintf(os.Stderr, "testcache: %s: save test ID %x => input ID %x => %x\n", a.Package.ImportPath, c.id1, testInputsID, testAndInputKey(c.id1, testInputsID))
2326 }
2327 cache.PutNoVerify(cache.Default(), c.id1, bytes.NewReader(testlog))
2328 cache.PutNoVerify(cache.Default(), testAndInputKey(c.id1, testInputsID), bytes.NewReader(a.TestOutput.Bytes()))
2329 if coverProfile != nil {
2330 cache.PutNoVerify(cache.Default(), coverProfileAndInputKey(c.id1, testInputsID, c.covMeta), bytes.NewReader(coverProfile))
2331 } else if c.covMeta != (cache.ActionID{}) {
2332
2333
2334 cache.PutNoVerify(cache.Default(), coverProfileAndInputKey(c.id1, testInputsID, c.covMeta), bytes.NewReader(nil))
2335 }
2336 }
2337 if c.id2 != (cache.ActionID{}) {
2338 if cache.DebugTest {
2339 fmt.Fprintf(os.Stderr, "testcache: %s: save test ID %x => input ID %x => %x\n", a.Package.ImportPath, c.id2, testInputsID, testAndInputKey(c.id2, testInputsID))
2340 }
2341 cache.PutNoVerify(cache.Default(), c.id2, bytes.NewReader(testlog))
2342 cache.PutNoVerify(cache.Default(), testAndInputKey(c.id2, testInputsID), bytes.NewReader(a.TestOutput.Bytes()))
2343 if coverProfile != nil {
2344 cache.PutNoVerify(cache.Default(), coverProfileAndInputKey(c.id2, testInputsID, c.covMeta), bytes.NewReader(coverProfile))
2345 } else if c.covMeta != (cache.ActionID{}) {
2346
2347 cache.PutNoVerify(cache.Default(), coverProfileAndInputKey(c.id2, testInputsID, c.covMeta), bytes.NewReader(nil))
2348 }
2349 }
2350 }
2351
2352
2353
2354 func coveragePercentage(out []byte) string {
2355 if !cfg.BuildCover {
2356 return ""
2357 }
2358
2359
2360
2361 re := regexp.MustCompile(`coverage: (.*)\n`)
2362 matches := re.FindSubmatch(out)
2363 if matches == nil {
2364
2365
2366 return ""
2367 }
2368 return fmt.Sprintf("\tcoverage: %s", matches[1])
2369 }
2370
2371
2372 func builderCleanTest(b *work.Builder, ctx context.Context, a *work.Action) error {
2373 if cfg.BuildWork {
2374 return nil
2375 }
2376 b.Shell(a).RemoveAll(a.Objdir)
2377 return nil
2378 }
2379
2380
2381 func builderPrintTest(b *work.Builder, ctx context.Context, a *work.Action) error {
2382 run := a.Deps[0]
2383 if run.Mode == "test clean" {
2384 run = run.Deps[0]
2385 }
2386 if run.Mode != "test run" {
2387 base.Fatalf("internal error: cannot find test run to print")
2388 }
2389 if run.TestOutput != nil {
2390 os.Stdout.Write(run.TestOutput.Bytes())
2391 run.TestOutput = nil
2392 }
2393 return nil
2394 }
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411 func printExitStatus(b *work.Builder, ctx context.Context, a *work.Action) error {
2412 if !testJSON && testFuzz == "" && len(pkgArgs) != 0 {
2413 if base.GetExitStatus() != 0 {
2414 fmt.Println("FAIL")
2415 return nil
2416 }
2417 }
2418 return nil
2419 }
2420
2421
2422
2423
2424
2425
2426 func testBinaryName(p *load.Package) string {
2427 var elem string
2428 if p.ImportPath == "command-line-arguments" {
2429 elem = p.Name
2430 } else {
2431 elem = p.DefaultExecName()
2432 }
2433
2434 return elem + ".test"
2435 }
2436
View as plain text