1 // Copyright 2011 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.
33 "cmd/go/internal/base"
34 "cmd/go/internal/cache"
36 "cmd/go/internal/load"
38 "cmd/go/internal/work"
39 "cmd/internal/test2json"
47 const testUsage
= "test [build/test flags] [packages] [build/test flags & test binary flags]"
49 var CmdTest
= &base
.Command
{
52 Short
: "test packages",
54 'Go test' automates testing the packages named by the import paths.
55 It prints a summary of the test results in the format:
58 FAIL archive/zip 0.022s
59 ok compress/gzip 0.033s
62 followed by detailed output for each failed package.
64 'Go test' recompiles each package along with any files with names matching
65 the file pattern "*_test.go".
66 These additional files can contain test functions, benchmark functions, and
67 example functions. See 'go help testfunc' for more.
68 Each listed package causes the execution of a separate test binary.
69 Files whose names begin with "_" (including "_test.go") or "." are ignored.
71 Test files that declare a package with the suffix "_test" will be compiled as a
72 separate package, and then linked and run with the main test binary.
74 The go tool will ignore a directory named "testdata", making it available
75 to hold ancillary data needed by the tests.
77 As part of building a test binary, go test runs go vet on the package
78 and its test source files to identify significant problems. If go vet
79 finds any problems, go test reports those and does not run the test binary.
80 Only a high-confidence subset of the default go vet checks are used.
81 To disable the running of go vet, use the -vet=off flag.
83 All test output and summary lines are printed to the go command's
84 standard output, even if the test printed them to its own standard
85 error. (The go command's standard error is reserved for printing
86 errors building the tests.)
88 Go test runs in two different modes:
90 The first, called local directory mode, occurs when go test is
91 invoked with no package arguments (for example, 'go test' or 'go
92 test -v'). In this mode, go test compiles the package sources and
93 tests found in the current directory and then runs the resulting
94 test binary. In this mode, caching (discussed below) is disabled.
95 After the package test finishes, go test prints a summary line
96 showing the test status ('ok' or 'FAIL'), package name, and elapsed
99 The second, called package list mode, occurs when go test is invoked
100 with explicit package arguments (for example 'go test math', 'go
101 test ./...', and even 'go test .'). In this mode, go test compiles
102 and tests each of the packages listed on the command line. If a
103 package test passes, go test prints only the final 'ok' summary
104 line. If a package test fails, go test prints the full test output.
105 If invoked with the -bench or -v flag, go test prints the full
106 output even for passing package tests, in order to display the
107 requested benchmark results or verbose logging.
109 In package list mode only, go test caches successful package test
110 results to avoid unnecessary repeated running of tests. When the
111 result of a test can be recovered from the cache, go test will
112 redisplay the previous output instead of running the test binary
113 again. When this happens, go test prints '(cached)' in place of the
114 elapsed time in the summary line.
116 The rule for a match in the cache is that the run involves the same
117 test binary and the flags on the command line come entirely from a
118 restricted set of 'cacheable' test flags, defined as -cpu, -list,
119 -parallel, -run, -short, and -v. If a run of go test has any test
120 or non-test flags outside this set, the result is not cached. To
121 disable test caching, use any test flag or argument other than the
122 cacheable flags. The idiomatic way to disable test caching explicitly
123 is to use -count=1. Tests that open files within the package's source
124 root (usually $GOPATH) or that consult environment variables only
125 match future runs in which the files and environment variables are unchanged.
126 A cached test result is treated as executing in no time at all,
127 so a successful package test result will be cached and reused
128 regardless of -timeout setting.
130 ` + strings
.TrimSpace(testFlag1
) + ` See 'go help testflag' for details.
132 For more about build flags, see 'go help build'.
133 For more about specifying packages, see 'go help packages'.
135 See also: go build, go vet.
140 In addition to the build flags, the flags handled by 'go test' itself are:
143 Pass the remainder of the command line (everything after -args)
144 to the test binary, uninterpreted and unchanged.
145 Because this flag consumes the remainder of the command line,
146 the package list (if present) must appear before this flag.
149 Compile the test binary to pkg.test but do not run it
150 (where pkg is the last element of the package's import path).
151 The file name can be changed with the -o flag.
154 Run the test binary using xprog. The behavior is the same as
155 in 'go run'. See 'go help run' for details.
158 Install packages that are dependencies of the test.
162 Convert test output to JSON suitable for automated processing.
163 See 'go doc test2json' for the encoding details.
166 Compile the test binary to the named file.
167 The test still runs (unless -c or -i is specified).
169 The test binary also accepts flags that control execution of the test; these
170 flags are also accessible by 'go test'.
173 // Usage prints the usage message for 'go test -h' and exits.
175 os
.Stderr
.WriteString(testUsage
+ "\n\n" +
176 strings
.TrimSpace(testFlag1
) + "\n\n\t" +
177 strings
.TrimSpace(testFlag2
) + "\n")
181 var HelpTestflag
= &base
.Command
{
182 UsageLine
: "testflag",
183 Short
: "testing flags",
185 The 'go test' command takes both flags that apply to 'go test' itself
186 and flags that apply to the resulting test binary.
188 Several of the flags control profiling and write an execution profile
189 suitable for "go tool pprof"; run "go tool pprof -h" for more
190 information. The --alloc_space, --alloc_objects, and --show_bytes
191 options of pprof control how the information is presented.
193 The following flags are recognized by the 'go test' command and
194 control the execution of any test:
196 ` + strings
.TrimSpace(testFlag2
) + `
202 Run only those benchmarks matching a regular expression.
203 By default, no benchmarks are run.
204 To run all benchmarks, use '-bench .' or '-bench=.'.
205 The regular expression is split by unbracketed slash (/)
206 characters into a sequence of regular expressions, and each
207 part of a benchmark's identifier must match the corresponding
208 element in the sequence, if any. Possible parents of matches
209 are run with b.N=1 to identify sub-benchmarks. For example,
210 given -bench=X/Y, top-level benchmarks matching X are run
211 with b.N=1 to find any sub-benchmarks matching Y, which are
215 Run enough iterations of each benchmark to take t, specified
216 as a time.Duration (for example, -benchtime 1h30s).
217 The default is 1 second (1s).
220 Run each test and benchmark n times (default 1).
221 If -cpu is set, run n times for each GOMAXPROCS value.
222 Examples are always run once.
225 Enable coverage analysis.
226 Note that because coverage works by annotating the source
227 code before compilation, compilation and test failures with
228 coverage enabled may report line numbers that don't correspond
229 to the original sources.
231 -covermode set,count,atomic
232 Set the mode for coverage analysis for the package[s]
233 being tested. The default is "set" unless -race is enabled,
234 in which case it is "atomic".
236 set: bool: does this statement run?
237 count: int: how many times does this statement run?
238 atomic: int: count, but correct in multithreaded tests;
239 significantly more expensive.
242 -coverpkg pattern1,pattern2,pattern3
243 Apply coverage analysis in each test to packages matching the patterns.
244 The default is for each test to analyze only the package being tested.
245 See 'go help packages' for a description of package patterns.
249 Specify a list of GOMAXPROCS values for which the tests or
250 benchmarks should be executed. The default is the current value
254 Do not start new tests after the first test failure.
257 List tests, benchmarks, or examples matching the regular expression.
258 No tests, benchmarks or examples will be run. This will only
259 list top-level tests. No subtest or subbenchmarks will be shown.
262 Allow parallel execution of test functions that call t.Parallel.
263 The value of this flag is the maximum number of tests to run
264 simultaneously; by default, it is set to the value of GOMAXPROCS.
265 Note that -parallel only applies within a single test binary.
266 The 'go test' command may run tests for different packages
267 in parallel as well, according to the setting of the -p flag
268 (see 'go help build').
271 Run only those tests and examples matching the regular expression.
272 For tests, the regular expression is split by unbracketed slash (/)
273 characters into a sequence of regular expressions, and each part
274 of a test's identifier must match the corresponding element in
275 the sequence, if any. Note that possible parents of matches are
276 run too, so that -run=X/Y matches and runs and reports the result
277 of all tests matching X, even those without sub-tests matching Y,
278 because it must run them to look for those sub-tests.
281 Tell long-running tests to shorten their run time.
282 It is off by default but set during all.bash so that installing
283 the Go tree can run a sanity check but not spend time running
287 If a test binary runs longer than duration d, panic.
288 If d is 0, the timeout is disabled.
289 The default is 10 minutes (10m).
292 Verbose output: log all tests as they are run. Also print all
293 text from Log and Logf calls even if the test succeeds.
296 Configure the invocation of "go vet" during "go test"
297 to use the comma-separated list of vet checks.
298 If list is empty, "go test" runs "go vet" with a curated list of
299 checks believed to be always worth addressing.
300 If list is "off", "go test" does not run "go vet" at all.
302 The following flags are also recognized by 'go test' and can be used to
303 profile the tests during execution:
306 Print memory allocation statistics for benchmarks.
308 -blockprofile block.out
309 Write a goroutine blocking profile to the specified file
310 when all tests are complete.
311 Writes test binary as -c would.
314 Control the detail provided in goroutine blocking profiles by
315 calling runtime.SetBlockProfileRate with n.
316 See 'go doc runtime.SetBlockProfileRate'.
317 The profiler aims to sample, on average, one blocking event every
318 n nanoseconds the program spends blocked. By default,
319 if -test.blockprofile is set without this flag, all blocking events
320 are recorded, equivalent to -test.blockprofilerate=1.
322 -coverprofile cover.out
323 Write a coverage profile to the file after all tests have passed.
327 Write a CPU profile to the specified file before exiting.
328 Writes test binary as -c would.
331 Write a memory profile to the file after all tests have passed.
332 Writes test binary as -c would.
335 Enable more precise (and expensive) memory profiles by setting
336 runtime.MemProfileRate. See 'go doc runtime.MemProfileRate'.
337 To profile all memory allocations, use -test.memprofilerate=1
338 and pass --alloc_space flag to the pprof tool.
340 -mutexprofile mutex.out
341 Write a mutex contention profile to the specified file
342 when all tests are complete.
343 Writes test binary as -c would.
345 -mutexprofilefraction n
346 Sample 1 in n stack traces of goroutines holding a
350 Place output files from profiling in the specified directory,
351 by default the directory in which "go test" is running.
354 Write an execution trace to the specified file before exiting.
356 Each of these flags is also recognized with an optional 'test.' prefix,
357 as in -test.v. When invoking the generated test binary (the result of
358 'go test -c') directly, however, the prefix is mandatory.
360 The 'go test' command rewrites or removes recognized flags,
361 as appropriate, both before and after the optional package list,
362 before invoking the test binary.
364 For instance, the command
366 go test -v -myflag testdata -cpuprofile=prof.out -x
368 will compile the test binary and then run it as
370 pkg.test -test.v -myflag testdata -test.cpuprofile=prof.out
372 (The -x flag is removed because it applies only to the go command's
373 execution, not to the test itself.)
375 The test flags that generate profiles (other than for coverage) also
376 leave the test binary in pkg.test for use when analyzing the profiles.
378 When 'go test' runs a test binary, it does so from within the
379 corresponding package's source code directory. Depending on the test,
380 it may be necessary to do the same when invoking a generated test
383 The command-line package list, if present, must appear before any
384 flag not known to the go test command. Continuing the example above,
385 the package list would have to appear before -myflag, but could appear
386 on either side of -v.
388 To keep an argument for a test binary from being interpreted as a
389 known flag or a package name, use -args (see 'go help test') which
390 passes the remainder of the command line through to the test binary
391 uninterpreted and unaltered.
393 For instance, the command
395 go test -v -args -x -v
397 will compile the test binary and then run it as
399 pkg.test -test.v -x -v
405 will compile the test binary and then run it as
409 In the first example, the -x and the second -v are passed through to the
410 test binary unchanged and with no effect on the go command itself.
411 In the second example, the argument math is passed through to the test
412 binary, instead of being interpreted as the package list.
415 var HelpTestfunc
= &base
.Command
{
416 UsageLine
: "testfunc",
417 Short
: "testing functions",
419 The 'go test' command expects to find test, benchmark, and example functions
420 in the "*_test.go" files corresponding to the package under test.
422 A test function is one named TestXxx (where Xxx does not start with a
423 lower case letter) and should have the signature,
425 func TestXxx(t *testing.T) { ... }
427 A benchmark function is one named BenchmarkXxx and should have the signature,
429 func BenchmarkXxx(b *testing.B) { ... }
431 An example function is similar to a test function but, instead of using
432 *testing.T to report success or failure, prints output to os.Stdout.
433 If the last comment in the function starts with "Output:" then the output
434 is compared exactly against the comment (see examples below). If the last
435 comment begins with "Unordered output:" then the output is compared to the
436 comment, however the order of the lines is ignored. An example with no such
437 comment is compiled but not executed. An example with no text after
438 "Output:" is compiled, executed, and expected to produce no output.
440 Godoc displays the body of ExampleXxx to demonstrate the use
441 of the function, constant, or variable Xxx. An example of a method M with
442 receiver type T or *T is named ExampleT_M. There may be multiple examples
443 for a given function, constant, or variable, distinguished by a trailing _xxx,
444 where xxx is a suffix not beginning with an upper case letter.
446 Here is an example of an example:
448 func ExamplePrintln() {
449 Println("The output of\nthis example.")
450 // Output: The output of
454 Here is another example where the ordering of the output is ignored:
457 for _, value := range Perm(4) {
461 // Unordered output: 4
468 The entire test file is presented as the example when it contains a single
469 example function, at least one other function, type, variable, or constant
470 declaration, and no test or benchmark functions.
472 See the documentation of the testing package for more information.
477 testC
bool // -c flag
478 testCover
bool // -cover flag
479 testCoverMode
string // -covermode flag
480 testCoverPaths
[]string // -coverpkg flag
481 testCoverPkgs
[]*load
.Package
// -coverpkg flag
482 testCoverProfile
string // -coverprofile flag
483 testOutputDir
string // -outputdir flag
484 testO
string // -o flag
485 testProfile
string // profiling flag that limits test to one package
486 testNeedBinary
bool // profile needs to keep binary around
487 testJSON
bool // -json flag
488 testV
bool // -v flag
489 testTimeout
string // -timeout flag
493 testShowPass
bool // show passing output
494 testVetList
string // -vet flag
498 testKillTimeout
= 10 * time
.Minute
499 testCacheExpire time
.Time
// ignore cached test results before this time
502 var testMainDeps
= []string{
503 // Dependencies for testmain.
506 "testing/internal/testdeps",
509 // testVetFlags is the list of flags to pass to vet when invoked automatically during go test.
510 var testVetFlags
= []string{
511 // TODO(rsc): Decide which tests are enabled by default.
512 // See golang.org/issue/18085.
535 func runTest(cmd
*base
.Command
, args
[]string) {
536 pkgArgs
, testArgs
= testFlags(args
)
538 work
.FindExecCmd() // initialize cached result
541 work
.VetFlags
= testVetFlags
543 pkgs
= load
.PackagesForBuild(pkgArgs
)
545 base
.Fatalf("no packages to test")
548 if testC
&& len(pkgs
) != 1 {
549 base
.Fatalf("cannot use -c flag with multiple packages")
551 if testO
!= "" && len(pkgs
) != 1 {
552 base
.Fatalf("cannot use -o flag with multiple packages")
554 if testProfile
!= "" && len(pkgs
) != 1 {
555 base
.Fatalf("cannot use %s flag with multiple packages", testProfile
)
558 defer closeCoverProfile()
560 // If a test timeout was given and is parseable, set our kill timeout
561 // to that timeout plus one minute. This is a backup alarm in case
562 // the test wedges with a goroutine spinning and its background
563 // timer does not get a chance to fire.
564 if dt
, err
:= time
.ParseDuration(testTimeout
); err
== nil && dt
> 0 {
565 testKillTimeout
= dt
+ 1*time
.Minute
566 } else if err
== nil && dt
== 0 {
567 // An explicit zero disables the test timeout.
568 // Let it have one century (almost) before we kill it.
569 testKillTimeout
= 100 * 365 * 24 * time
.Hour
572 // show passing test output (after buffering) with -v flag.
573 // must buffer because tests are running in parallel, and
574 // otherwise the output will get mixed.
575 testShowPass
= testV || testList
577 // For 'go test -i -o x.test', we want to build x.test. Imply -c to make the logic easier.
578 if cfg
.BuildI
&& testO
!= "" {
582 // Read testcache expiration time, if present.
583 // (We implement go clean -testcache by writing an expiration date
584 // instead of searching out and deleting test result cache entries.)
585 if dir
:= cache
.DefaultDir(); dir
!= "off" {
586 if data
, _
:= ioutil
.ReadFile(filepath
.Join(dir
, "testexpire.txt")); len(data
) > 0 && data
[len(data
)-1] == '\n' {
587 if t
, err
:= strconv
.ParseInt(string(data
[:len(data
)-1]), 10, 64); err
== nil {
588 testCacheExpire
= time
.Unix(0, t
)
599 deps
:= make(map[string]bool)
600 for _
, dep
:= range testMainDeps
{
604 for _
, p
:= range pkgs
{
605 // Dependencies for each test.
606 for _
, path
:= range p
.Imports
{
609 for _
, path
:= range p
.Resolve(p
.TestImports
) {
612 for _
, path
:= range p
.Resolve(p
.XTestImports
) {
617 // translate C to runtime/cgo
620 deps
["runtime/cgo"] = true
622 // Ignore pseudo-packages.
623 delete(deps
, "unsafe")
626 for path
:= range deps
{
627 if !build
.IsLocalImport(path
) {
628 all
= append(all
, path
)
633 a
:= &work
.Action
{Mode
: "go test -i"}
634 for _
, p
:= range load
.PackagesForBuild(all
) {
635 if cfg
.BuildToolchainName
== "gccgo" && p
.Standard
{
636 // gccgo's standard library packages
637 // can not be reinstalled.
640 a
.Deps
= append(a
.Deps
, b
.CompileAction(work
.ModeInstall
, work
.ModeInstall
, p
))
643 if !testC || a
.Failed
{
649 var builds
, runs
, prints
[]*work
.Action
651 if testCoverPaths
!= nil {
652 match
:= make([]func(*load
.Package
) bool, len(testCoverPaths
))
653 matched
:= make([]bool, len(testCoverPaths
))
654 for i
:= range testCoverPaths
{
655 match
[i
] = load
.MatchPackage(testCoverPaths
[i
], base
.Cwd
)
658 // Select for coverage all dependencies matching the testCoverPaths patterns.
659 for _
, p
:= range load
.PackageList(pkgs
) {
661 for i
:= range testCoverPaths
{
668 // Silently ignore attempts to run coverage on
669 // sync/atomic when using atomic coverage mode.
670 // Atomic coverage mode uses sync/atomic, so
671 // we can't also do coverage on it.
672 if testCoverMode
== "atomic" && p
.Standard
&& p
.ImportPath
== "sync/atomic" {
676 // If using the race detector, silently ignore
677 // attempts to run coverage on the runtime
678 // packages. It will cause the race detector
679 // to be invoked before it has been initialized.
680 if cfg
.BuildRace
&& p
.Standard
&& (p
.ImportPath
== "runtime" || strings
.HasPrefix(p
.ImportPath
, "runtime/internal")) {
685 testCoverPkgs
= append(testCoverPkgs
, p
)
689 // Warn about -coverpkg arguments that are not actually used.
690 for i
:= range testCoverPaths
{
692 fmt
.Fprintf(os
.Stderr
, "warning: no packages being tested depend on matches for pattern %s\n", testCoverPaths
[i
])
696 // Mark all the coverage packages for rebuilding with coverage.
697 for _
, p
:= range testCoverPkgs
{
698 // There is nothing to cover in package unsafe; it comes from the compiler.
699 if p
.ImportPath
== "unsafe" {
702 p
.Internal
.CoverMode
= testCoverMode
703 var coverFiles
[]string
704 coverFiles
= append(coverFiles
, p
.GoFiles
...)
705 coverFiles
= append(coverFiles
, p
.CgoFiles
...)
706 coverFiles
= append(coverFiles
, p
.TestGoFiles
...)
707 p
.Internal
.CoverVars
= declareCoverVars(p
.ImportPath
, coverFiles
...)
708 if testCover
&& testCoverMode
== "atomic" {
709 ensureImport(p
, "sync/atomic")
714 // Prepare build + run + print actions for all packages being tested.
715 for _
, p
:= range pkgs
{
716 // sync/atomic import is inserted by the cover tool. See #18486
717 if testCover
&& testCoverMode
== "atomic" {
718 ensureImport(p
, "sync/atomic")
721 buildTest
, runTest
, printTest
, err
:= builderTest(&b
, p
)
724 if strings
.HasPrefix(str
, "\n") {
727 failed
:= fmt
.Sprintf("FAIL\t%s [setup failed]\n", p
.ImportPath
)
729 if p
.ImportPath
!= "" {
730 base
.Errorf("# %s\n%s\n%s", p
.ImportPath
, str
, failed
)
732 base
.Errorf("%s\n%s", str
, failed
)
736 builds
= append(builds
, buildTest
)
737 runs
= append(runs
, runTest
)
738 prints
= append(prints
, printTest
)
741 // Ultimately the goal is to print the output.
742 root
:= &work
.Action
{Mode
: "go test", Deps
: prints
}
744 // Force the printing of results to happen in order,
746 for i
, a
:= range prints
{
748 a
.Deps
= append(a
.Deps
, prints
[i
-1])
752 // Force benchmarks to run in serial.
753 if !testC
&& testBench
{
754 // The first run must wait for all builds.
755 // Later runs must wait for the previous run's print.
756 for i
, run
:= range runs
{
758 run
.Deps
= append(run
.Deps
, builds
...)
760 run
.Deps
= append(run
.Deps
, prints
[i
-1])
768 // ensures that package p imports the named package
769 func ensureImport(p
*load
.Package
, pkg
string) {
770 for _
, d
:= range p
.Internal
.Imports
{
776 p1
:= load
.LoadPackage(pkg
, &load
.ImportStack
{})
778 base
.Fatalf("load %s: %v", pkg
, p1
.Error
)
781 p
.Internal
.Imports
= append(p
.Internal
.Imports
, p1
)
784 var windowsBadWords
= []string{
791 func builderTest(b
*work
.Builder
, p
*load
.Package
) (buildAction
, runAction
, printAction
*work
.Action
, err error
) {
792 if len(p
.TestGoFiles
)+len(p
.XTestGoFiles
) == 0 {
793 build
:= b
.CompileAction(work
.ModeBuild
, work
.ModeBuild
, p
)
794 run
:= &work
.Action
{Mode
: "test run", Package
: p
, Deps
: []*work
.Action
{build
}}
795 addTestVet(b
, p
, run
, nil)
796 print := &work
.Action
{Mode
: "test print", Func
: builderNoTest
, Package
: p
, Deps
: []*work
.Action
{run
}}
797 return build
, run
, print, nil
800 // Build Package structs describing:
801 // ptest - package + test files
802 // pxtest - package of external test files
803 // pmain - pkg.test binary
804 var ptest
, pxtest
, pmain
*load
.Package
806 localCover
:= testCover
&& testCoverPaths
== nil
808 ptest
, pxtest
, err
= load
.GetTestPackagesFor(p
, localCover || p
.Name
== "main")
810 return nil, nil, nil, err
813 // Use last element of import path, not package name.
814 // They differ when package name is "main".
815 // But if the import path is "command-line-arguments",
816 // like it is during 'go run', use the package name.
818 if p
.ImportPath
== "command-line-arguments" {
821 _
, elem
= path
.Split(p
.ImportPath
)
823 testBinary
:= elem
+ ".test"
825 // Should we apply coverage analysis locally,
826 // only for this package and only for this test?
827 // Yes, if -cover is on but -coverpkg has not specified
828 // a list of packages for global coverage.
830 ptest
.Internal
.CoverMode
= testCoverMode
831 var coverFiles
[]string
832 coverFiles
= append(coverFiles
, ptest
.GoFiles
...)
833 coverFiles
= append(coverFiles
, ptest
.CgoFiles
...)
834 ptest
.Internal
.CoverVars
= declareCoverVars(ptest
.ImportPath
, coverFiles
...)
837 testDir
:= b
.NewObjdir()
838 if err
:= b
.Mkdir(testDir
); err
!= nil {
839 return nil, nil, nil, err
842 // Action for building pkg.test.
843 pmain
= &load
.Package
{
844 PackagePublic
: load
.PackagePublic
{
847 GoFiles
: []string{"_testmain.go"},
848 ImportPath
: p
.ImportPath
+ " (testmain)",
851 Internal
: load
.PackageInternal
{
852 Build
: &build
.Package
{Name
: "main"},
853 OmitDebug
: !testC
&& !testNeedBinary
,
855 Asmflags
: p
.Internal
.Asmflags
,
856 Gcflags
: p
.Internal
.Gcflags
,
857 Ldflags
: p
.Internal
.Ldflags
,
858 Gccgoflags
: p
.Internal
.Gccgoflags
,
862 // The generated main also imports testing, regexp, and os.
863 // Also the linker introduces implicit dependencies reported by LinkerDeps.
864 var stk load
.ImportStack
866 deps
:= testMainDeps
// cap==len, so safe for append
867 for _
, d
:= range load
.LinkerDeps(p
) {
868 deps
= append(deps
, d
)
870 for _
, dep
:= range deps
{
871 if dep
== ptest
.ImportPath
{
872 pmain
.Internal
.Imports
= append(pmain
.Internal
.Imports
, ptest
)
874 p1
:= load
.LoadImport(dep
, "", nil, &stk
, nil, 0)
876 return nil, nil, nil, p1
.Error
878 pmain
.Internal
.Imports
= append(pmain
.Internal
.Imports
, p1
)
882 if testCoverPkgs
!= nil {
883 // Add imports, but avoid duplicates.
884 seen
:= map[*load
.Package
]bool{p
: true, ptest
: true}
885 for _
, p1
:= range pmain
.Internal
.Imports
{
888 for _
, p1
:= range testCoverPkgs
{
891 pmain
.Internal
.Imports
= append(pmain
.Internal
.Imports
, p1
)
896 // Do initial scan for metadata needed for writing _testmain.go
897 // Use that metadata to update the list of imports for package main.
898 // The list of imports is used by recompileForTest and by the loop
899 // afterward that gathers t.Cover information.
900 t
, err
:= loadTestFuncs(ptest
)
902 return nil, nil, nil, err
904 if len(ptest
.GoFiles
)+len(ptest
.CgoFiles
) > 0 {
905 pmain
.Internal
.Imports
= append(pmain
.Internal
.Imports
, ptest
)
909 pmain
.Internal
.Imports
= append(pmain
.Internal
.Imports
, pxtest
)
914 // We have made modifications to the package p being tested
915 // and are rebuilding p (as ptest).
916 // Arrange to rebuild all packages q such that
917 // the test depends on q and q depends on p.
918 // This makes sure that q sees the modifications to p.
919 // Strictly speaking, the rebuild is only necessary if the
920 // modifications to p change its export metadata, but
921 // determining that is a bit tricky, so we rebuild always.
922 recompileForTest(pmain
, p
, ptest
, pxtest
)
925 for _
, cp
:= range pmain
.Internal
.Imports
{
926 if len(cp
.Internal
.CoverVars
) > 0 {
927 t
.Cover
= append(t
.Cover
, coverInfo
{cp
, cp
.Internal
.CoverVars
})
932 // writeTestmain writes _testmain.go,
933 // using the test description gathered in t.
934 if err
:= writeTestmain(testDir
+"_testmain.go", t
); err
!= nil {
935 return nil, nil, nil, err
939 // Set compile objdir to testDir we've already created,
940 // so that the default file path stripping applies to _testmain.go.
941 b
.CompileAction(work
.ModeBuild
, work
.ModeBuild
, pmain
).Objdir
= testDir
943 a
:= b
.LinkAction(work
.ModeBuild
, work
.ModeBuild
, pmain
)
944 a
.Target
= testDir
+ testBinary
+ cfg
.ExeSuffix
945 if cfg
.Goos
== "windows" {
946 // There are many reserved words on Windows that,
947 // if used in the name of an executable, cause Windows
948 // to try to ask for extra permissions.
949 // The word list includes setup, install, update, and patch,
950 // but it does not appear to be defined anywhere.
951 // We have run into this trying to run the
952 // go.codereview/patch tests.
953 // For package names containing those words, use test.test.exe
954 // instead of pkgname.test.exe.
955 // Note that this file name is only used in the Go command's
956 // temporary directory. If the -c or other flags are
957 // given, the code below will still use pkgname.test.exe.
958 // There are two user-visible effects of this change.
959 // First, you can actually run 'go test' in directories that
960 // have names that Windows thinks are installer-like,
961 // without getting a dialog box asking for more permissions.
962 // Second, in the Windows process listing during go test,
963 // the test shows up as test.test.exe, not pkgname.test.exe.
964 // That second one is a drawback, but it seems a small
965 // price to pay for the test running at all.
966 // If maintaining the list of bad words is too onerous,
967 // we could just do this always on Windows.
968 for _
, bad
:= range windowsBadWords
{
969 if strings
.Contains(testBinary
, bad
) {
970 a
.Target
= testDir
+ "test.test" + cfg
.ExeSuffix
976 var installAction
, cleanAction
*work
.Action
977 if testC || testNeedBinary
{
978 // -c or profiling flag: create action to copy binary to ./test.out.
979 target
:= filepath
.Join(base
.Cwd
, testBinary
+cfg
.ExeSuffix
)
982 if !filepath
.IsAbs(target
) {
983 target
= filepath
.Join(base
.Cwd
, target
)
986 pmain
.Target
= target
987 installAction
= &work
.Action
{
989 Func
: work
.BuildInstallFunc
,
990 Deps
: []*work
.Action
{buildAction
},
994 runAction
= installAction
// make sure runAction != nil even if not running test
997 printAction
= &work
.Action
{Mode
: "test print (nop)", Package
: p
, Deps
: []*work
.Action
{runAction
}} // nop
1001 runAction
= &work
.Action
{
1003 Func
: c
.builderRunTest
,
1004 Deps
: []*work
.Action
{buildAction
},
1006 IgnoreFail
: true, // run (prepare output) even if build failed
1007 TryCache
: c
.tryCache
,
1010 if len(ptest
.GoFiles
)+len(ptest
.CgoFiles
) > 0 {
1011 addTestVet(b
, ptest
, runAction
, installAction
)
1014 addTestVet(b
, pxtest
, runAction
, installAction
)
1016 cleanAction
= &work
.Action
{
1018 Func
: builderCleanTest
,
1019 Deps
: []*work
.Action
{runAction
},
1021 IgnoreFail
: true, // clean even if test failed
1024 printAction
= &work
.Action
{
1026 Func
: builderPrintTest
,
1027 Deps
: []*work
.Action
{cleanAction
},
1029 IgnoreFail
: true, // print even if test failed
1032 if installAction
!= nil {
1033 if runAction
!= installAction
{
1034 installAction
.Deps
= append(installAction
.Deps
, runAction
)
1036 if cleanAction
!= nil {
1037 cleanAction
.Deps
= append(cleanAction
.Deps
, installAction
)
1041 return buildAction
, runAction
, printAction
, nil
1044 func addTestVet(b
*work
.Builder
, p
*load
.Package
, runAction
, installAction
*work
.Action
) {
1045 if testVetList
== "off" {
1049 vet
:= b
.VetAction(work
.ModeBuild
, work
.ModeBuild
, p
)
1050 runAction
.Deps
= append(runAction
.Deps
, vet
)
1051 // Install will clean the build directory.
1052 // Make sure vet runs first.
1053 // The install ordering in b.VetAction does not apply here
1054 // because we are using a custom installAction (created above).
1055 if installAction
!= nil {
1056 installAction
.Deps
= append(installAction
.Deps
, vet
)
1060 func recompileForTest(pmain
, preal
, ptest
, pxtest
*load
.Package
) {
1061 // The "test copy" of preal is ptest.
1062 // For each package that depends on preal, make a "test copy"
1063 // that depends on ptest. And so on, up the dependency tree.
1064 testCopy
:= map[*load
.Package
]*load
.Package
{preal
: ptest
}
1065 for _
, p
:= range load
.PackageList([]*load
.Package
{pmain
}) {
1070 didSplit
:= p
== pmain || p
== pxtest
1076 if testCopy
[p
] != nil {
1077 panic("recompileForTest loop")
1079 p1
:= new(load
.Package
)
1082 p1
.Internal
.Imports
= make([]*load
.Package
, len(p
.Internal
.Imports
))
1083 copy(p1
.Internal
.Imports
, p
.Internal
.Imports
)
1088 // Update p.Internal.Imports to use test copies.
1089 for i
, imp
:= range p
.Internal
.Imports
{
1090 if p1
:= testCopy
[imp
]; p1
!= nil && p1
!= imp
{
1092 p
.Internal
.Imports
[i
] = p1
1098 // isTestFile reports whether the source file is a set of tests and should therefore
1099 // be excluded from coverage analysis.
1100 func isTestFile(file
string) bool {
1101 // We don't cover tests, only the code they test.
1102 return strings
.HasSuffix(file
, "_test.go")
1105 // declareCoverVars attaches the required cover variables names
1106 // to the files, to be used when annotating the files.
1107 func declareCoverVars(importPath
string, files
...string) map[string]*load
.CoverVar
{
1108 coverVars
:= make(map[string]*load
.CoverVar
)
1110 // We create the cover counters as new top-level variables in the package.
1111 // We need to avoid collisions with user variables (GoCover_0 is unlikely but still)
1112 // and more importantly with dot imports of other covered packages,
1113 // so we append 12 hex digits from the SHA-256 of the import path.
1114 // The point is only to avoid accidents, not to defeat users determined to
1116 sum
:= sha256
.Sum256([]byte(importPath
))
1117 h
:= fmt
.Sprintf("%x", sum
[:6])
1118 for _
, file
:= range files
{
1119 if isTestFile(file
) {
1122 coverVars
[file
] = &load
.CoverVar
{
1123 File
: filepath
.Join(importPath
, file
),
1124 Var
: fmt
.Sprintf("GoCover_%d_%x", coverIndex
, h
),
1131 var noTestsToRun
= []byte("\ntesting: warning: no tests to run\n")
1133 type runCache
struct {
1134 disableCache
bool // cache should be disabled for this run
1141 // stdoutMu and lockedStdout provide a locked standard output
1142 // that guarantees never to interlace writes from multiple
1143 // goroutines, so that we can have multiple JSON streams writing
1144 // to a lockedStdout simultaneously and know that events will
1145 // still be intelligible.
1146 var stdoutMu sync
.Mutex
1148 type lockedStdout
struct{}
1150 func (lockedStdout
) Write(b
[]byte) (int, error
) {
1152 defer stdoutMu
.Unlock()
1153 return os
.Stdout
.Write(b
)
1156 // builderRunTest is the action for running a test binary.
1157 func (c
*runCache
) builderRunTest(b
*work
.Builder
, a
*work
.Action
) error
{
1159 // We were unable to build the binary.
1161 a
.TestOutput
= new(bytes
.Buffer
)
1162 fmt
.Fprintf(a
.TestOutput
, "FAIL\t%s [build failed]\n", a
.Package
.ImportPath
)
1163 base
.SetExitStatus(1)
1167 var stdout io
.Writer
= os
.Stdout
1169 json
:= test2json
.NewConverter(lockedStdout
{}, a
.Package
.ImportPath
, test2json
.Timestamp
)
1174 var buf bytes
.Buffer
1175 if len(pkgArgs
) == 0 || testBench
{
1176 // Stream test output (no buffering) when no package has
1177 // been given on the command line (implicit current directory)
1178 // or when benchmarking.
1179 // No change to stdout.
1181 // If we're only running a single package under test or if parallelism is
1182 // set to 1, and if we're displaying all output (testShowPass), we can
1183 // hurry the output along, echoing it as soon as it comes in.
1184 // We still have to copy to &buf for caching the result. This special
1185 // case was introduced in Go 1.5 and is intentionally undocumented:
1186 // the exact details of output buffering are up to the go command and
1187 // subject to change. It would be nice to remove this special case
1188 // entirely, but it is surely very helpful to see progress being made
1189 // when tests are run on slow single-CPU ARM systems.
1191 // If we're showing JSON output, then display output as soon as
1192 // possible even when multiple tests are being run: the JSON output
1193 // events are attributed to specific package tests, so interlacing them
1195 if testShowPass
&& (len(pkgs
) == 1 || cfg
.BuildP
== 1) || testJSON
{
1196 // Write both to stdout and buf, for possible saving
1197 // to cache, and for looking for the "no tests to run" message.
1198 stdout
= io
.MultiWriter(stdout
, &buf
)
1205 // We did not find a cached result using the link step action ID,
1206 // so we ran the link step. Try again now with the link output
1207 // content ID. The attempt using the action ID makes sure that
1208 // if the link inputs don't change, we reuse the cached test
1209 // result without even rerunning the linker. The attempt using
1210 // the link output (test binary) content ID makes sure that if
1211 // we have different link inputs but the same final binary,
1212 // we still reuse the cached test result.
1213 // c.saveOutput will store the result under both IDs.
1214 c
.tryCacheWithID(b
, a
, a
.Deps
[0].BuildContentID())
1218 stdout
.Write(c
.buf
.Bytes())
1221 a
.TestOutput
= c
.buf
1225 execCmd
:= work
.FindExecCmd()
1226 testlogArg
:= []string{}
1227 if !c
.disableCache
&& len(execCmd
) == 0 {
1228 testlogArg
= []string{"-test.testlogfile=" + a
.Objdir
+ "testlog.txt"}
1230 args
:= str
.StringList(execCmd
, a
.Deps
[0].BuiltTarget(), testlogArg
, testArgs
)
1232 if testCoverProfile
!= "" {
1233 // Write coverage to temporary profile, for merging later.
1234 for i
, arg
:= range args
{
1235 if strings
.HasPrefix(arg
, "-test.coverprofile=") {
1236 args
[i
] = "-test.coverprofile=" + a
.Objdir
+ "_cover_.out"
1241 if cfg
.BuildN || cfg
.BuildX
{
1242 b
.Showcmd("", "%s", strings
.Join(args
, " "))
1248 cmd
:= exec
.Command(args
[0], args
[1:]...)
1249 cmd
.Dir
= a
.Package
.Dir
1250 cmd
.Env
= base
.EnvForDir(cmd
.Dir
, cfg
.OrigEnv
)
1254 // If there are any local SWIG dependencies, we want to load
1255 // the shared library from the build directory.
1256 if a
.Package
.UsesSwig() {
1259 prefix
:= "LD_LIBRARY_PATH="
1260 for i
, v
:= range env
{
1261 if strings
.HasPrefix(v
, prefix
) {
1268 env
= append(env
, "LD_LIBRARY_PATH=.")
1276 // This is a last-ditch deadline to detect and
1277 // stop wedged test binaries, to keep the builders
1280 tick
:= time
.NewTimer(testKillTimeout
)
1281 base
.StartSigHandlers()
1282 done
:= make(chan error
)
1291 if base
.SignalTrace
!= nil {
1292 // Send a quit signal in the hope that the program will print
1293 // a stack trace and exit. Give it five seconds before resorting
1295 cmd
.Process
.Signal(base
.SignalTrace
)
1298 fmt
.Fprintf(cmd
.Stdout
, "*** Test killed with %v: ran too long (%v).\n", base
.SignalTrace
, testKillTimeout
)
1300 case <-time
.After(5 * time
.Second
):
1305 fmt
.Fprintf(cmd
.Stdout
, "*** Test killed: ran too long (%v).\n", testKillTimeout
)
1311 t
:= fmt
.Sprintf("%.3fs", time
.Since(t0
).Seconds())
1313 mergeCoverProfile(cmd
.Stdout
, a
.Objdir
+"_cover_.out")
1317 if !testShowPass
&& !testJSON
{
1320 if bytes
.HasPrefix(out
, noTestsToRun
[1:]) || bytes
.Contains(out
, noTestsToRun
) {
1321 norun
= " [no tests to run]"
1323 fmt
.Fprintf(cmd
.Stdout
, "ok \t%s\t%s%s%s\n", a
.Package
.ImportPath
, t
, coveragePercentage(out
), norun
)
1326 base
.SetExitStatus(1)
1327 // If there was test output, assume we don't need to print the exit status.
1328 // Buf there's no test output, do print the exit status.
1330 fmt
.Fprintf(cmd
.Stdout
, "%s\n", err
)
1332 fmt
.Fprintf(cmd
.Stdout
, "FAIL\t%s\t%s\n", a
.Package
.ImportPath
, t
)
1335 if cmd
.Stdout
!= &buf
{
1336 buf
.Reset() // cmd.Stdout was going to os.Stdout already
1341 // tryCache is called just before the link attempt,
1342 // to see if the test result is cached and therefore the link is unneeded.
1343 // It reports whether the result can be satisfied from cache.
1344 func (c
*runCache
) tryCache(b
*work
.Builder
, a
*work
.Action
) bool {
1345 return c
.tryCacheWithID(b
, a
, a
.Deps
[0].BuildActionID())
1348 func (c
*runCache
) tryCacheWithID(b
*work
.Builder
, a
*work
.Action
, id
string) bool {
1349 if len(pkgArgs
) == 0 {
1350 // Caching does not apply to "go test",
1351 // only to "go test foo" (including "go test .").
1352 if cache
.DebugTest
{
1353 fmt
.Fprintf(os
.Stderr
, "testcache: caching disabled in local directory mode\n")
1355 c
.disableCache
= true
1359 var cacheArgs
[]string
1360 for _
, arg
:= range testArgs
{
1361 i
:= strings
.Index(arg
, "=")
1362 if i
< 0 ||
!strings
.HasPrefix(arg
, "-test.") {
1363 if cache
.DebugTest
{
1364 fmt
.Fprintf(os
.Stderr
, "testcache: caching disabled for test argument: %s\n", arg
)
1366 c
.disableCache
= true
1376 // These are cacheable.
1377 // Note that this list is documented above,
1378 // so if you add to this list, update the docs too.
1379 cacheArgs
= append(cacheArgs
, arg
)
1381 case "-test.timeout":
1382 // Special case: this is cacheable but ignored during the hash.
1383 // Do not add to cacheArgs.
1386 // nothing else is cacheable
1387 if cache
.DebugTest
{
1388 fmt
.Fprintf(os
.Stderr
, "testcache: caching disabled for test argument: %s\n", arg
)
1390 c
.disableCache
= true
1395 if cache
.Default() == nil {
1396 if cache
.DebugTest
{
1397 fmt
.Fprintf(os
.Stderr
, "testcache: GOCACHE=off\n")
1399 c
.disableCache
= true
1403 // The test cache result fetch is a two-level lookup.
1405 // First, we use the content hash of the test binary
1406 // and its command-line arguments to find the
1407 // list of environment variables and files consulted
1408 // the last time the test was run with those arguments.
1409 // (To avoid unnecessary links, we store this entry
1410 // under two hashes: id1 uses the linker inputs as a
1411 // proxy for the test binary, and id2 uses the actual
1412 // test binary. If the linker inputs are unchanged,
1413 // this way we avoid the link step, even though we
1414 // do not cache link outputs.)
1416 // Second, we compute a hash of the values of the
1417 // environment variables and the content of the files
1418 // listed in the log from the previous run.
1419 // Then we look up test output using a combination of
1420 // the hash from the first part (testID) and the hash of the
1421 // test inputs (testInputsID).
1423 // In order to store a new test result, we must redo the
1424 // testInputsID computation using the log from the run
1425 // we want to cache, and then we store that new log and
1428 h
:= cache
.NewHash("testResult")
1429 fmt
.Fprintf(h
, "test binary %s args %q execcmd %q", id
, cacheArgs
, work
.ExecCmd
)
1431 if c
.id1
== (cache
.ActionID
{}) {
1436 if cache
.DebugTest
{
1437 fmt
.Fprintf(os
.Stderr
, "testcache: %s: test ID %x => %x\n", a
.Package
.ImportPath
, id
, testID
)
1440 // Load list of referenced environment variables and files
1441 // from last run of testID, and compute hash of that content.
1442 data
, entry
, err
:= cache
.Default().GetBytes(testID
)
1443 if !bytes
.HasPrefix(data
, testlogMagic
) || data
[len(data
)-1] != '\n' {
1444 if cache
.DebugTest
{
1446 fmt
.Fprintf(os
.Stderr
, "testcache: %s: input list not found: %v\n", a
.Package
.ImportPath
, err
)
1448 fmt
.Fprintf(os
.Stderr
, "testcache: %s: input list malformed\n", a
.Package
.ImportPath
)
1453 testInputsID
, err
:= computeTestInputsID(a
, data
)
1457 if cache
.DebugTest
{
1458 fmt
.Fprintf(os
.Stderr
, "testcache: %s: test ID %x => input ID %x => %x\n", a
.Package
.ImportPath
, testID
, testInputsID
, testAndInputKey(testID
, testInputsID
))
1461 // Parse cached result in preparation for changing run time to "(cached)".
1462 // If we can't parse the cached result, don't use it.
1463 data
, entry
, err
= cache
.Default().GetBytes(testAndInputKey(testID
, testInputsID
))
1464 if len(data
) == 0 || data
[len(data
)-1] != '\n' {
1465 if cache
.DebugTest
{
1467 fmt
.Fprintf(os
.Stderr
, "testcache: %s: test output not found: %v\n", a
.Package
.ImportPath
, err
)
1469 fmt
.Fprintf(os
.Stderr
, "testcache: %s: test output malformed\n", a
.Package
.ImportPath
)
1474 if entry
.Time
.Before(testCacheExpire
) {
1475 if cache
.DebugTest
{
1476 fmt
.Fprintf(os
.Stderr
, "testcache: %s: test output expired due to go clean -testcache\n", a
.Package
.ImportPath
)
1480 i
:= bytes
.LastIndexByte(data
[:len(data
)-1], '\n') + 1
1481 if !bytes
.HasPrefix(data
[i
:], []byte("ok \t")) {
1482 if cache
.DebugTest
{
1483 fmt
.Fprintf(os
.Stderr
, "testcache: %s: test output malformed\n", a
.Package
.ImportPath
)
1487 j
:= bytes
.IndexByte(data
[i
+len("ok \t"):], '\t')
1489 if cache
.DebugTest
{
1490 fmt
.Fprintf(os
.Stderr
, "testcache: %s: test output malformed\n", a
.Package
.ImportPath
)
1494 j
+= i
+ len("ok \t") + 1
1496 // Committed to printing.
1497 c
.buf
= new(bytes
.Buffer
)
1498 c
.buf
.Write(data
[:j
])
1499 c
.buf
.WriteString("(cached)")
1500 for j
< len(data
) && ('0' <= data
[j
] && data
[j
] <= '9' || data
[j
] == '.' || data
[j
] == 's') {
1503 c
.buf
.Write(data
[j
:])
1507 var errBadTestInputs
= errors
.New("error parsing test inputs")
1508 var testlogMagic
= []byte("# test log\n") // known to testing/internal/testdeps/deps.go
1510 // computeTestInputsID computes the "test inputs ID"
1511 // (see comment in tryCacheWithID above) for the
1513 func computeTestInputsID(a
*work
.Action
, testlog
[]byte) (cache
.ActionID
, error
) {
1514 testlog
= bytes
.TrimPrefix(testlog
, testlogMagic
)
1515 h
:= cache
.NewHash("testInputs")
1516 pwd
:= a
.Package
.Dir
1517 for _
, line
:= range bytes
.Split(testlog
, []byte("\n")) {
1522 i
:= strings
.Index(s
, " ")
1524 if cache
.DebugTest
{
1525 fmt
.Fprintf(os
.Stderr
, "testcache: %s: input list malformed (%q)\n", a
.Package
.ImportPath
, line
)
1527 return cache
.ActionID
{}, errBadTestInputs
1533 if cache
.DebugTest
{
1534 fmt
.Fprintf(os
.Stderr
, "testcache: %s: input list malformed (%q)\n", a
.Package
.ImportPath
, line
)
1536 return cache
.ActionID
{}, errBadTestInputs
1538 fmt
.Fprintf(h
, "env %s %x\n", name
, hashGetenv(name
))
1540 pwd
= name
// always absolute
1541 fmt
.Fprintf(h
, "cbdir %s %x\n", name
, hashStat(name
))
1543 if !filepath
.IsAbs(name
) {
1544 name
= filepath
.Join(pwd
, name
)
1546 if !inDir(name
, a
.Package
.Root
) {
1547 // Do not recheck files outside the GOPATH or GOROOT root.
1550 fmt
.Fprintf(h
, "stat %s %x\n", name
, hashStat(name
))
1552 if !filepath
.IsAbs(name
) {
1553 name
= filepath
.Join(pwd
, name
)
1555 if !inDir(name
, a
.Package
.Root
) {
1556 // Do not recheck files outside the GOPATH or GOROOT root.
1559 fh
, err
:= hashOpen(name
)
1561 if cache
.DebugTest
{
1562 fmt
.Fprintf(os
.Stderr
, "testcache: %s: input file %s: %s\n", a
.Package
.ImportPath
, name
, err
)
1564 return cache
.ActionID
{}, err
1566 fmt
.Fprintf(h
, "open %s %x\n", name
, fh
)
1573 func inDir(path
, dir
string) bool {
1574 if str
.HasFilePathPrefix(path
, dir
) {
1577 xpath
, err1
:= filepath
.EvalSymlinks(path
)
1578 xdir
, err2
:= filepath
.EvalSymlinks(dir
)
1579 if err1
== nil && err2
== nil && str
.HasFilePathPrefix(xpath
, xdir
) {
1585 func hashGetenv(name
string) cache
.ActionID
{
1586 h
:= cache
.NewHash("getenv")
1587 v
, ok
:= os
.LookupEnv(name
)
1597 const modTimeCutoff
= 2 * time
.Second
1599 var errFileTooNew
= errors
.New("file used as input is too new")
1601 func hashOpen(name
string) (cache
.ActionID
, error
) {
1602 h
:= cache
.NewHash("open")
1603 info
, err
:= os
.Stat(name
)
1605 fmt
.Fprintf(h
, "err %v\n", err
)
1608 hashWriteStat(h
, info
)
1610 names
, err
:= ioutil
.ReadDir(name
)
1612 fmt
.Fprintf(h
, "err %v\n", err
)
1614 for _
, f
:= range names
{
1615 fmt
.Fprintf(h
, "file %s ", f
.Name())
1618 } else if info
.Mode().IsRegular() {
1619 // Because files might be very large, do not attempt
1620 // to hash the entirety of their content. Instead assume
1621 // the mtime and size recorded in hashWriteStat above
1624 // To avoid problems for very recent files where a new
1625 // write might not change the mtime due to file system
1626 // mtime precision, reject caching if a file was read that
1627 // is less than modTimeCutoff old.
1628 if time
.Since(info
.ModTime()) < modTimeCutoff
{
1629 return cache
.ActionID
{}, errFileTooNew
1635 func hashStat(name
string) cache
.ActionID
{
1636 h
:= cache
.NewHash("stat")
1637 if info
, err
:= os
.Stat(name
); err
!= nil {
1638 fmt
.Fprintf(h
, "err %v\n", err
)
1640 hashWriteStat(h
, info
)
1642 if info
, err
:= os
.Lstat(name
); err
!= nil {
1643 fmt
.Fprintf(h
, "err %v\n", err
)
1645 hashWriteStat(h
, info
)
1650 func hashWriteStat(h io
.Writer
, info os
.FileInfo
) {
1651 fmt
.Fprintf(h
, "stat %d %x %v %v\n", info
.Size(), uint64(info
.Mode()), info
.ModTime(), info
.IsDir())
1654 // testAndInputKey returns the actual cache key for the pair (testID, testInputsID).
1655 func testAndInputKey(testID
, testInputsID cache
.ActionID
) cache
.ActionID
{
1656 return cache
.Subkey(testID
, fmt
.Sprintf("inputs:%x", testInputsID
))
1659 func (c
*runCache
) saveOutput(a
*work
.Action
) {
1660 if c
.id1
== (cache
.ActionID
{}) && c
.id2
== (cache
.ActionID
{}) {
1664 // See comment about two-level lookup in tryCacheWithID above.
1665 testlog
, err
:= ioutil
.ReadFile(a
.Objdir
+ "testlog.txt")
1666 if err
!= nil ||
!bytes
.HasPrefix(testlog
, testlogMagic
) || testlog
[len(testlog
)-1] != '\n' {
1667 if cache
.DebugTest
{
1669 fmt
.Fprintf(os
.Stderr
, "testcache: %s: reading testlog: %v\n", a
.Package
.ImportPath
, err
)
1671 fmt
.Fprintf(os
.Stderr
, "testcache: %s: reading testlog: malformed\n", a
.Package
.ImportPath
)
1676 testInputsID
, err
:= computeTestInputsID(a
, testlog
)
1680 if c
.id1
!= (cache
.ActionID
{}) {
1681 if cache
.DebugTest
{
1682 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
))
1684 cache
.Default().PutNoVerify(c
.id1
, bytes
.NewReader(testlog
))
1685 cache
.Default().PutNoVerify(testAndInputKey(c
.id1
, testInputsID
), bytes
.NewReader(a
.TestOutput
.Bytes()))
1687 if c
.id2
!= (cache
.ActionID
{}) {
1688 if cache
.DebugTest
{
1689 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
))
1691 cache
.Default().PutNoVerify(c
.id2
, bytes
.NewReader(testlog
))
1692 cache
.Default().PutNoVerify(testAndInputKey(c
.id2
, testInputsID
), bytes
.NewReader(a
.TestOutput
.Bytes()))
1696 // coveragePercentage returns the coverage results (if enabled) for the
1697 // test. It uncovers the data by scanning the output from the test run.
1698 func coveragePercentage(out
[]byte) string {
1702 // The string looks like
1703 // test coverage for encoding/binary: 79.9% of statements
1704 // Extract the piece from the percentage to the end of the line.
1705 re
:= regexp
.MustCompile(`coverage: (.*)\n`)
1706 matches
:= re
.FindSubmatch(out
)
1708 // Probably running "go test -cover" not "go test -cover fmt".
1709 // The coverage output will appear in the output directly.
1712 return fmt
.Sprintf("\tcoverage: %s", matches
[1])
1715 // builderCleanTest is the action for cleaning up after a test.
1716 func builderCleanTest(b
*work
.Builder
, a
*work
.Action
) error
{
1721 b
.Showcmd("", "rm -r %s", a
.Objdir
)
1723 os
.RemoveAll(a
.Objdir
)
1727 // builderPrintTest is the action for printing a test result.
1728 func builderPrintTest(b
*work
.Builder
, a
*work
.Action
) error
{
1730 run
:= clean
.Deps
[0]
1731 if run
.TestOutput
!= nil {
1732 os
.Stdout
.Write(run
.TestOutput
.Bytes())
1733 run
.TestOutput
= nil
1738 // builderNoTest is the action for testing a package with no test files.
1739 func builderNoTest(b
*work
.Builder
, a
*work
.Action
) error
{
1740 var stdout io
.Writer
= os
.Stdout
1742 json
:= test2json
.NewConverter(lockedStdout
{}, a
.Package
.ImportPath
, test2json
.Timestamp
)
1746 fmt
.Fprintf(stdout
, "? \t%s\t[no test files]\n", a
.Package
.ImportPath
)
1750 // isTestFunc tells whether fn has the type of a testing function. arg
1751 // specifies the parameter type we look for: B, M or T.
1752 func isTestFunc(fn
*ast
.FuncDecl
, arg
string) bool {
1753 if fn
.Type
.Results
!= nil && len(fn
.Type
.Results
.List
) > 0 ||
1754 fn
.Type
.Params
.List
== nil ||
1755 len(fn
.Type
.Params
.List
) != 1 ||
1756 len(fn
.Type
.Params
.List
[0].Names
) > 1 {
1759 ptr
, ok
:= fn
.Type
.Params
.List
[0].Type
.(*ast
.StarExpr
)
1763 // We can't easily check that the type is *testing.M
1764 // because we don't know how testing has been imported,
1765 // but at least check that it's *M or *something.M.
1766 // Same applies for B and T.
1767 if name
, ok
:= ptr
.X
.(*ast
.Ident
); ok
&& name
.Name
== arg
{
1770 if sel
, ok
:= ptr
.X
.(*ast
.SelectorExpr
); ok
&& sel
.Sel
.Name
== arg
{
1776 // isTest tells whether name looks like a test (or benchmark, according to prefix).
1777 // It is a Test (say) if there is a character after Test that is not a lower-case letter.
1778 // We don't want TesticularCancer.
1779 func isTest(name
, prefix
string) bool {
1780 if !strings
.HasPrefix(name
, prefix
) {
1783 if len(name
) == len(prefix
) { // "Test" is ok
1786 rune
, _
:= utf8
.DecodeRuneInString(name
[len(prefix
):])
1787 return !unicode
.IsLower(rune
)
1790 type coverInfo
struct {
1791 Package
*load
.Package
1792 Vars
map[string]*load
.CoverVar
1795 // loadTestFuncs returns the testFuncs describing the tests that will be run.
1796 func loadTestFuncs(ptest
*load
.Package
) (*testFuncs
, error
) {
1800 for _
, file
:= range ptest
.TestGoFiles
{
1801 if err
:= t
.load(filepath
.Join(ptest
.Dir
, file
), "_test", &t
.ImportTest
, &t
.NeedTest
); err
!= nil {
1805 for _
, file
:= range ptest
.XTestGoFiles
{
1806 if err
:= t
.load(filepath
.Join(ptest
.Dir
, file
), "_xtest", &t
.ImportXtest
, &t
.NeedXtest
); err
!= nil {
1813 // writeTestmain writes the _testmain.go file for t to the file named out.
1814 func writeTestmain(out
string, t
*testFuncs
) error
{
1815 f
, err
:= os
.Create(out
)
1821 if err
:= testmainTmpl
.Execute(f
, t
); err
!= nil {
1828 type testFuncs
struct {
1830 Benchmarks
[]testFunc
1833 Package
*load
.Package
1841 func (t
*testFuncs
) CoverMode() string {
1842 return testCoverMode
1845 func (t
*testFuncs
) CoverEnabled() bool {
1849 // ImportPath returns the import path of the package being tested, if it is within GOPATH.
1850 // This is printed by the testing package when running benchmarks.
1851 func (t
*testFuncs
) ImportPath() string {
1852 pkg
:= t
.Package
.ImportPath
1853 if strings
.HasPrefix(pkg
, "_/") {
1856 if pkg
== "command-line-arguments" {
1862 // Covered returns a string describing which packages are being tested for coverage.
1863 // If the covered package is the same as the tested package, it returns the empty string.
1864 // Otherwise it is a comma-separated human-readable list of packages beginning with
1865 // " in", ready for use in the coverage message.
1866 func (t
*testFuncs
) Covered() string {
1867 if testCoverPaths
== nil {
1870 return " in " + strings
.Join(testCoverPaths
, ", ")
1873 // Tested returns the name of the package being tested.
1874 func (t
*testFuncs
) Tested() string {
1875 return t
.Package
.Name
1878 type testFunc
struct {
1879 Package
string // imported package name (_test or _xtest)
1880 Name
string // function name
1881 Output
string // output, for examples
1882 Unordered
bool // output is allowed to be unordered.
1885 var testFileSet
= token
.NewFileSet()
1887 func (t
*testFuncs
) load(filename
, pkg
string, doImport
, seen
*bool) error
{
1888 f
, err
:= parser
.ParseFile(testFileSet
, filename
, nil, parser
.ParseComments
)
1890 return base
.ExpandScanner(err
)
1892 for _
, d
:= range f
.Decls
{
1893 n
, ok
:= d
.(*ast
.FuncDecl
)
1900 name
:= n
.Name
.String()
1902 case name
== "TestMain":
1903 if isTestFunc(n
, "T") {
1904 t
.Tests
= append(t
.Tests
, testFunc
{pkg
, name
, "", false})
1905 *doImport
, *seen
= true, true
1908 err
:= checkTestFunc(n
, "M")
1912 if t
.TestMain
!= nil {
1913 return errors
.New("multiple definitions of TestMain")
1915 t
.TestMain
= &testFunc
{pkg
, name
, "", false}
1916 *doImport
, *seen
= true, true
1917 case isTest(name
, "Test"):
1918 err
:= checkTestFunc(n
, "T")
1922 t
.Tests
= append(t
.Tests
, testFunc
{pkg
, name
, "", false})
1923 *doImport
, *seen
= true, true
1924 case isTest(name
, "Benchmark"):
1925 err
:= checkTestFunc(n
, "B")
1929 t
.Benchmarks
= append(t
.Benchmarks
, testFunc
{pkg
, name
, "", false})
1930 *doImport
, *seen
= true, true
1933 ex
:= doc
.Examples(f
)
1934 sort
.Slice(ex
, func(i
, j
int) bool { return ex
[i
].Order
< ex
[j
].Order
})
1935 for _
, e
:= range ex
{
1936 *doImport
= true // import test file whether executed or not
1937 if e
.Output
== "" && !e
.EmptyOutput
{
1938 // Don't run examples with no output.
1941 t
.Examples
= append(t
.Examples
, testFunc
{pkg
, "Example" + e
.Name
, e
.Output
, e
.Unordered
})
1947 func checkTestFunc(fn
*ast
.FuncDecl
, arg
string) error
{
1948 if !isTestFunc(fn
, arg
) {
1949 name
:= fn
.Name
.String()
1950 pos
:= testFileSet
.Position(fn
.Pos())
1951 return fmt
.Errorf("%s: wrong signature for %s, must be: func %s(%s *testing.%s)", pos
, name
, name
, strings
.ToLower(arg
), arg
)
1956 var testmainTmpl
= template
.Must(template
.New("main").Parse(`
1960 {{if not .TestMain}}
1964 "testing/internal/testdeps"
1967 {{if .NeedTest}}_test{{else}}_{{end}} {{.Package.ImportPath | printf "%q"}}
1970 {{if .NeedXtest}}_xtest{{else}}_{{end}} {{.Package.ImportPath | printf "%s_test" | printf "%q"}}
1972 {{range $i, $p := .Cover}}
1973 _cover{{$i}} {{$p.Package.ImportPath | printf "%q"}}
1977 var tests = []testing.InternalTest{
1979 {"{{.Name}}", {{.Package}}.{{.Name}}},
1983 var benchmarks = []testing.InternalBenchmark{
1984 {{range .Benchmarks}}
1985 {"{{.Name}}", {{.Package}}.{{.Name}}},
1989 var examples = []testing.InternalExample{
1991 {"{{.Name}}", {{.Package}}.{{.Name}}, {{.Output | printf "%q"}}, {{.Unordered}}},
1996 testdeps.ImportPath = {{.ImportPath | printf "%q"}}
1999 {{if .CoverEnabled}}
2001 // Only updated by init functions, so no need for atomicity.
2003 coverCounters = make(map[string][]uint32)
2004 coverBlocks = make(map[string][]testing.CoverBlock)
2008 {{range $i, $p := .Cover}}
2009 {{range $file, $cover := $p.Vars}}
2010 coverRegisterFile({{printf "%q" $cover.File}}, _cover{{$i}}.{{$cover.Var}}.Count[:], _cover{{$i}}.{{$cover.Var}}.Pos[:], _cover{{$i}}.{{$cover.Var}}.NumStmt[:])
2015 func coverRegisterFile(fileName string, counter []uint32, pos []uint32, numStmts []uint16) {
2016 if 3*len(counter) != len(pos) || len(counter) != len(numStmts) {
2017 panic("coverage: mismatched sizes")
2019 if coverCounters[fileName] != nil {
2020 // Already registered.
2023 coverCounters[fileName] = counter
2024 block := make([]testing.CoverBlock, len(counter))
2025 for i := range counter {
2026 block[i] = testing.CoverBlock{
2028 Col0: uint16(pos[3*i+2]),
2030 Col1: uint16(pos[3*i+2]>>16),
2034 coverBlocks[fileName] = block
2039 {{if .CoverEnabled}}
2040 testing.RegisterCover(testing.Cover{
2041 Mode: {{printf "%q" .CoverMode}},
2042 Counters: coverCounters,
2043 Blocks: coverBlocks,
2044 CoveredPackages: {{printf "%q" .Covered}},
2047 m := testing.MainStart(testdeps.TestDeps{}, tests, benchmarks, examples)
2049 {{.Package}}.{{.Name}}(m)