libgo: update to go1.9
[official-gcc.git] / libgo / go / cmd / go / internal / test / test.go
blobc1e66f9e88963bfb6901f1cbecf1a44fc3d2f530
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.
5 package test
7 import (
8 "bytes"
9 "errors"
10 "fmt"
11 "go/ast"
12 "go/build"
13 "go/doc"
14 "go/parser"
15 "go/token"
16 "os"
17 "os/exec"
18 "path"
19 "path/filepath"
20 "regexp"
21 "runtime"
22 "sort"
23 "strings"
24 "text/template"
25 "time"
26 "unicode"
27 "unicode/utf8"
29 "cmd/go/internal/base"
30 "cmd/go/internal/cfg"
31 "cmd/go/internal/load"
32 "cmd/go/internal/str"
33 "cmd/go/internal/work"
36 // Break init loop.
37 func init() {
38 CmdTest.Run = runTest
41 const testUsage = "test [build/test flags] [packages] [build/test flags & test binary flags]"
43 var CmdTest = &base.Command{
44 CustomFlags: true,
45 UsageLine: testUsage,
46 Short: "test packages",
47 Long: `
48 'Go test' automates testing the packages named by the import paths.
49 It prints a summary of the test results in the format:
51 ok archive/tar 0.011s
52 FAIL archive/zip 0.022s
53 ok compress/gzip 0.033s
54 ...
56 followed by detailed output for each failed package.
58 'Go test' recompiles each package along with any files with names matching
59 the file pattern "*_test.go".
60 Files whose names begin with "_" (including "_test.go") or "." are ignored.
61 These additional files can contain test functions, benchmark functions, and
62 example functions. See 'go help testfunc' for more.
63 Each listed package causes the execution of a separate test binary.
65 Test files that declare a package with the suffix "_test" will be compiled as a
66 separate package, and then linked and run with the main test binary.
68 The go tool will ignore a directory named "testdata", making it available
69 to hold ancillary data needed by the tests.
71 By default, go test needs no arguments. It compiles and tests the package
72 with source in the current directory, including tests, and runs the tests.
74 The package is built in a temporary directory so it does not interfere with the
75 non-test installation.
77 ` + strings.TrimSpace(testFlag1) + ` See 'go help testflag' for details.
79 For more about build flags, see 'go help build'.
80 For more about specifying packages, see 'go help packages'.
82 See also: go build, go vet.
86 const testFlag1 = `
87 In addition to the build flags, the flags handled by 'go test' itself are:
89 -args
90 Pass the remainder of the command line (everything after -args)
91 to the test binary, uninterpreted and unchanged.
92 Because this flag consumes the remainder of the command line,
93 the package list (if present) must appear before this flag.
96 Compile the test binary to pkg.test but do not run it
97 (where pkg is the last element of the package's import path).
98 The file name can be changed with the -o flag.
100 -exec xprog
101 Run the test binary using xprog. The behavior is the same as
102 in 'go run'. See 'go help run' for details.
105 Install packages that are dependencies of the test.
106 Do not run the test.
108 -o file
109 Compile the test binary to the named file.
110 The test still runs (unless -c or -i is specified).
112 The test binary also accepts flags that control execution of the test; these
113 flags are also accessible by 'go test'.
116 // Usage prints the usage message for 'go test -h' and exits.
117 func Usage() {
118 os.Stderr.WriteString(testUsage + "\n\n" +
119 strings.TrimSpace(testFlag1) + "\n\n\t" +
120 strings.TrimSpace(testFlag2) + "\n")
121 os.Exit(2)
124 var HelpTestflag = &base.Command{
125 UsageLine: "testflag",
126 Short: "description of testing flags",
127 Long: `
128 The 'go test' command takes both flags that apply to 'go test' itself
129 and flags that apply to the resulting test binary.
131 Several of the flags control profiling and write an execution profile
132 suitable for "go tool pprof"; run "go tool pprof -h" for more
133 information. The --alloc_space, --alloc_objects, and --show_bytes
134 options of pprof control how the information is presented.
136 The following flags are recognized by the 'go test' command and
137 control the execution of any test:
139 ` + strings.TrimSpace(testFlag2) + `
143 const testFlag2 = `
144 -bench regexp
145 Run only those benchmarks matching a regular expression.
146 By default, no benchmarks are run.
147 To run all benchmarks, use '-bench .' or '-bench=.'.
148 The regular expression is split by unbracketed slash (/)
149 characters into a sequence of regular expressions, and each
150 part of a benchmark's identifier must match the corresponding
151 element in the sequence, if any. Possible parents of matches
152 are run with b.N=1 to identify sub-benchmarks. For example,
153 given -bench=X/Y, top-level benchmarks matching X are run
154 with b.N=1 to find any sub-benchmarks matching Y, which are
155 then run in full.
157 -benchtime t
158 Run enough iterations of each benchmark to take t, specified
159 as a time.Duration (for example, -benchtime 1h30s).
160 The default is 1 second (1s).
162 -count n
163 Run each test and benchmark n times (default 1).
164 If -cpu is set, run n times for each GOMAXPROCS value.
165 Examples are always run once.
167 -cover
168 Enable coverage analysis.
169 Note that because coverage works by annotating the source
170 code before compilation, compilation and test failures with
171 coverage enabled may report line numbers that don't correspond
172 to the original sources.
174 -covermode set,count,atomic
175 Set the mode for coverage analysis for the package[s]
176 being tested. The default is "set" unless -race is enabled,
177 in which case it is "atomic".
178 The values:
179 set: bool: does this statement run?
180 count: int: how many times does this statement run?
181 atomic: int: count, but correct in multithreaded tests;
182 significantly more expensive.
183 Sets -cover.
185 -coverpkg pkg1,pkg2,pkg3
186 Apply coverage analysis in each test to the given list of packages.
187 The default is for each test to analyze only the package being tested.
188 Packages are specified as import paths.
189 Sets -cover.
191 -cpu 1,2,4
192 Specify a list of GOMAXPROCS values for which the tests or
193 benchmarks should be executed. The default is the current value
194 of GOMAXPROCS.
196 -list regexp
197 List tests, benchmarks, or examples matching the regular expression.
198 No tests, benchmarks or examples will be run. This will only
199 list top-level tests. No subtest or subbenchmarks will be shown.
201 -parallel n
202 Allow parallel execution of test functions that call t.Parallel.
203 The value of this flag is the maximum number of tests to run
204 simultaneously; by default, it is set to the value of GOMAXPROCS.
205 Note that -parallel only applies within a single test binary.
206 The 'go test' command may run tests for different packages
207 in parallel as well, according to the setting of the -p flag
208 (see 'go help build').
210 -run regexp
211 Run only those tests and examples matching the regular expression.
212 For tests, the regular expression is split by unbracketed slash (/)
213 characters into a sequence of regular expressions, and each part
214 of a test's identifier must match the corresponding element in
215 the sequence, if any. Note that possible parents of matches are
216 run too, so that -run=X/Y matches and runs and reports the result
217 of all tests matching X, even those without sub-tests matching Y,
218 because it must run them to look for those sub-tests.
220 -short
221 Tell long-running tests to shorten their run time.
222 It is off by default but set during all.bash so that installing
223 the Go tree can run a sanity check but not spend time running
224 exhaustive tests.
226 -timeout d
227 If a test binary runs longer than duration d, panic.
228 The default is 10 minutes (10m).
231 Verbose output: log all tests as they are run. Also print all
232 text from Log and Logf calls even if the test succeeds.
234 The following flags are also recognized by 'go test' and can be used to
235 profile the tests during execution:
237 -benchmem
238 Print memory allocation statistics for benchmarks.
240 -blockprofile block.out
241 Write a goroutine blocking profile to the specified file
242 when all tests are complete.
243 Writes test binary as -c would.
245 -blockprofilerate n
246 Control the detail provided in goroutine blocking profiles by
247 calling runtime.SetBlockProfileRate with n.
248 See 'go doc runtime.SetBlockProfileRate'.
249 The profiler aims to sample, on average, one blocking event every
250 n nanoseconds the program spends blocked. By default,
251 if -test.blockprofile is set without this flag, all blocking events
252 are recorded, equivalent to -test.blockprofilerate=1.
254 -coverprofile cover.out
255 Write a coverage profile to the file after all tests have passed.
256 Sets -cover.
258 -cpuprofile cpu.out
259 Write a CPU profile to the specified file before exiting.
260 Writes test binary as -c would.
262 -memprofile mem.out
263 Write a memory profile to the file after all tests have passed.
264 Writes test binary as -c would.
266 -memprofilerate n
267 Enable more precise (and expensive) memory profiles by setting
268 runtime.MemProfileRate. See 'go doc runtime.MemProfileRate'.
269 To profile all memory allocations, use -test.memprofilerate=1
270 and pass --alloc_space flag to the pprof tool.
272 -mutexprofile mutex.out
273 Write a mutex contention profile to the specified file
274 when all tests are complete.
275 Writes test binary as -c would.
277 -mutexprofilefraction n
278 Sample 1 in n stack traces of goroutines holding a
279 contended mutex.
281 -outputdir directory
282 Place output files from profiling in the specified directory,
283 by default the directory in which "go test" is running.
285 -trace trace.out
286 Write an execution trace to the specified file before exiting.
288 Each of these flags is also recognized with an optional 'test.' prefix,
289 as in -test.v. When invoking the generated test binary (the result of
290 'go test -c') directly, however, the prefix is mandatory.
292 The 'go test' command rewrites or removes recognized flags,
293 as appropriate, both before and after the optional package list,
294 before invoking the test binary.
296 For instance, the command
298 go test -v -myflag testdata -cpuprofile=prof.out -x
300 will compile the test binary and then run it as
302 pkg.test -test.v -myflag testdata -test.cpuprofile=prof.out
304 (The -x flag is removed because it applies only to the go command's
305 execution, not to the test itself.)
307 The test flags that generate profiles (other than for coverage) also
308 leave the test binary in pkg.test for use when analyzing the profiles.
310 When 'go test' runs a test binary, it does so from within the
311 corresponding package's source code directory. Depending on the test,
312 it may be necessary to do the same when invoking a generated test
313 binary directly.
315 The command-line package list, if present, must appear before any
316 flag not known to the go test command. Continuing the example above,
317 the package list would have to appear before -myflag, but could appear
318 on either side of -v.
320 To keep an argument for a test binary from being interpreted as a
321 known flag or a package name, use -args (see 'go help test') which
322 passes the remainder of the command line through to the test binary
323 uninterpreted and unaltered.
325 For instance, the command
327 go test -v -args -x -v
329 will compile the test binary and then run it as
331 pkg.test -test.v -x -v
333 Similarly,
335 go test -args math
337 will compile the test binary and then run it as
339 pkg.test math
341 In the first example, the -x and the second -v are passed through to the
342 test binary unchanged and with no effect on the go command itself.
343 In the second example, the argument math is passed through to the test
344 binary, instead of being interpreted as the package list.
347 var HelpTestfunc = &base.Command{
348 UsageLine: "testfunc",
349 Short: "description of testing functions",
350 Long: `
351 The 'go test' command expects to find test, benchmark, and example functions
352 in the "*_test.go" files corresponding to the package under test.
354 A test function is one named TestXXX (where XXX is any alphanumeric string
355 not starting with a lower case letter) and should have the signature,
357 func TestXXX(t *testing.T) { ... }
359 A benchmark function is one named BenchmarkXXX and should have the signature,
361 func BenchmarkXXX(b *testing.B) { ... }
363 An example function is similar to a test function but, instead of using
364 *testing.T to report success or failure, prints output to os.Stdout.
365 If the last comment in the function starts with "Output:" then the output
366 is compared exactly against the comment (see examples below). If the last
367 comment begins with "Unordered output:" then the output is compared to the
368 comment, however the order of the lines is ignored. An example with no such
369 comment is compiled but not executed. An example with no text after
370 "Output:" is compiled, executed, and expected to produce no output.
372 Godoc displays the body of ExampleXXX to demonstrate the use
373 of the function, constant, or variable XXX. An example of a method M with
374 receiver type T or *T is named ExampleT_M. There may be multiple examples
375 for a given function, constant, or variable, distinguished by a trailing _xxx,
376 where xxx is a suffix not beginning with an upper case letter.
378 Here is an example of an example:
380 func ExamplePrintln() {
381 Println("The output of\nthis example.")
382 // Output: The output of
383 // this example.
386 Here is another example where the ordering of the output is ignored:
388 func ExamplePerm() {
389 for _, value := range Perm(4) {
390 fmt.Println(value)
393 // Unordered output: 4
394 // 2
395 // 1
396 // 3
397 // 0
400 The entire test file is presented as the example when it contains a single
401 example function, at least one other function, type, variable, or constant
402 declaration, and no test or benchmark functions.
404 See the documentation of the testing package for more information.
408 var (
409 testC bool // -c flag
410 testCover bool // -cover flag
411 testCoverMode string // -covermode flag
412 testCoverPaths []string // -coverpkg flag
413 testCoverPkgs []*load.Package // -coverpkg flag
414 testO string // -o flag
415 testProfile bool // some profiling flag
416 testNeedBinary bool // profile needs to keep binary around
417 testV bool // -v flag
418 testTimeout string // -timeout flag
419 testArgs []string
420 testBench bool
421 testList bool
422 testStreamOutput bool // show output as it is generated
423 testShowPass bool // show passing output
425 testKillTimeout = 10 * time.Minute
428 var testMainDeps = map[string]bool{
429 // Dependencies for testmain.
430 "testing": true,
431 "testing/internal/testdeps": true,
432 "os": true,
435 func runTest(cmd *base.Command, args []string) {
436 var pkgArgs []string
437 pkgArgs, testArgs = testFlags(args)
439 work.FindExecCmd() // initialize cached result
441 work.InstrumentInit()
442 work.BuildModeInit()
443 pkgs := load.PackagesForBuild(pkgArgs)
444 if len(pkgs) == 0 {
445 base.Fatalf("no packages to test")
448 if testC && len(pkgs) != 1 {
449 base.Fatalf("cannot use -c flag with multiple packages")
451 if testO != "" && len(pkgs) != 1 {
452 base.Fatalf("cannot use -o flag with multiple packages")
454 if testProfile && len(pkgs) != 1 {
455 base.Fatalf("cannot use test profile flag with multiple packages")
458 // If a test timeout was given and is parseable, set our kill timeout
459 // to that timeout plus one minute. This is a backup alarm in case
460 // the test wedges with a goroutine spinning and its background
461 // timer does not get a chance to fire.
462 if dt, err := time.ParseDuration(testTimeout); err == nil && dt > 0 {
463 testKillTimeout = dt + 1*time.Minute
466 // show passing test output (after buffering) with -v flag.
467 // must buffer because tests are running in parallel, and
468 // otherwise the output will get mixed.
469 testShowPass = testV || testList
471 // stream test output (no buffering) when no package has
472 // been given on the command line (implicit current directory)
473 // or when benchmarking.
474 // Also stream if we're showing output anyway with a
475 // single package under test or if parallelism is set to 1.
476 // In these cases, streaming the output produces the same result
477 // as not streaming, just more immediately.
478 testStreamOutput = len(pkgArgs) == 0 || testBench ||
479 (testShowPass && (len(pkgs) == 1 || cfg.BuildP == 1))
481 // For 'go test -i -o x.test', we want to build x.test. Imply -c to make the logic easier.
482 if cfg.BuildI && testO != "" {
483 testC = true
486 var b work.Builder
487 b.Init()
489 if cfg.BuildI {
490 cfg.BuildV = testV
492 deps := make(map[string]bool)
493 for dep := range testMainDeps {
494 deps[dep] = true
497 for _, p := range pkgs {
498 // Dependencies for each test.
499 for _, path := range p.Imports {
500 deps[path] = true
502 for _, path := range p.Vendored(p.TestImports) {
503 deps[path] = true
505 for _, path := range p.Vendored(p.XTestImports) {
506 deps[path] = true
510 // translate C to runtime/cgo
511 if deps["C"] {
512 delete(deps, "C")
513 deps["runtime/cgo"] = true
514 if cfg.Goos == runtime.GOOS && cfg.Goarch == runtime.GOARCH && !cfg.BuildRace && !cfg.BuildMSan {
515 deps["cmd/cgo"] = true
518 // Ignore pseudo-packages.
519 delete(deps, "unsafe")
521 all := []string{}
522 for path := range deps {
523 if !build.IsLocalImport(path) {
524 all = append(all, path)
527 sort.Strings(all)
529 a := &work.Action{}
530 for _, p := range load.PackagesForBuild(all) {
531 if cfg.BuildToolchainName == "gccgo" && p.Standard {
532 continue
534 a.Deps = append(a.Deps, b.Action(work.ModeInstall, work.ModeInstall, p))
536 b.Do(a)
537 if !testC || a.Failed {
538 return
540 b.Init()
543 var builds, runs, prints []*work.Action
545 if testCoverPaths != nil {
546 // Load packages that were asked about for coverage.
547 // packagesForBuild exits if the packages cannot be loaded.
548 testCoverPkgs = load.PackagesForBuild(testCoverPaths)
550 // Warn about -coverpkg arguments that are not actually used.
551 used := make(map[string]bool)
552 for _, p := range pkgs {
553 used[p.ImportPath] = true
554 for _, dep := range p.Deps {
555 used[dep] = true
558 for _, p := range testCoverPkgs {
559 if !used[p.ImportPath] {
560 fmt.Fprintf(os.Stderr, "warning: no packages being tested depend on %s\n", p.ImportPath)
564 // Mark all the coverage packages for rebuilding with coverage.
565 for _, p := range testCoverPkgs {
566 // There is nothing to cover in package unsafe; it comes from the compiler.
567 if p.ImportPath == "unsafe" {
568 continue
570 p.Stale = true // rebuild
571 p.StaleReason = "rebuild for coverage"
572 p.Internal.Fake = true // do not warn about rebuild
573 p.Internal.CoverMode = testCoverMode
574 var coverFiles []string
575 coverFiles = append(coverFiles, p.GoFiles...)
576 coverFiles = append(coverFiles, p.CgoFiles...)
577 coverFiles = append(coverFiles, p.TestGoFiles...)
578 p.Internal.CoverVars = declareCoverVars(p.ImportPath, coverFiles...)
582 // Prepare build + run + print actions for all packages being tested.
583 for _, p := range pkgs {
584 // sync/atomic import is inserted by the cover tool. See #18486
585 if testCover && testCoverMode == "atomic" {
586 ensureImport(p, "sync/atomic")
589 buildTest, runTest, printTest, err := builderTest(&b, p)
590 if err != nil {
591 str := err.Error()
592 if strings.HasPrefix(str, "\n") {
593 str = str[1:]
595 failed := fmt.Sprintf("FAIL\t%s [setup failed]\n", p.ImportPath)
597 if p.ImportPath != "" {
598 base.Errorf("# %s\n%s\n%s", p.ImportPath, str, failed)
599 } else {
600 base.Errorf("%s\n%s", str, failed)
602 continue
604 builds = append(builds, buildTest)
605 runs = append(runs, runTest)
606 prints = append(prints, printTest)
609 // Ultimately the goal is to print the output.
610 root := &work.Action{Deps: prints}
612 // Force the printing of results to happen in order,
613 // one at a time.
614 for i, a := range prints {
615 if i > 0 {
616 a.Deps = append(a.Deps, prints[i-1])
620 // Force benchmarks to run in serial.
621 if !testC && testBench {
622 // The first run must wait for all builds.
623 // Later runs must wait for the previous run's print.
624 for i, run := range runs {
625 if i == 0 {
626 run.Deps = append(run.Deps, builds...)
627 } else {
628 run.Deps = append(run.Deps, prints[i-1])
633 // If we are building any out-of-date packages other
634 // than those under test, warn.
635 okBuild := map[*load.Package]bool{}
636 for _, p := range pkgs {
637 okBuild[p] = true
639 warned := false
640 for _, a := range work.ActionList(root) {
641 if a.Package == nil || okBuild[a.Package] {
642 continue
644 okBuild[a.Package] = true // warn at most once
646 // Don't warn about packages being rebuilt because of
647 // things like coverage analysis.
648 for _, p1 := range a.Package.Internal.Imports {
649 if p1.Internal.Fake {
650 a.Package.Internal.Fake = true
654 if a.Func != nil && !okBuild[a.Package] && !a.Package.Internal.Fake && !a.Package.Internal.Local {
655 if !warned {
656 fmt.Fprintf(os.Stderr, "warning: building out-of-date packages:\n")
657 warned = true
659 fmt.Fprintf(os.Stderr, "\t%s\n", a.Package.ImportPath)
662 if warned {
663 args := strings.Join(pkgArgs, " ")
664 if args != "" {
665 args = " " + args
667 extraOpts := ""
668 if cfg.BuildRace {
669 extraOpts = "-race "
671 if cfg.BuildMSan {
672 extraOpts = "-msan "
674 fmt.Fprintf(os.Stderr, "installing these packages with 'go test %s-i%s' will speed future tests.\n\n", extraOpts, args)
677 b.Do(root)
680 // ensures that package p imports the named package
681 func ensureImport(p *load.Package, pkg string) {
682 for _, d := range p.Internal.Deps {
683 if d.Name == pkg {
684 return
688 a := load.LoadPackage(pkg, &load.ImportStack{})
689 if a.Error != nil {
690 base.Fatalf("load %s: %v", pkg, a.Error)
692 load.ComputeStale(a)
694 p.Internal.Imports = append(p.Internal.Imports, a)
697 var windowsBadWords = []string{
698 "install",
699 "patch",
700 "setup",
701 "update",
704 func builderTest(b *work.Builder, p *load.Package) (buildAction, runAction, printAction *work.Action, err error) {
705 if len(p.TestGoFiles)+len(p.XTestGoFiles) == 0 {
706 build := b.Action(work.ModeBuild, work.ModeBuild, p)
707 run := &work.Action{Package: p, Deps: []*work.Action{build}}
708 print := &work.Action{Func: builderNoTest, Package: p, Deps: []*work.Action{run}}
709 return build, run, print, nil
712 // Build Package structs describing:
713 // ptest - package + test files
714 // pxtest - package of external test files
715 // pmain - pkg.test binary
716 var ptest, pxtest, pmain *load.Package
718 var imports, ximports []*load.Package
719 var stk load.ImportStack
720 stk.Push(p.ImportPath + " (test)")
721 for i, path := range p.TestImports {
722 p1 := load.LoadImport(path, p.Dir, p, &stk, p.Internal.Build.TestImportPos[path], load.UseVendor)
723 if cfg.BuildToolchainName == "gccgo" && p1.Standard {
724 continue
726 if p1.Error != nil {
727 return nil, nil, nil, p1.Error
729 if len(p1.DepsErrors) > 0 {
730 err := p1.DepsErrors[0]
731 err.Pos = "" // show full import stack
732 return nil, nil, nil, err
734 if str.Contains(p1.Deps, p.ImportPath) || p1.ImportPath == p.ImportPath {
735 // Same error that loadPackage returns (via reusePackage) in pkg.go.
736 // Can't change that code, because that code is only for loading the
737 // non-test copy of a package.
738 err := &load.PackageError{
739 ImportStack: testImportStack(stk[0], p1, p.ImportPath),
740 Err: "import cycle not allowed in test",
741 IsImportCycle: true,
743 return nil, nil, nil, err
745 p.TestImports[i] = p1.ImportPath
746 imports = append(imports, p1)
748 stk.Pop()
749 stk.Push(p.ImportPath + "_test")
750 pxtestNeedsPtest := false
751 for i, path := range p.XTestImports {
752 p1 := load.LoadImport(path, p.Dir, p, &stk, p.Internal.Build.XTestImportPos[path], load.UseVendor)
753 if cfg.BuildToolchainName == "gccgo" && p1.Standard {
754 continue
756 if p1.Error != nil {
757 return nil, nil, nil, p1.Error
759 if len(p1.DepsErrors) > 0 {
760 err := p1.DepsErrors[0]
761 err.Pos = "" // show full import stack
762 return nil, nil, nil, err
764 if p1.ImportPath == p.ImportPath {
765 pxtestNeedsPtest = true
766 } else {
767 ximports = append(ximports, p1)
769 p.XTestImports[i] = p1.ImportPath
771 stk.Pop()
773 // Use last element of import path, not package name.
774 // They differ when package name is "main".
775 // But if the import path is "command-line-arguments",
776 // like it is during 'go run', use the package name.
777 var elem string
778 if p.ImportPath == "command-line-arguments" {
779 elem = p.Name
780 } else {
781 _, elem = path.Split(p.ImportPath)
783 testBinary := elem + ".test"
785 // The ptest package needs to be importable under the
786 // same import path that p has, but we cannot put it in
787 // the usual place in the temporary tree, because then
788 // other tests will see it as the real package.
789 // Instead we make a _test directory under the import path
790 // and then repeat the import path there. We tell the
791 // compiler and linker to look in that _test directory first.
793 // That is, if the package under test is unicode/utf8,
794 // then the normal place to write the package archive is
795 // $WORK/unicode/utf8.a, but we write the test package archive to
796 // $WORK/unicode/utf8/_test/unicode/utf8.a.
797 // We write the external test package archive to
798 // $WORK/unicode/utf8/_test/unicode/utf8_test.a.
799 testDir := filepath.Join(b.WorkDir, filepath.FromSlash(p.ImportPath+"/_test"))
800 ptestObj := work.BuildToolchain.Pkgpath(testDir, p)
802 // Create the directory for the .a files.
803 ptestDir, _ := filepath.Split(ptestObj)
804 if err := b.Mkdir(ptestDir); err != nil {
805 return nil, nil, nil, err
808 // Should we apply coverage analysis locally,
809 // only for this package and only for this test?
810 // Yes, if -cover is on but -coverpkg has not specified
811 // a list of packages for global coverage.
812 localCover := testCover && testCoverPaths == nil
814 // Test package.
815 if len(p.TestGoFiles) > 0 || localCover || p.Name == "main" {
816 ptest = new(load.Package)
817 *ptest = *p
818 ptest.GoFiles = nil
819 ptest.GoFiles = append(ptest.GoFiles, p.GoFiles...)
820 ptest.GoFiles = append(ptest.GoFiles, p.TestGoFiles...)
821 ptest.Internal.Target = ""
822 ptest.Imports = str.StringList(p.Imports, p.TestImports)
823 ptest.Internal.Imports = append(append([]*load.Package{}, p.Internal.Imports...), imports...)
824 ptest.Internal.Pkgdir = testDir
825 ptest.Internal.Fake = true
826 ptest.Internal.ForceLibrary = true
827 ptest.Stale = true
828 ptest.StaleReason = "rebuild for test"
829 ptest.Internal.Build = new(build.Package)
830 *ptest.Internal.Build = *p.Internal.Build
831 m := map[string][]token.Position{}
832 for k, v := range p.Internal.Build.ImportPos {
833 m[k] = append(m[k], v...)
835 for k, v := range p.Internal.Build.TestImportPos {
836 m[k] = append(m[k], v...)
838 ptest.Internal.Build.ImportPos = m
840 if localCover {
841 ptest.Internal.CoverMode = testCoverMode
842 var coverFiles []string
843 coverFiles = append(coverFiles, ptest.GoFiles...)
844 coverFiles = append(coverFiles, ptest.CgoFiles...)
845 ptest.Internal.CoverVars = declareCoverVars(ptest.ImportPath, coverFiles...)
847 } else {
848 ptest = p
851 // External test package.
852 if len(p.XTestGoFiles) > 0 {
853 pxtest = &load.Package{
854 PackagePublic: load.PackagePublic{
855 Name: p.Name + "_test",
856 ImportPath: p.ImportPath + "_test",
857 Root: p.Root,
858 Dir: p.Dir,
859 GoFiles: p.XTestGoFiles,
860 Imports: p.XTestImports,
861 Stale: true,
863 Internal: load.PackageInternal{
864 LocalPrefix: p.Internal.LocalPrefix,
865 Build: &build.Package{
866 ImportPos: p.Internal.Build.XTestImportPos,
868 Imports: ximports,
869 Pkgdir: testDir,
870 Fake: true,
871 External: true,
874 if pxtestNeedsPtest {
875 pxtest.Internal.Imports = append(pxtest.Internal.Imports, ptest)
879 // Action for building pkg.test.
880 pmain = &load.Package{
881 PackagePublic: load.PackagePublic{
882 Name: "main",
883 Dir: testDir,
884 GoFiles: []string{"_testmain.go"},
885 ImportPath: "testmain",
886 Root: p.Root,
887 Stale: true,
889 Internal: load.PackageInternal{
890 Build: &build.Package{Name: "main"},
891 Pkgdir: testDir,
892 Fake: true,
893 OmitDebug: !testC && !testNeedBinary,
897 // The generated main also imports testing, regexp, and os.
898 stk.Push("testmain")
899 for dep := range testMainDeps {
900 if dep == ptest.ImportPath {
901 pmain.Internal.Imports = append(pmain.Internal.Imports, ptest)
902 } else {
903 p1 := load.LoadImport(dep, "", nil, &stk, nil, 0)
904 if cfg.BuildToolchainName == "gccgo" && p1.Standard {
905 continue
907 if p1.Error != nil {
908 return nil, nil, nil, p1.Error
910 pmain.Internal.Imports = append(pmain.Internal.Imports, p1)
914 if testCoverPkgs != nil {
915 // Add imports, but avoid duplicates.
916 seen := map[*load.Package]bool{p: true, ptest: true}
917 for _, p1 := range pmain.Internal.Imports {
918 seen[p1] = true
920 for _, p1 := range testCoverPkgs {
921 if !seen[p1] {
922 seen[p1] = true
923 pmain.Internal.Imports = append(pmain.Internal.Imports, p1)
928 // Do initial scan for metadata needed for writing _testmain.go
929 // Use that metadata to update the list of imports for package main.
930 // The list of imports is used by recompileForTest and by the loop
931 // afterward that gathers t.Cover information.
932 t, err := loadTestFuncs(ptest)
933 if err != nil {
934 return nil, nil, nil, err
936 if len(ptest.GoFiles)+len(ptest.CgoFiles) > 0 {
937 pmain.Internal.Imports = append(pmain.Internal.Imports, ptest)
938 t.ImportTest = true
940 if pxtest != nil {
941 pmain.Internal.Imports = append(pmain.Internal.Imports, pxtest)
942 t.ImportXtest = true
945 if ptest != p && localCover {
946 // We have made modifications to the package p being tested
947 // and are rebuilding p (as ptest), writing it to the testDir tree.
948 // Arrange to rebuild, writing to that same tree, all packages q
949 // such that the test depends on q, and q depends on p.
950 // This makes sure that q sees the modifications to p.
951 // Strictly speaking, the rebuild is only necessary if the
952 // modifications to p change its export metadata, but
953 // determining that is a bit tricky, so we rebuild always.
955 // This will cause extra compilation, so for now we only do it
956 // when testCover is set. The conditions are more general, though,
957 // and we may find that we need to do it always in the future.
958 recompileForTest(pmain, p, ptest, testDir)
961 if cfg.BuildContext.GOOS == "darwin" {
962 if cfg.BuildContext.GOARCH == "arm" || cfg.BuildContext.GOARCH == "arm64" {
963 t.NeedCgo = true
967 for _, cp := range pmain.Internal.Imports {
968 if len(cp.Internal.CoverVars) > 0 {
969 t.Cover = append(t.Cover, coverInfo{cp, cp.Internal.CoverVars})
973 if !cfg.BuildN {
974 // writeTestmain writes _testmain.go. This must happen after recompileForTest,
975 // because recompileForTest modifies XXX.
976 if err := writeTestmain(filepath.Join(testDir, "_testmain.go"), t); err != nil {
977 return nil, nil, nil, err
981 load.ComputeStale(pmain)
983 if ptest != p {
984 a := b.Action(work.ModeBuild, work.ModeBuild, ptest)
985 a.Objdir = testDir + string(filepath.Separator) + "_obj_test" + string(filepath.Separator)
986 a.Objpkg = ptestObj
987 a.Target = ptestObj
988 a.Link = false
991 if pxtest != nil {
992 a := b.Action(work.ModeBuild, work.ModeBuild, pxtest)
993 a.Objdir = testDir + string(filepath.Separator) + "_obj_xtest" + string(filepath.Separator)
994 a.Objpkg = work.BuildToolchain.Pkgpath(testDir, pxtest)
995 a.Target = a.Objpkg
998 a := b.Action(work.ModeBuild, work.ModeBuild, pmain)
999 a.Objdir = testDir + string(filepath.Separator)
1000 a.Objpkg = filepath.Join(testDir, "main.a")
1001 a.Target = filepath.Join(testDir, testBinary) + cfg.ExeSuffix
1002 if cfg.Goos == "windows" {
1003 // There are many reserved words on Windows that,
1004 // if used in the name of an executable, cause Windows
1005 // to try to ask for extra permissions.
1006 // The word list includes setup, install, update, and patch,
1007 // but it does not appear to be defined anywhere.
1008 // We have run into this trying to run the
1009 // go.codereview/patch tests.
1010 // For package names containing those words, use test.test.exe
1011 // instead of pkgname.test.exe.
1012 // Note that this file name is only used in the Go command's
1013 // temporary directory. If the -c or other flags are
1014 // given, the code below will still use pkgname.test.exe.
1015 // There are two user-visible effects of this change.
1016 // First, you can actually run 'go test' in directories that
1017 // have names that Windows thinks are installer-like,
1018 // without getting a dialog box asking for more permissions.
1019 // Second, in the Windows process listing during go test,
1020 // the test shows up as test.test.exe, not pkgname.test.exe.
1021 // That second one is a drawback, but it seems a small
1022 // price to pay for the test running at all.
1023 // If maintaining the list of bad words is too onerous,
1024 // we could just do this always on Windows.
1025 for _, bad := range windowsBadWords {
1026 if strings.Contains(testBinary, bad) {
1027 a.Target = filepath.Join(testDir, "test.test") + cfg.ExeSuffix
1028 break
1032 buildAction = a
1034 if testC || testNeedBinary {
1035 // -c or profiling flag: create action to copy binary to ./test.out.
1036 target := filepath.Join(base.Cwd, testBinary+cfg.ExeSuffix)
1037 if testO != "" {
1038 target = testO
1039 if !filepath.IsAbs(target) {
1040 target = filepath.Join(base.Cwd, target)
1043 buildAction = &work.Action{
1044 Func: work.BuildInstallFunc,
1045 Deps: []*work.Action{buildAction},
1046 Package: pmain,
1047 Target: target,
1049 runAction = buildAction // make sure runAction != nil even if not running test
1051 if testC {
1052 printAction = &work.Action{Package: p, Deps: []*work.Action{runAction}} // nop
1053 } else {
1054 // run test
1055 runAction = &work.Action{
1056 Func: builderRunTest,
1057 Deps: []*work.Action{buildAction},
1058 Package: p,
1059 IgnoreFail: true,
1061 cleanAction := &work.Action{
1062 Func: builderCleanTest,
1063 Deps: []*work.Action{runAction},
1064 Package: p,
1066 printAction = &work.Action{
1067 Func: builderPrintTest,
1068 Deps: []*work.Action{cleanAction},
1069 Package: p,
1073 return buildAction, runAction, printAction, nil
1076 func testImportStack(top string, p *load.Package, target string) []string {
1077 stk := []string{top, p.ImportPath}
1078 Search:
1079 for p.ImportPath != target {
1080 for _, p1 := range p.Internal.Imports {
1081 if p1.ImportPath == target || str.Contains(p1.Deps, target) {
1082 stk = append(stk, p1.ImportPath)
1083 p = p1
1084 continue Search
1087 // Can't happen, but in case it does...
1088 stk = append(stk, "<lost path to cycle>")
1089 break
1091 return stk
1094 func recompileForTest(pmain, preal, ptest *load.Package, testDir string) {
1095 // The "test copy" of preal is ptest.
1096 // For each package that depends on preal, make a "test copy"
1097 // that depends on ptest. And so on, up the dependency tree.
1098 testCopy := map[*load.Package]*load.Package{preal: ptest}
1099 for _, p := range load.PackageList([]*load.Package{pmain}) {
1100 // Copy on write.
1101 didSplit := false
1102 split := func() {
1103 if didSplit {
1104 return
1106 didSplit = true
1107 if p.Internal.Pkgdir != testDir {
1108 p1 := new(load.Package)
1109 testCopy[p] = p1
1110 *p1 = *p
1111 p1.Internal.Imports = make([]*load.Package, len(p.Internal.Imports))
1112 copy(p1.Internal.Imports, p.Internal.Imports)
1113 p = p1
1114 p.Internal.Pkgdir = testDir
1115 p.Internal.Target = ""
1116 p.Internal.Fake = true
1117 p.Stale = true
1118 p.StaleReason = "depends on package being tested"
1122 // Update p.Deps and p.Internal.Imports to use at test copies.
1123 for i, dep := range p.Internal.Deps {
1124 if p1 := testCopy[dep]; p1 != nil && p1 != dep {
1125 split()
1126 p.Internal.Deps[i] = p1
1129 for i, imp := range p.Internal.Imports {
1130 if p1 := testCopy[imp]; p1 != nil && p1 != imp {
1131 split()
1132 p.Internal.Imports[i] = p1
1138 var coverIndex = 0
1140 // isTestFile reports whether the source file is a set of tests and should therefore
1141 // be excluded from coverage analysis.
1142 func isTestFile(file string) bool {
1143 // We don't cover tests, only the code they test.
1144 return strings.HasSuffix(file, "_test.go")
1147 // declareCoverVars attaches the required cover variables names
1148 // to the files, to be used when annotating the files.
1149 func declareCoverVars(importPath string, files ...string) map[string]*load.CoverVar {
1150 coverVars := make(map[string]*load.CoverVar)
1151 for _, file := range files {
1152 if isTestFile(file) {
1153 continue
1155 coverVars[file] = &load.CoverVar{
1156 File: filepath.Join(importPath, file),
1157 Var: fmt.Sprintf("GoCover_%d", coverIndex),
1159 coverIndex++
1161 return coverVars
1164 var noTestsToRun = []byte("\ntesting: warning: no tests to run\n")
1166 // builderRunTest is the action for running a test binary.
1167 func builderRunTest(b *work.Builder, a *work.Action) error {
1168 args := str.StringList(work.FindExecCmd(), a.Deps[0].Target, testArgs)
1169 a.TestOutput = new(bytes.Buffer)
1171 if cfg.BuildN || cfg.BuildX {
1172 b.Showcmd("", "%s", strings.Join(args, " "))
1173 if cfg.BuildN {
1174 return nil
1178 if a.Failed {
1179 // We were unable to build the binary.
1180 a.Failed = false
1181 fmt.Fprintf(a.TestOutput, "FAIL\t%s [build failed]\n", a.Package.ImportPath)
1182 base.SetExitStatus(1)
1183 return nil
1186 cmd := exec.Command(args[0], args[1:]...)
1187 cmd.Dir = a.Package.Dir
1188 cmd.Env = base.EnvForDir(cmd.Dir, cfg.OrigEnv)
1189 var buf bytes.Buffer
1190 if testStreamOutput {
1191 cmd.Stdout = os.Stdout
1192 cmd.Stderr = os.Stderr
1193 } else {
1194 cmd.Stdout = &buf
1195 cmd.Stderr = &buf
1198 // If there are any local SWIG dependencies, we want to load
1199 // the shared library from the build directory.
1200 if a.Package.UsesSwig() {
1201 env := cmd.Env
1202 found := false
1203 prefix := "LD_LIBRARY_PATH="
1204 for i, v := range env {
1205 if strings.HasPrefix(v, prefix) {
1206 env[i] = v + ":."
1207 found = true
1208 break
1211 if !found {
1212 env = append(env, "LD_LIBRARY_PATH=.")
1214 cmd.Env = env
1217 t0 := time.Now()
1218 err := cmd.Start()
1220 // This is a last-ditch deadline to detect and
1221 // stop wedged test binaries, to keep the builders
1222 // running.
1223 if err == nil {
1224 tick := time.NewTimer(testKillTimeout)
1225 base.StartSigHandlers()
1226 done := make(chan error)
1227 go func() {
1228 done <- cmd.Wait()
1230 Outer:
1231 select {
1232 case err = <-done:
1233 // ok
1234 case <-tick.C:
1235 if base.SignalTrace != nil {
1236 // Send a quit signal in the hope that the program will print
1237 // a stack trace and exit. Give it five seconds before resorting
1238 // to Kill.
1239 cmd.Process.Signal(base.SignalTrace)
1240 select {
1241 case err = <-done:
1242 fmt.Fprintf(&buf, "*** Test killed with %v: ran too long (%v).\n", base.SignalTrace, testKillTimeout)
1243 break Outer
1244 case <-time.After(5 * time.Second):
1247 cmd.Process.Kill()
1248 err = <-done
1249 fmt.Fprintf(&buf, "*** Test killed: ran too long (%v).\n", testKillTimeout)
1251 tick.Stop()
1253 out := buf.Bytes()
1254 t := fmt.Sprintf("%.3fs", time.Since(t0).Seconds())
1255 if err == nil {
1256 norun := ""
1257 if testShowPass {
1258 a.TestOutput.Write(out)
1260 if bytes.HasPrefix(out, noTestsToRun[1:]) || bytes.Contains(out, noTestsToRun) {
1261 norun = " [no tests to run]"
1263 fmt.Fprintf(a.TestOutput, "ok \t%s\t%s%s%s\n", a.Package.ImportPath, t, coveragePercentage(out), norun)
1264 return nil
1267 base.SetExitStatus(1)
1268 if len(out) > 0 {
1269 a.TestOutput.Write(out)
1270 // assume printing the test binary's exit status is superfluous
1271 } else {
1272 fmt.Fprintf(a.TestOutput, "%s\n", err)
1274 fmt.Fprintf(a.TestOutput, "FAIL\t%s\t%s\n", a.Package.ImportPath, t)
1276 return nil
1279 // coveragePercentage returns the coverage results (if enabled) for the
1280 // test. It uncovers the data by scanning the output from the test run.
1281 func coveragePercentage(out []byte) string {
1282 if !testCover {
1283 return ""
1285 // The string looks like
1286 // test coverage for encoding/binary: 79.9% of statements
1287 // Extract the piece from the percentage to the end of the line.
1288 re := regexp.MustCompile(`coverage: (.*)\n`)
1289 matches := re.FindSubmatch(out)
1290 if matches == nil {
1291 // Probably running "go test -cover" not "go test -cover fmt".
1292 // The coverage output will appear in the output directly.
1293 return ""
1295 return fmt.Sprintf("\tcoverage: %s", matches[1])
1298 // builderCleanTest is the action for cleaning up after a test.
1299 func builderCleanTest(b *work.Builder, a *work.Action) error {
1300 if cfg.BuildWork {
1301 return nil
1303 run := a.Deps[0]
1304 testDir := filepath.Join(b.WorkDir, filepath.FromSlash(run.Package.ImportPath+"/_test"))
1305 os.RemoveAll(testDir)
1306 return nil
1309 // builderPrintTest is the action for printing a test result.
1310 func builderPrintTest(b *work.Builder, a *work.Action) error {
1311 clean := a.Deps[0]
1312 run := clean.Deps[0]
1313 os.Stdout.Write(run.TestOutput.Bytes())
1314 run.TestOutput = nil
1315 return nil
1318 // builderNoTest is the action for testing a package with no test files.
1319 func builderNoTest(b *work.Builder, a *work.Action) error {
1320 fmt.Printf("? \t%s\t[no test files]\n", a.Package.ImportPath)
1321 return nil
1324 // isTestFunc tells whether fn has the type of a testing function. arg
1325 // specifies the parameter type we look for: B, M or T.
1326 func isTestFunc(fn *ast.FuncDecl, arg string) bool {
1327 if fn.Type.Results != nil && len(fn.Type.Results.List) > 0 ||
1328 fn.Type.Params.List == nil ||
1329 len(fn.Type.Params.List) != 1 ||
1330 len(fn.Type.Params.List[0].Names) > 1 {
1331 return false
1333 ptr, ok := fn.Type.Params.List[0].Type.(*ast.StarExpr)
1334 if !ok {
1335 return false
1337 // We can't easily check that the type is *testing.M
1338 // because we don't know how testing has been imported,
1339 // but at least check that it's *M or *something.M.
1340 // Same applies for B and T.
1341 if name, ok := ptr.X.(*ast.Ident); ok && name.Name == arg {
1342 return true
1344 if sel, ok := ptr.X.(*ast.SelectorExpr); ok && sel.Sel.Name == arg {
1345 return true
1347 return false
1350 // isTest tells whether name looks like a test (or benchmark, according to prefix).
1351 // It is a Test (say) if there is a character after Test that is not a lower-case letter.
1352 // We don't want TesticularCancer.
1353 func isTest(name, prefix string) bool {
1354 if !strings.HasPrefix(name, prefix) {
1355 return false
1357 if len(name) == len(prefix) { // "Test" is ok
1358 return true
1360 rune, _ := utf8.DecodeRuneInString(name[len(prefix):])
1361 return !unicode.IsLower(rune)
1364 type coverInfo struct {
1365 Package *load.Package
1366 Vars map[string]*load.CoverVar
1369 // loadTestFuncs returns the testFuncs describing the tests that will be run.
1370 func loadTestFuncs(ptest *load.Package) (*testFuncs, error) {
1371 t := &testFuncs{
1372 Package: ptest,
1374 for _, file := range ptest.TestGoFiles {
1375 if err := t.load(filepath.Join(ptest.Dir, file), "_test", &t.ImportTest, &t.NeedTest); err != nil {
1376 return nil, err
1379 for _, file := range ptest.XTestGoFiles {
1380 if err := t.load(filepath.Join(ptest.Dir, file), "_xtest", &t.ImportXtest, &t.NeedXtest); err != nil {
1381 return nil, err
1384 return t, nil
1387 // writeTestmain writes the _testmain.go file for t to the file named out.
1388 func writeTestmain(out string, t *testFuncs) error {
1389 f, err := os.Create(out)
1390 if err != nil {
1391 return err
1393 defer f.Close()
1395 if err := testmainTmpl.Execute(f, t); err != nil {
1396 return err
1399 return nil
1402 type testFuncs struct {
1403 Tests []testFunc
1404 Benchmarks []testFunc
1405 Examples []testFunc
1406 TestMain *testFunc
1407 Package *load.Package
1408 ImportTest bool
1409 NeedTest bool
1410 ImportXtest bool
1411 NeedXtest bool
1412 NeedCgo bool
1413 Cover []coverInfo
1416 func (t *testFuncs) CoverMode() string {
1417 return testCoverMode
1420 func (t *testFuncs) CoverEnabled() bool {
1421 return testCover
1424 // ImportPath returns the import path of the package being tested, if it is within GOPATH.
1425 // This is printed by the testing package when running benchmarks.
1426 func (t *testFuncs) ImportPath() string {
1427 pkg := t.Package.ImportPath
1428 if strings.HasPrefix(pkg, "_/") {
1429 return ""
1431 if pkg == "command-line-arguments" {
1432 return ""
1434 return pkg
1437 // Covered returns a string describing which packages are being tested for coverage.
1438 // If the covered package is the same as the tested package, it returns the empty string.
1439 // Otherwise it is a comma-separated human-readable list of packages beginning with
1440 // " in", ready for use in the coverage message.
1441 func (t *testFuncs) Covered() string {
1442 if testCoverPaths == nil {
1443 return ""
1445 return " in " + strings.Join(testCoverPaths, ", ")
1448 // Tested returns the name of the package being tested.
1449 func (t *testFuncs) Tested() string {
1450 return t.Package.Name
1453 type testFunc struct {
1454 Package string // imported package name (_test or _xtest)
1455 Name string // function name
1456 Output string // output, for examples
1457 Unordered bool // output is allowed to be unordered.
1460 var testFileSet = token.NewFileSet()
1462 func (t *testFuncs) load(filename, pkg string, doImport, seen *bool) error {
1463 f, err := parser.ParseFile(testFileSet, filename, nil, parser.ParseComments)
1464 if err != nil {
1465 return base.ExpandScanner(err)
1467 for _, d := range f.Decls {
1468 n, ok := d.(*ast.FuncDecl)
1469 if !ok {
1470 continue
1472 if n.Recv != nil {
1473 continue
1475 name := n.Name.String()
1476 switch {
1477 case name == "TestMain" && isTestFunc(n, "M"):
1478 if t.TestMain != nil {
1479 return errors.New("multiple definitions of TestMain")
1481 t.TestMain = &testFunc{pkg, name, "", false}
1482 *doImport, *seen = true, true
1483 case isTest(name, "Test"):
1484 err := checkTestFunc(n, "T")
1485 if err != nil {
1486 return err
1488 t.Tests = append(t.Tests, testFunc{pkg, name, "", false})
1489 *doImport, *seen = true, true
1490 case isTest(name, "Benchmark"):
1491 err := checkTestFunc(n, "B")
1492 if err != nil {
1493 return err
1495 t.Benchmarks = append(t.Benchmarks, testFunc{pkg, name, "", false})
1496 *doImport, *seen = true, true
1499 ex := doc.Examples(f)
1500 sort.Slice(ex, func(i, j int) bool { return ex[i].Order < ex[j].Order })
1501 for _, e := range ex {
1502 *doImport = true // import test file whether executed or not
1503 if e.Output == "" && !e.EmptyOutput {
1504 // Don't run examples with no output.
1505 continue
1507 t.Examples = append(t.Examples, testFunc{pkg, "Example" + e.Name, e.Output, e.Unordered})
1508 *seen = true
1510 return nil
1513 func checkTestFunc(fn *ast.FuncDecl, arg string) error {
1514 if !isTestFunc(fn, arg) {
1515 name := fn.Name.String()
1516 pos := testFileSet.Position(fn.Pos())
1517 return fmt.Errorf("%s: wrong signature for %s, must be: func %s(%s *testing.%s)", pos, name, name, strings.ToLower(arg), arg)
1519 return nil
1522 var testmainTmpl = template.Must(template.New("main").Parse(`
1523 package main
1525 import (
1526 {{if not .TestMain}}
1527 "os"
1528 {{end}}
1529 "testing"
1530 "testing/internal/testdeps"
1532 {{if .ImportTest}}
1533 {{if .NeedTest}}_test{{else}}_{{end}} {{.Package.ImportPath | printf "%q"}}
1534 {{end}}
1535 {{if .ImportXtest}}
1536 {{if .NeedXtest}}_xtest{{else}}_{{end}} {{.Package.ImportPath | printf "%s_test" | printf "%q"}}
1537 {{end}}
1538 {{range $i, $p := .Cover}}
1539 _cover{{$i}} {{$p.Package.ImportPath | printf "%q"}}
1540 {{end}}
1542 {{if .NeedCgo}}
1543 _ "runtime/cgo"
1544 {{end}}
1547 var tests = []testing.InternalTest{
1548 {{range .Tests}}
1549 {"{{.Name}}", {{.Package}}.{{.Name}}},
1550 {{end}}
1553 var benchmarks = []testing.InternalBenchmark{
1554 {{range .Benchmarks}}
1555 {"{{.Name}}", {{.Package}}.{{.Name}}},
1556 {{end}}
1559 var examples = []testing.InternalExample{
1560 {{range .Examples}}
1561 {"{{.Name}}", {{.Package}}.{{.Name}}, {{.Output | printf "%q"}}, {{.Unordered}}},
1562 {{end}}
1565 func init() {
1566 testdeps.ImportPath = {{.ImportPath | printf "%q"}}
1569 {{if .CoverEnabled}}
1571 // Only updated by init functions, so no need for atomicity.
1572 var (
1573 coverCounters = make(map[string][]uint32)
1574 coverBlocks = make(map[string][]testing.CoverBlock)
1577 func init() {
1578 {{range $i, $p := .Cover}}
1579 {{range $file, $cover := $p.Vars}}
1580 coverRegisterFile({{printf "%q" $cover.File}}, _cover{{$i}}.{{$cover.Var}}.Count[:], _cover{{$i}}.{{$cover.Var}}.Pos[:], _cover{{$i}}.{{$cover.Var}}.NumStmt[:])
1581 {{end}}
1582 {{end}}
1585 func coverRegisterFile(fileName string, counter []uint32, pos []uint32, numStmts []uint16) {
1586 if 3*len(counter) != len(pos) || len(counter) != len(numStmts) {
1587 panic("coverage: mismatched sizes")
1589 if coverCounters[fileName] != nil {
1590 // Already registered.
1591 return
1593 coverCounters[fileName] = counter
1594 block := make([]testing.CoverBlock, len(counter))
1595 for i := range counter {
1596 block[i] = testing.CoverBlock{
1597 Line0: pos[3*i+0],
1598 Col0: uint16(pos[3*i+2]),
1599 Line1: pos[3*i+1],
1600 Col1: uint16(pos[3*i+2]>>16),
1601 Stmts: numStmts[i],
1604 coverBlocks[fileName] = block
1606 {{end}}
1608 func main() {
1609 {{if .CoverEnabled}}
1610 testing.RegisterCover(testing.Cover{
1611 Mode: {{printf "%q" .CoverMode}},
1612 Counters: coverCounters,
1613 Blocks: coverBlocks,
1614 CoveredPackages: {{printf "%q" .Covered}},
1616 {{end}}
1617 m := testing.MainStart(testdeps.TestDeps{}, tests, benchmarks, examples)
1618 {{with .TestMain}}
1619 {{.Package}}.{{.Name}}(m)
1620 {{else}}
1621 os.Exit(m.Run())
1622 {{end}}