Home | History | Annotate | Download | only in go
      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.
      4 
      5 package main
      6 
      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"
     28 )
     29 
     30 // Break init loop.
     31 func init() {
     32 	cmdTest.Run = runTest
     33 }
     34 
     35 const testUsage = "test [build/test flags] [packages] [build/test flags & test binary flags]"
     36 
     37 var cmdTest = &Command{
     38 	CustomFlags: true,
     39 	UsageLine:   testUsage,
     40 	Short:       "test packages",
     41 	Long: `
     42 'Go test' automates testing the packages named by the import paths.
     43 It prints a summary of the test results in the format:
     44 
     45 	ok   archive/tar   0.011s
     46 	FAIL archive/zip   0.022s
     47 	ok   compress/gzip 0.033s
     48 	...
     49 
     50 followed by detailed output for each failed package.
     51 
     52 'Go test' recompiles each package along with any files with names matching
     53 the file pattern "*_test.go".
     54 Files whose names begin with "_" (including "_test.go") or "." are ignored.
     55 These additional files can contain test functions, benchmark functions, and
     56 example functions.  See 'go help testfunc' for more.
     57 Each listed package causes the execution of a separate test binary.
     58 
     59 Test files that declare a package with the suffix "_test" will be compiled as a
     60 separate package, and then linked and run with the main test binary.
     61 
     62 The go tool will ignore a directory named "testdata", making it available
     63 to hold ancillary data needed by the tests.
     64 
     65 By default, go test needs no arguments.  It compiles and tests the package
     66 with source in the current directory, including tests, and runs the tests.
     67 
     68 The package is built in a temporary directory so it does not interfere with the
     69 non-test installation.
     70 
     71 ` + strings.TrimSpace(testFlag1) + ` See 'go help testflag' for details.
     72 
     73 For more about build flags, see 'go help build'.
     74 For more about specifying packages, see 'go help packages'.
     75 
     76 See also: go build, go vet.
     77 `,
     78 }
     79 
     80 const testFlag1 = `
     81 In addition to the build flags, the flags handled by 'go test' itself are:
     82 
     83 	-args
     84 	    Pass the remainder of the command line (everything after -args)
     85 	    to the test binary, uninterpreted and unchanged.
     86 	    Because this flag consumes the remainder of the command line,
     87 	    the package list (if present) must appear before this flag.
     88 
     89 	-c
     90 	    Compile the test binary to pkg.test but do not run it
     91 	    (where pkg is the last element of the package's import path).
     92 	    The file name can be changed with the -o flag.
     93 
     94 	-exec xprog
     95 	    Run the test binary using xprog. The behavior is the same as
     96 	    in 'go run'. See 'go help run' for details.
     97 
     98 	-i
     99 	    Install packages that are dependencies of the test.
    100 	    Do not run the test.
    101 
    102 	-o file
    103 	    Compile the test binary to the named file.
    104 	    The test still runs (unless -c or -i is specified).
    105 
    106 The test binary also accepts flags that control execution of the test; these
    107 flags are also accessible by 'go test'.
    108 `
    109 
    110 var helpTestflag = &Command{
    111 	UsageLine: "testflag",
    112 	Short:     "description of testing flags",
    113 	Long: `
    114 The 'go test' command takes both flags that apply to 'go test' itself
    115 and flags that apply to the resulting test binary.
    116 
    117 Several of the flags control profiling and write an execution profile
    118 suitable for "go tool pprof"; run "go tool pprof -h" for more
    119 information.  The --alloc_space, --alloc_objects, and --show_bytes
    120 options of pprof control how the information is presented.
    121 
    122 The following flags are recognized by the 'go test' command and
    123 control the execution of any test:
    124 
    125 	` + strings.TrimSpace(testFlag2) + `
    126 `,
    127 }
    128 
    129 const testFlag2 = `
    130 	-bench regexp
    131 	    Run (sub)benchmarks matching a regular expression.
    132 	    The given regular expression is split into smaller ones by
    133 	    top-level '/', where each must match the corresponding part of a
    134 	    benchmark's identifier.
    135 	    By default, no benchmarks run. To run all benchmarks,
    136 	    use '-bench .' or '-bench=.'.
    137 
    138 	-benchtime t
    139 	    Run enough iterations of each benchmark to take t, specified
    140 	    as a time.Duration (for example, -benchtime 1h30s).
    141 	    The default is 1 second (1s).
    142 
    143 	-count n
    144 	    Run each test and benchmark n times (default 1).
    145 	    If -cpu is set, run n times for each GOMAXPROCS value.
    146 	    Examples are always run once.
    147 
    148 	-cover
    149 	    Enable coverage analysis.
    150 
    151 	-covermode set,count,atomic
    152 	    Set the mode for coverage analysis for the package[s]
    153 	    being tested. The default is "set" unless -race is enabled,
    154 	    in which case it is "atomic".
    155 	    The values:
    156 		set: bool: does this statement run?
    157 		count: int: how many times does this statement run?
    158 		atomic: int: count, but correct in multithreaded tests;
    159 			significantly more expensive.
    160 	    Sets -cover.
    161 
    162 	-coverpkg pkg1,pkg2,pkg3
    163 	    Apply coverage analysis in each test to the given list of packages.
    164 	    The default is for each test to analyze only the package being tested.
    165 	    Packages are specified as import paths.
    166 	    Sets -cover.
    167 
    168 	-cpu 1,2,4
    169 	    Specify a list of GOMAXPROCS values for which the tests or
    170 	    benchmarks should be executed.  The default is the current value
    171 	    of GOMAXPROCS.
    172 
    173 	-parallel n
    174 	    Allow parallel execution of test functions that call t.Parallel.
    175 	    The value of this flag is the maximum number of tests to run
    176 	    simultaneously; by default, it is set to the value of GOMAXPROCS.
    177 	    Note that -parallel only applies within a single test binary.
    178 	    The 'go test' command may run tests for different packages
    179 	    in parallel as well, according to the setting of the -p flag
    180 	    (see 'go help build').
    181 
    182 	-run regexp
    183 	    Run only those tests and examples matching the regular expression.
    184 	    For tests the regular expression is split into smaller ones by
    185 	    top-level '/', where each must match the corresponding part of a
    186 	    test's identifier.
    187 
    188 	-short
    189 	    Tell long-running tests to shorten their run time.
    190 	    It is off by default but set during all.bash so that installing
    191 	    the Go tree can run a sanity check but not spend time running
    192 	    exhaustive tests.
    193 
    194 	-timeout t
    195 	    If a test runs longer than t, panic.
    196 	    The default is 10 minutes (10m).
    197 
    198 	-v
    199 	    Verbose output: log all tests as they are run. Also print all
    200 	    text from Log and Logf calls even if the test succeeds.
    201 
    202 The following flags are also recognized by 'go test' and can be used to
    203 profile the tests during execution:
    204 
    205 	-benchmem
    206 	    Print memory allocation statistics for benchmarks.
    207 
    208 	-blockprofile block.out
    209 	    Write a goroutine blocking profile to the specified file
    210 	    when all tests are complete.
    211 	    Writes test binary as -c would.
    212 
    213 	-blockprofilerate n
    214 	    Control the detail provided in goroutine blocking profiles by
    215 	    calling runtime.SetBlockProfileRate with n.
    216 	    See 'go doc runtime.SetBlockProfileRate'.
    217 	    The profiler aims to sample, on average, one blocking event every
    218 	    n nanoseconds the program spends blocked.  By default,
    219 	    if -test.blockprofile is set without this flag, all blocking events
    220 	    are recorded, equivalent to -test.blockprofilerate=1.
    221 
    222 	-coverprofile cover.out
    223 	    Write a coverage profile to the file after all tests have passed.
    224 	    Sets -cover.
    225 
    226 	-cpuprofile cpu.out
    227 	    Write a CPU profile to the specified file before exiting.
    228 	    Writes test binary as -c would.
    229 
    230 	-memprofile mem.out
    231 	    Write a memory profile to the file after all tests have passed.
    232 	    Writes test binary as -c would.
    233 
    234 	-memprofilerate n
    235 	    Enable more precise (and expensive) memory profiles by setting
    236 	    runtime.MemProfileRate.  See 'go doc runtime.MemProfileRate'.
    237 	    To profile all memory allocations, use -test.memprofilerate=1
    238 	    and pass --alloc_space flag to the pprof tool.
    239 
    240 	-mutexprofile mutex.out
    241 	    Write a mutex contention profile to the specified file
    242 	    when all tests are complete.
    243 	    Writes test binary as -c would.
    244 
    245 	-mutexprofilefraction n
    246 	    Sample 1 in n stack traces of goroutines holding a
    247 	    contended mutex.
    248 
    249 	-outputdir directory
    250 	    Place output files from profiling in the specified directory,
    251 	    by default the directory in which "go test" is running.
    252 
    253 	-trace trace.out
    254 	    Write an execution trace to the specified file before exiting.
    255 
    256 Each of these flags is also recognized with an optional 'test.' prefix,
    257 as in -test.v. When invoking the generated test binary (the result of
    258 'go test -c') directly, however, the prefix is mandatory.
    259 
    260 The 'go test' command rewrites or removes recognized flags,
    261 as appropriate, both before and after the optional package list,
    262 before invoking the test binary.
    263 
    264 For instance, the command
    265 
    266 	go test -v -myflag testdata -cpuprofile=prof.out -x
    267 
    268 will compile the test binary and then run it as
    269 
    270 	pkg.test -test.v -myflag testdata -test.cpuprofile=prof.out
    271 
    272 (The -x flag is removed because it applies only to the go command's
    273 execution, not to the test itself.)
    274 
    275 The test flags that generate profiles (other than for coverage) also
    276 leave the test binary in pkg.test for use when analyzing the profiles.
    277 
    278 When 'go test' runs a test binary, it does so from within the
    279 corresponding package's source code directory. Depending on the test,
    280 it may be necessary to do the same when invoking a generated test
    281 binary directly.
    282 
    283 The command-line package list, if present, must appear before any
    284 flag not known to the go test command. Continuing the example above,
    285 the package list would have to appear before -myflag, but could appear
    286 on either side of -v.
    287 
    288 To keep an argument for a test binary from being interpreted as a
    289 known flag or a package name, use -args (see 'go help test') which
    290 passes the remainder of the command line through to the test binary
    291 uninterpreted and unaltered.
    292 
    293 For instance, the command
    294 
    295 	go test -v -args -x -v
    296 
    297 will compile the test binary and then run it as
    298 
    299 	pkg.test -test.v -x -v
    300 
    301 Similarly,
    302 
    303 	go test -args math
    304 
    305 will compile the test binary and then run it as
    306 
    307 	pkg.test math
    308 
    309 In the first example, the -x and the second -v are passed through to the
    310 test binary unchanged and with no effect on the go command itself.
    311 In the second example, the argument math is passed through to the test
    312 binary, instead of being interpreted as the package list.
    313 `
    314 
    315 var helpTestfunc = &Command{
    316 	UsageLine: "testfunc",
    317 	Short:     "description of testing functions",
    318 	Long: `
    319 The 'go test' command expects to find test, benchmark, and example functions
    320 in the "*_test.go" files corresponding to the package under test.
    321 
    322 A test function is one named TestXXX (where XXX is any alphanumeric string
    323 not starting with a lower case letter) and should have the signature,
    324 
    325 	func TestXXX(t *testing.T) { ... }
    326 
    327 A benchmark function is one named BenchmarkXXX and should have the signature,
    328 
    329 	func BenchmarkXXX(b *testing.B) { ... }
    330 
    331 An example function is similar to a test function but, instead of using
    332 *testing.T to report success or failure, prints output to os.Stdout.
    333 If the last comment in the function starts with "Output:" then the output
    334 is compared exactly against the comment (see examples below). If the last
    335 comment begins with "Unordered output:" then the output is compared to the
    336 comment, however the order of the lines is ignored. An example with no such
    337 comment is compiled but not executed. An example with no text after
    338 "Output:" is compiled, executed, and expected to produce no output.
    339 
    340 Godoc displays the body of ExampleXXX to demonstrate the use
    341 of the function, constant, or variable XXX.  An example of a method M with
    342 receiver type T or *T is named ExampleT_M.  There may be multiple examples
    343 for a given function, constant, or variable, distinguished by a trailing _xxx,
    344 where xxx is a suffix not beginning with an upper case letter.
    345 
    346 Here is an example of an example:
    347 
    348 	func ExamplePrintln() {
    349 		Println("The output of\nthis example.")
    350 		// Output: The output of
    351 		// this example.
    352 	}
    353 
    354 Here is another example where the ordering of the output is ignored:
    355 
    356 	func ExamplePerm() {
    357 		for _, value := range Perm(4) {
    358 			fmt.Println(value)
    359 		}
    360 
    361 		// Unordered output: 4
    362 		// 2
    363 		// 1
    364 		// 3
    365 		// 0
    366 	}
    367 
    368 The entire test file is presented as the example when it contains a single
    369 example function, at least one other function, type, variable, or constant
    370 declaration, and no test or benchmark functions.
    371 
    372 See the documentation of the testing package for more information.
    373 `,
    374 }
    375 
    376 var (
    377 	testC            bool       // -c flag
    378 	testCover        bool       // -cover flag
    379 	testCoverMode    string     // -covermode flag
    380 	testCoverPaths   []string   // -coverpkg flag
    381 	testCoverPkgs    []*Package // -coverpkg flag
    382 	testO            string     // -o flag
    383 	testProfile      bool       // some profiling flag
    384 	testNeedBinary   bool       // profile needs to keep binary around
    385 	testV            bool       // -v flag
    386 	testTimeout      string     // -timeout flag
    387 	testArgs         []string
    388 	testBench        bool
    389 	testStreamOutput bool // show output as it is generated
    390 	testShowPass     bool // show passing output
    391 
    392 	testKillTimeout = 10 * time.Minute
    393 )
    394 
    395 var testMainDeps = map[string]bool{
    396 	// Dependencies for testmain.
    397 	"testing":                   true,
    398 	"testing/internal/testdeps": true,
    399 	"os": true,
    400 }
    401 
    402 func runTest(cmd *Command, args []string) {
    403 	var pkgArgs []string
    404 	pkgArgs, testArgs = testFlags(args)
    405 
    406 	findExecCmd() // initialize cached result
    407 
    408 	instrumentInit()
    409 	buildModeInit()
    410 	pkgs := packagesForBuild(pkgArgs)
    411 	if len(pkgs) == 0 {
    412 		fatalf("no packages to test")
    413 	}
    414 
    415 	if testC && len(pkgs) != 1 {
    416 		fatalf("cannot use -c flag with multiple packages")
    417 	}
    418 	if testO != "" && len(pkgs) != 1 {
    419 		fatalf("cannot use -o flag with multiple packages")
    420 	}
    421 	if testProfile && len(pkgs) != 1 {
    422 		fatalf("cannot use test profile flag with multiple packages")
    423 	}
    424 
    425 	// If a test timeout was given and is parseable, set our kill timeout
    426 	// to that timeout plus one minute. This is a backup alarm in case
    427 	// the test wedges with a goroutine spinning and its background
    428 	// timer does not get a chance to fire.
    429 	if dt, err := time.ParseDuration(testTimeout); err == nil && dt > 0 {
    430 		testKillTimeout = dt + 1*time.Minute
    431 	}
    432 
    433 	// show passing test output (after buffering) with -v flag.
    434 	// must buffer because tests are running in parallel, and
    435 	// otherwise the output will get mixed.
    436 	testShowPass = testV
    437 
    438 	// stream test output (no buffering) when no package has
    439 	// been given on the command line (implicit current directory)
    440 	// or when benchmarking.
    441 	// Also stream if we're showing output anyway with a
    442 	// single package under test or if parallelism is set to 1.
    443 	// In these cases, streaming the output produces the same result
    444 	// as not streaming, just more immediately.
    445 	testStreamOutput = len(pkgArgs) == 0 || testBench ||
    446 		(testShowPass && (len(pkgs) == 1 || buildP == 1))
    447 
    448 	// For 'go test -i -o x.test', we want to build x.test. Imply -c to make the logic easier.
    449 	if buildI && testO != "" {
    450 		testC = true
    451 	}
    452 
    453 	var b builder
    454 	b.init()
    455 
    456 	if buildI {
    457 		buildV = testV
    458 
    459 		deps := make(map[string]bool)
    460 		for dep := range testMainDeps {
    461 			deps[dep] = true
    462 		}
    463 
    464 		for _, p := range pkgs {
    465 			// Dependencies for each test.
    466 			for _, path := range p.Imports {
    467 				deps[path] = true
    468 			}
    469 			for _, path := range p.vendored(p.TestImports) {
    470 				deps[path] = true
    471 			}
    472 			for _, path := range p.vendored(p.XTestImports) {
    473 				deps[path] = true
    474 			}
    475 		}
    476 
    477 		// translate C to runtime/cgo
    478 		if deps["C"] {
    479 			delete(deps, "C")
    480 			deps["runtime/cgo"] = true
    481 			if goos == runtime.GOOS && goarch == runtime.GOARCH && !buildRace && !buildMSan {
    482 				deps["cmd/cgo"] = true
    483 			}
    484 		}
    485 		// Ignore pseudo-packages.
    486 		delete(deps, "unsafe")
    487 
    488 		all := []string{}
    489 		for path := range deps {
    490 			if !build.IsLocalImport(path) {
    491 				all = append(all, path)
    492 			}
    493 		}
    494 		sort.Strings(all)
    495 
    496 		a := &action{}
    497 		for _, p := range packagesForBuild(all) {
    498 			a.deps = append(a.deps, b.action(modeInstall, modeInstall, p))
    499 		}
    500 		b.do(a)
    501 		if !testC || a.failed {
    502 			return
    503 		}
    504 		b.init()
    505 	}
    506 
    507 	var builds, runs, prints []*action
    508 
    509 	if testCoverPaths != nil {
    510 		// Load packages that were asked about for coverage.
    511 		// packagesForBuild exits if the packages cannot be loaded.
    512 		testCoverPkgs = packagesForBuild(testCoverPaths)
    513 
    514 		// Warn about -coverpkg arguments that are not actually used.
    515 		used := make(map[string]bool)
    516 		for _, p := range pkgs {
    517 			used[p.ImportPath] = true
    518 			for _, dep := range p.Deps {
    519 				used[dep] = true
    520 			}
    521 		}
    522 		for _, p := range testCoverPkgs {
    523 			if !used[p.ImportPath] {
    524 				fmt.Fprintf(os.Stderr, "warning: no packages being tested depend on %s\n", p.ImportPath)
    525 			}
    526 		}
    527 
    528 		// Mark all the coverage packages for rebuilding with coverage.
    529 		for _, p := range testCoverPkgs {
    530 			// There is nothing to cover in package unsafe; it comes from the compiler.
    531 			if p.ImportPath == "unsafe" {
    532 				continue
    533 			}
    534 			p.Stale = true // rebuild
    535 			p.StaleReason = "rebuild for coverage"
    536 			p.fake = true // do not warn about rebuild
    537 			p.coverMode = testCoverMode
    538 			var coverFiles []string
    539 			coverFiles = append(coverFiles, p.GoFiles...)
    540 			coverFiles = append(coverFiles, p.CgoFiles...)
    541 			coverFiles = append(coverFiles, p.TestGoFiles...)
    542 			p.coverVars = declareCoverVars(p.ImportPath, coverFiles...)
    543 		}
    544 	}
    545 
    546 	// Prepare build + run + print actions for all packages being tested.
    547 	for _, p := range pkgs {
    548 		buildTest, runTest, printTest, err := b.test(p)
    549 		if err != nil {
    550 			str := err.Error()
    551 			if strings.HasPrefix(str, "\n") {
    552 				str = str[1:]
    553 			}
    554 			failed := fmt.Sprintf("FAIL\t%s [setup failed]\n", p.ImportPath)
    555 
    556 			if p.ImportPath != "" {
    557 				errorf("# %s\n%s\n%s", p.ImportPath, str, failed)
    558 			} else {
    559 				errorf("%s\n%s", str, failed)
    560 			}
    561 			continue
    562 		}
    563 		builds = append(builds, buildTest)
    564 		runs = append(runs, runTest)
    565 		prints = append(prints, printTest)
    566 	}
    567 
    568 	// Ultimately the goal is to print the output.
    569 	root := &action{deps: prints}
    570 
    571 	// Force the printing of results to happen in order,
    572 	// one at a time.
    573 	for i, a := range prints {
    574 		if i > 0 {
    575 			a.deps = append(a.deps, prints[i-1])
    576 		}
    577 	}
    578 
    579 	// Force benchmarks to run in serial.
    580 	if !testC && testBench {
    581 		// The first run must wait for all builds.
    582 		// Later runs must wait for the previous run's print.
    583 		for i, run := range runs {
    584 			if i == 0 {
    585 				run.deps = append(run.deps, builds...)
    586 			} else {
    587 				run.deps = append(run.deps, prints[i-1])
    588 			}
    589 		}
    590 	}
    591 
    592 	// If we are building any out-of-date packages other
    593 	// than those under test, warn.
    594 	okBuild := map[*Package]bool{}
    595 	for _, p := range pkgs {
    596 		okBuild[p] = true
    597 	}
    598 	warned := false
    599 	for _, a := range actionList(root) {
    600 		if a.p == nil || okBuild[a.p] {
    601 			continue
    602 		}
    603 		okBuild[a.p] = true // warn at most once
    604 
    605 		// Don't warn about packages being rebuilt because of
    606 		// things like coverage analysis.
    607 		for _, p1 := range a.p.imports {
    608 			if p1.fake {
    609 				a.p.fake = true
    610 			}
    611 		}
    612 
    613 		if a.f != nil && !okBuild[a.p] && !a.p.fake && !a.p.local {
    614 			if !warned {
    615 				fmt.Fprintf(os.Stderr, "warning: building out-of-date packages:\n")
    616 				warned = true
    617 			}
    618 			fmt.Fprintf(os.Stderr, "\t%s\n", a.p.ImportPath)
    619 		}
    620 	}
    621 	if warned {
    622 		args := strings.Join(pkgArgs, " ")
    623 		if args != "" {
    624 			args = " " + args
    625 		}
    626 		extraOpts := ""
    627 		if buildRace {
    628 			extraOpts = "-race "
    629 		}
    630 		if buildMSan {
    631 			extraOpts = "-msan "
    632 		}
    633 		fmt.Fprintf(os.Stderr, "installing these packages with 'go test %s-i%s' will speed future tests.\n\n", extraOpts, args)
    634 	}
    635 
    636 	b.do(root)
    637 }
    638 
    639 func contains(x []string, s string) bool {
    640 	for _, t := range x {
    641 		if t == s {
    642 			return true
    643 		}
    644 	}
    645 	return false
    646 }
    647 
    648 var windowsBadWords = []string{
    649 	"install",
    650 	"patch",
    651 	"setup",
    652 	"update",
    653 }
    654 
    655 func (b *builder) test(p *Package) (buildAction, runAction, printAction *action, err error) {
    656 	if len(p.TestGoFiles)+len(p.XTestGoFiles) == 0 {
    657 		build := b.action(modeBuild, modeBuild, p)
    658 		run := &action{p: p, deps: []*action{build}}
    659 		print := &action{f: (*builder).notest, p: p, deps: []*action{run}}
    660 		return build, run, print, nil
    661 	}
    662 
    663 	// Build Package structs describing:
    664 	//	ptest - package + test files
    665 	//	pxtest - package of external test files
    666 	//	pmain - pkg.test binary
    667 	var ptest, pxtest, pmain *Package
    668 
    669 	var imports, ximports []*Package
    670 	var stk importStack
    671 	stk.push(p.ImportPath + " (test)")
    672 	for i, path := range p.TestImports {
    673 		p1 := loadImport(path, p.Dir, p, &stk, p.build.TestImportPos[path], useVendor)
    674 		if p1.Error != nil {
    675 			return nil, nil, nil, p1.Error
    676 		}
    677 		if len(p1.DepsErrors) > 0 {
    678 			err := p1.DepsErrors[0]
    679 			err.Pos = "" // show full import stack
    680 			return nil, nil, nil, err
    681 		}
    682 		if contains(p1.Deps, p.ImportPath) || p1.ImportPath == p.ImportPath {
    683 			// Same error that loadPackage returns (via reusePackage) in pkg.go.
    684 			// Can't change that code, because that code is only for loading the
    685 			// non-test copy of a package.
    686 			err := &PackageError{
    687 				ImportStack:   testImportStack(stk[0], p1, p.ImportPath),
    688 				Err:           "import cycle not allowed in test",
    689 				isImportCycle: true,
    690 			}
    691 			return nil, nil, nil, err
    692 		}
    693 		p.TestImports[i] = p1.ImportPath
    694 		imports = append(imports, p1)
    695 	}
    696 	stk.pop()
    697 	stk.push(p.ImportPath + "_test")
    698 	pxtestNeedsPtest := false
    699 	for i, path := range p.XTestImports {
    700 		p1 := loadImport(path, p.Dir, p, &stk, p.build.XTestImportPos[path], useVendor)
    701 		if p1.Error != nil {
    702 			return nil, nil, nil, p1.Error
    703 		}
    704 		if len(p1.DepsErrors) > 0 {
    705 			err := p1.DepsErrors[0]
    706 			err.Pos = "" // show full import stack
    707 			return nil, nil, nil, err
    708 		}
    709 		if p1.ImportPath == p.ImportPath {
    710 			pxtestNeedsPtest = true
    711 		} else {
    712 			ximports = append(ximports, p1)
    713 		}
    714 		p.XTestImports[i] = p1.ImportPath
    715 	}
    716 	stk.pop()
    717 
    718 	// Use last element of import path, not package name.
    719 	// They differ when package name is "main".
    720 	// But if the import path is "command-line-arguments",
    721 	// like it is during 'go run', use the package name.
    722 	var elem string
    723 	if p.ImportPath == "command-line-arguments" {
    724 		elem = p.Name
    725 	} else {
    726 		_, elem = path.Split(p.ImportPath)
    727 	}
    728 	testBinary := elem + ".test"
    729 
    730 	// The ptest package needs to be importable under the
    731 	// same import path that p has, but we cannot put it in
    732 	// the usual place in the temporary tree, because then
    733 	// other tests will see it as the real package.
    734 	// Instead we make a _test directory under the import path
    735 	// and then repeat the import path there. We tell the
    736 	// compiler and linker to look in that _test directory first.
    737 	//
    738 	// That is, if the package under test is unicode/utf8,
    739 	// then the normal place to write the package archive is
    740 	// $WORK/unicode/utf8.a, but we write the test package archive to
    741 	// $WORK/unicode/utf8/_test/unicode/utf8.a.
    742 	// We write the external test package archive to
    743 	// $WORK/unicode/utf8/_test/unicode/utf8_test.a.
    744 	testDir := filepath.Join(b.work, filepath.FromSlash(p.ImportPath+"/_test"))
    745 	ptestObj := buildToolchain.pkgpath(testDir, p)
    746 
    747 	// Create the directory for the .a files.
    748 	ptestDir, _ := filepath.Split(ptestObj)
    749 	if err := b.mkdir(ptestDir); err != nil {
    750 		return nil, nil, nil, err
    751 	}
    752 
    753 	// Should we apply coverage analysis locally,
    754 	// only for this package and only for this test?
    755 	// Yes, if -cover is on but -coverpkg has not specified
    756 	// a list of packages for global coverage.
    757 	localCover := testCover && testCoverPaths == nil
    758 
    759 	// Test package.
    760 	if len(p.TestGoFiles) > 0 || localCover || p.Name == "main" {
    761 		ptest = new(Package)
    762 		*ptest = *p
    763 		ptest.GoFiles = nil
    764 		ptest.GoFiles = append(ptest.GoFiles, p.GoFiles...)
    765 		ptest.GoFiles = append(ptest.GoFiles, p.TestGoFiles...)
    766 		ptest.target = ""
    767 		ptest.Imports = stringList(p.Imports, p.TestImports)
    768 		ptest.imports = append(append([]*Package{}, p.imports...), imports...)
    769 		ptest.pkgdir = testDir
    770 		ptest.fake = true
    771 		ptest.forceLibrary = true
    772 		ptest.Stale = true
    773 		ptest.StaleReason = "rebuild for test"
    774 		ptest.build = new(build.Package)
    775 		*ptest.build = *p.build
    776 		m := map[string][]token.Position{}
    777 		for k, v := range p.build.ImportPos {
    778 			m[k] = append(m[k], v...)
    779 		}
    780 		for k, v := range p.build.TestImportPos {
    781 			m[k] = append(m[k], v...)
    782 		}
    783 		ptest.build.ImportPos = m
    784 
    785 		if localCover {
    786 			ptest.coverMode = testCoverMode
    787 			var coverFiles []string
    788 			coverFiles = append(coverFiles, ptest.GoFiles...)
    789 			coverFiles = append(coverFiles, ptest.CgoFiles...)
    790 			ptest.coverVars = declareCoverVars(ptest.ImportPath, coverFiles...)
    791 		}
    792 	} else {
    793 		ptest = p
    794 	}
    795 
    796 	// External test package.
    797 	if len(p.XTestGoFiles) > 0 {
    798 		pxtest = &Package{
    799 			Name:        p.Name + "_test",
    800 			ImportPath:  p.ImportPath + "_test",
    801 			localPrefix: p.localPrefix,
    802 			Root:        p.Root,
    803 			Dir:         p.Dir,
    804 			GoFiles:     p.XTestGoFiles,
    805 			Imports:     p.XTestImports,
    806 			build: &build.Package{
    807 				ImportPos: p.build.XTestImportPos,
    808 			},
    809 			imports:  ximports,
    810 			pkgdir:   testDir,
    811 			fake:     true,
    812 			external: true,
    813 			Stale:    true,
    814 		}
    815 		if pxtestNeedsPtest {
    816 			pxtest.imports = append(pxtest.imports, ptest)
    817 		}
    818 	}
    819 
    820 	// Action for building pkg.test.
    821 	pmain = &Package{
    822 		Name:       "main",
    823 		Dir:        testDir,
    824 		GoFiles:    []string{"_testmain.go"},
    825 		ImportPath: "testmain",
    826 		Root:       p.Root,
    827 		build:      &build.Package{Name: "main"},
    828 		pkgdir:     testDir,
    829 		fake:       true,
    830 		Stale:      true,
    831 		omitDWARF:  !testC && !testNeedBinary,
    832 	}
    833 
    834 	// The generated main also imports testing, regexp, and os.
    835 	stk.push("testmain")
    836 	for dep := range testMainDeps {
    837 		if dep == ptest.ImportPath {
    838 			pmain.imports = append(pmain.imports, ptest)
    839 		} else {
    840 			p1 := loadImport(dep, "", nil, &stk, nil, 0)
    841 			if p1.Error != nil {
    842 				return nil, nil, nil, p1.Error
    843 			}
    844 			pmain.imports = append(pmain.imports, p1)
    845 		}
    846 	}
    847 
    848 	if testCoverPkgs != nil {
    849 		// Add imports, but avoid duplicates.
    850 		seen := map[*Package]bool{p: true, ptest: true}
    851 		for _, p1 := range pmain.imports {
    852 			seen[p1] = true
    853 		}
    854 		for _, p1 := range testCoverPkgs {
    855 			if !seen[p1] {
    856 				seen[p1] = true
    857 				pmain.imports = append(pmain.imports, p1)
    858 			}
    859 		}
    860 	}
    861 
    862 	// Do initial scan for metadata needed for writing _testmain.go
    863 	// Use that metadata to update the list of imports for package main.
    864 	// The list of imports is used by recompileForTest and by the loop
    865 	// afterward that gathers t.Cover information.
    866 	t, err := loadTestFuncs(ptest)
    867 	if err != nil {
    868 		return nil, nil, nil, err
    869 	}
    870 	if len(ptest.GoFiles)+len(ptest.CgoFiles) > 0 {
    871 		pmain.imports = append(pmain.imports, ptest)
    872 		t.ImportTest = true
    873 	}
    874 	if pxtest != nil {
    875 		pmain.imports = append(pmain.imports, pxtest)
    876 		t.ImportXtest = true
    877 	}
    878 
    879 	if ptest != p && localCover {
    880 		// We have made modifications to the package p being tested
    881 		// and are rebuilding p (as ptest), writing it to the testDir tree.
    882 		// Arrange to rebuild, writing to that same tree, all packages q
    883 		// such that the test depends on q, and q depends on p.
    884 		// This makes sure that q sees the modifications to p.
    885 		// Strictly speaking, the rebuild is only necessary if the
    886 		// modifications to p change its export metadata, but
    887 		// determining that is a bit tricky, so we rebuild always.
    888 		//
    889 		// This will cause extra compilation, so for now we only do it
    890 		// when testCover is set. The conditions are more general, though,
    891 		// and we may find that we need to do it always in the future.
    892 		recompileForTest(pmain, p, ptest, testDir)
    893 	}
    894 
    895 	if buildContext.GOOS == "darwin" {
    896 		if buildContext.GOARCH == "arm" || buildContext.GOARCH == "arm64" {
    897 			t.IsIOS = true
    898 			t.NeedOS = true
    899 		}
    900 	}
    901 	if t.TestMain == nil {
    902 		t.NeedOS = true
    903 	}
    904 
    905 	for _, cp := range pmain.imports {
    906 		if len(cp.coverVars) > 0 {
    907 			t.Cover = append(t.Cover, coverInfo{cp, cp.coverVars})
    908 		}
    909 	}
    910 
    911 	if !buildN {
    912 		// writeTestmain writes _testmain.go. This must happen after recompileForTest,
    913 		// because recompileForTest modifies XXX.
    914 		if err := writeTestmain(filepath.Join(testDir, "_testmain.go"), t); err != nil {
    915 			return nil, nil, nil, err
    916 		}
    917 	}
    918 
    919 	computeStale(pmain)
    920 
    921 	if ptest != p {
    922 		a := b.action(modeBuild, modeBuild, ptest)
    923 		a.objdir = testDir + string(filepath.Separator) + "_obj_test" + string(filepath.Separator)
    924 		a.objpkg = ptestObj
    925 		a.target = ptestObj
    926 		a.link = false
    927 	}
    928 
    929 	if pxtest != nil {
    930 		a := b.action(modeBuild, modeBuild, pxtest)
    931 		a.objdir = testDir + string(filepath.Separator) + "_obj_xtest" + string(filepath.Separator)
    932 		a.objpkg = buildToolchain.pkgpath(testDir, pxtest)
    933 		a.target = a.objpkg
    934 	}
    935 
    936 	a := b.action(modeBuild, modeBuild, pmain)
    937 	a.objdir = testDir + string(filepath.Separator)
    938 	a.objpkg = filepath.Join(testDir, "main.a")
    939 	a.target = filepath.Join(testDir, testBinary) + exeSuffix
    940 	if goos == "windows" {
    941 		// There are many reserved words on Windows that,
    942 		// if used in the name of an executable, cause Windows
    943 		// to try to ask for extra permissions.
    944 		// The word list includes setup, install, update, and patch,
    945 		// but it does not appear to be defined anywhere.
    946 		// We have run into this trying to run the
    947 		// go.codereview/patch tests.
    948 		// For package names containing those words, use test.test.exe
    949 		// instead of pkgname.test.exe.
    950 		// Note that this file name is only used in the Go command's
    951 		// temporary directory. If the -c or other flags are
    952 		// given, the code below will still use pkgname.test.exe.
    953 		// There are two user-visible effects of this change.
    954 		// First, you can actually run 'go test' in directories that
    955 		// have names that Windows thinks are installer-like,
    956 		// without getting a dialog box asking for more permissions.
    957 		// Second, in the Windows process listing during go test,
    958 		// the test shows up as test.test.exe, not pkgname.test.exe.
    959 		// That second one is a drawback, but it seems a small
    960 		// price to pay for the test running at all.
    961 		// If maintaining the list of bad words is too onerous,
    962 		// we could just do this always on Windows.
    963 		for _, bad := range windowsBadWords {
    964 			if strings.Contains(testBinary, bad) {
    965 				a.target = filepath.Join(testDir, "test.test") + exeSuffix
    966 				break
    967 			}
    968 		}
    969 	}
    970 	buildAction = a
    971 
    972 	if testC || testNeedBinary {
    973 		// -c or profiling flag: create action to copy binary to ./test.out.
    974 		target := filepath.Join(cwd, testBinary+exeSuffix)
    975 		if testO != "" {
    976 			target = testO
    977 			if !filepath.IsAbs(target) {
    978 				target = filepath.Join(cwd, target)
    979 			}
    980 		}
    981 		buildAction = &action{
    982 			f:      (*builder).install,
    983 			deps:   []*action{buildAction},
    984 			p:      pmain,
    985 			target: target,
    986 		}
    987 		runAction = buildAction // make sure runAction != nil even if not running test
    988 	}
    989 	if testC {
    990 		printAction = &action{p: p, deps: []*action{runAction}} // nop
    991 	} else {
    992 		// run test
    993 		runAction = &action{
    994 			f:          (*builder).runTest,
    995 			deps:       []*action{buildAction},
    996 			p:          p,
    997 			ignoreFail: true,
    998 		}
    999 		cleanAction := &action{
   1000 			f:    (*builder).cleanTest,
   1001 			deps: []*action{runAction},
   1002 			p:    p,
   1003 		}
   1004 		printAction = &action{
   1005 			f:    (*builder).printTest,
   1006 			deps: []*action{cleanAction},
   1007 			p:    p,
   1008 		}
   1009 	}
   1010 
   1011 	return buildAction, runAction, printAction, nil
   1012 }
   1013 
   1014 func testImportStack(top string, p *Package, target string) []string {
   1015 	stk := []string{top, p.ImportPath}
   1016 Search:
   1017 	for p.ImportPath != target {
   1018 		for _, p1 := range p.imports {
   1019 			if p1.ImportPath == target || contains(p1.Deps, target) {
   1020 				stk = append(stk, p1.ImportPath)
   1021 				p = p1
   1022 				continue Search
   1023 			}
   1024 		}
   1025 		// Can't happen, but in case it does...
   1026 		stk = append(stk, "<lost path to cycle>")
   1027 		break
   1028 	}
   1029 	return stk
   1030 }
   1031 
   1032 func recompileForTest(pmain, preal, ptest *Package, testDir string) {
   1033 	// The "test copy" of preal is ptest.
   1034 	// For each package that depends on preal, make a "test copy"
   1035 	// that depends on ptest. And so on, up the dependency tree.
   1036 	testCopy := map[*Package]*Package{preal: ptest}
   1037 	for _, p := range packageList([]*Package{pmain}) {
   1038 		// Copy on write.
   1039 		didSplit := false
   1040 		split := func() {
   1041 			if didSplit {
   1042 				return
   1043 			}
   1044 			didSplit = true
   1045 			if p.pkgdir != testDir {
   1046 				p1 := new(Package)
   1047 				testCopy[p] = p1
   1048 				*p1 = *p
   1049 				p1.imports = make([]*Package, len(p.imports))
   1050 				copy(p1.imports, p.imports)
   1051 				p = p1
   1052 				p.pkgdir = testDir
   1053 				p.target = ""
   1054 				p.fake = true
   1055 				p.Stale = true
   1056 				p.StaleReason = "depends on package being tested"
   1057 			}
   1058 		}
   1059 
   1060 		// Update p.deps and p.imports to use at test copies.
   1061 		for i, dep := range p.deps {
   1062 			if p1 := testCopy[dep]; p1 != nil && p1 != dep {
   1063 				split()
   1064 				p.deps[i] = p1
   1065 			}
   1066 		}
   1067 		for i, imp := range p.imports {
   1068 			if p1 := testCopy[imp]; p1 != nil && p1 != imp {
   1069 				split()
   1070 				p.imports[i] = p1
   1071 			}
   1072 		}
   1073 	}
   1074 }
   1075 
   1076 var coverIndex = 0
   1077 
   1078 // isTestFile reports whether the source file is a set of tests and should therefore
   1079 // be excluded from coverage analysis.
   1080 func isTestFile(file string) bool {
   1081 	// We don't cover tests, only the code they test.
   1082 	return strings.HasSuffix(file, "_test.go")
   1083 }
   1084 
   1085 // declareCoverVars attaches the required cover variables names
   1086 // to the files, to be used when annotating the files.
   1087 func declareCoverVars(importPath string, files ...string) map[string]*CoverVar {
   1088 	coverVars := make(map[string]*CoverVar)
   1089 	for _, file := range files {
   1090 		if isTestFile(file) {
   1091 			continue
   1092 		}
   1093 		coverVars[file] = &CoverVar{
   1094 			File: filepath.Join(importPath, file),
   1095 			Var:  fmt.Sprintf("GoCover_%d", coverIndex),
   1096 		}
   1097 		coverIndex++
   1098 	}
   1099 	return coverVars
   1100 }
   1101 
   1102 var noTestsToRun = []byte("\ntesting: warning: no tests to run\n")
   1103 
   1104 // runTest is the action for running a test binary.
   1105 func (b *builder) runTest(a *action) error {
   1106 	args := stringList(findExecCmd(), a.deps[0].target, testArgs)
   1107 	a.testOutput = new(bytes.Buffer)
   1108 
   1109 	if buildN || buildX {
   1110 		b.showcmd("", "%s", strings.Join(args, " "))
   1111 		if buildN {
   1112 			return nil
   1113 		}
   1114 	}
   1115 
   1116 	if a.failed {
   1117 		// We were unable to build the binary.
   1118 		a.failed = false
   1119 		fmt.Fprintf(a.testOutput, "FAIL\t%s [build failed]\n", a.p.ImportPath)
   1120 		setExitStatus(1)
   1121 		return nil
   1122 	}
   1123 
   1124 	cmd := exec.Command(args[0], args[1:]...)
   1125 	cmd.Dir = a.p.Dir
   1126 	cmd.Env = envForDir(cmd.Dir, origEnv)
   1127 	var buf bytes.Buffer
   1128 	if testStreamOutput {
   1129 		cmd.Stdout = os.Stdout
   1130 		cmd.Stderr = os.Stderr
   1131 	} else {
   1132 		cmd.Stdout = &buf
   1133 		cmd.Stderr = &buf
   1134 	}
   1135 
   1136 	// If there are any local SWIG dependencies, we want to load
   1137 	// the shared library from the build directory.
   1138 	if a.p.usesSwig() {
   1139 		env := cmd.Env
   1140 		found := false
   1141 		prefix := "LD_LIBRARY_PATH="
   1142 		for i, v := range env {
   1143 			if strings.HasPrefix(v, prefix) {
   1144 				env[i] = v + ":."
   1145 				found = true
   1146 				break
   1147 			}
   1148 		}
   1149 		if !found {
   1150 			env = append(env, "LD_LIBRARY_PATH=.")
   1151 		}
   1152 		cmd.Env = env
   1153 	}
   1154 
   1155 	t0 := time.Now()
   1156 	err := cmd.Start()
   1157 
   1158 	// This is a last-ditch deadline to detect and
   1159 	// stop wedged test binaries, to keep the builders
   1160 	// running.
   1161 	if err == nil {
   1162 		tick := time.NewTimer(testKillTimeout)
   1163 		startSigHandlers()
   1164 		done := make(chan error)
   1165 		go func() {
   1166 			done <- cmd.Wait()
   1167 		}()
   1168 	Outer:
   1169 		select {
   1170 		case err = <-done:
   1171 			// ok
   1172 		case <-tick.C:
   1173 			if signalTrace != nil {
   1174 				// Send a quit signal in the hope that the program will print
   1175 				// a stack trace and exit. Give it five seconds before resorting
   1176 				// to Kill.
   1177 				cmd.Process.Signal(signalTrace)
   1178 				select {
   1179 				case err = <-done:
   1180 					fmt.Fprintf(&buf, "*** Test killed with %v: ran too long (%v).\n", signalTrace, testKillTimeout)
   1181 					break Outer
   1182 				case <-time.After(5 * time.Second):
   1183 				}
   1184 			}
   1185 			cmd.Process.Kill()
   1186 			err = <-done
   1187 			fmt.Fprintf(&buf, "*** Test killed: ran too long (%v).\n", testKillTimeout)
   1188 		}
   1189 		tick.Stop()
   1190 	}
   1191 	out := buf.Bytes()
   1192 	t := fmt.Sprintf("%.3fs", time.Since(t0).Seconds())
   1193 	if err == nil {
   1194 		norun := ""
   1195 		if testShowPass {
   1196 			a.testOutput.Write(out)
   1197 		}
   1198 		if bytes.HasPrefix(out, noTestsToRun[1:]) || bytes.Contains(out, noTestsToRun) {
   1199 			norun = " [no tests to run]"
   1200 		}
   1201 		fmt.Fprintf(a.testOutput, "ok  \t%s\t%s%s%s\n", a.p.ImportPath, t, coveragePercentage(out), norun)
   1202 		return nil
   1203 	}
   1204 
   1205 	setExitStatus(1)
   1206 	if len(out) > 0 {
   1207 		a.testOutput.Write(out)
   1208 		// assume printing the test binary's exit status is superfluous
   1209 	} else {
   1210 		fmt.Fprintf(a.testOutput, "%s\n", err)
   1211 	}
   1212 	fmt.Fprintf(a.testOutput, "FAIL\t%s\t%s\n", a.p.ImportPath, t)
   1213 
   1214 	return nil
   1215 }
   1216 
   1217 // coveragePercentage returns the coverage results (if enabled) for the
   1218 // test. It uncovers the data by scanning the output from the test run.
   1219 func coveragePercentage(out []byte) string {
   1220 	if !testCover {
   1221 		return ""
   1222 	}
   1223 	// The string looks like
   1224 	//	test coverage for encoding/binary: 79.9% of statements
   1225 	// Extract the piece from the percentage to the end of the line.
   1226 	re := regexp.MustCompile(`coverage: (.*)\n`)
   1227 	matches := re.FindSubmatch(out)
   1228 	if matches == nil {
   1229 		// Probably running "go test -cover" not "go test -cover fmt".
   1230 		// The coverage output will appear in the output directly.
   1231 		return ""
   1232 	}
   1233 	return fmt.Sprintf("\tcoverage: %s", matches[1])
   1234 }
   1235 
   1236 // cleanTest is the action for cleaning up after a test.
   1237 func (b *builder) cleanTest(a *action) error {
   1238 	if buildWork {
   1239 		return nil
   1240 	}
   1241 	run := a.deps[0]
   1242 	testDir := filepath.Join(b.work, filepath.FromSlash(run.p.ImportPath+"/_test"))
   1243 	os.RemoveAll(testDir)
   1244 	return nil
   1245 }
   1246 
   1247 // printTest is the action for printing a test result.
   1248 func (b *builder) printTest(a *action) error {
   1249 	clean := a.deps[0]
   1250 	run := clean.deps[0]
   1251 	os.Stdout.Write(run.testOutput.Bytes())
   1252 	run.testOutput = nil
   1253 	return nil
   1254 }
   1255 
   1256 // notest is the action for testing a package with no test files.
   1257 func (b *builder) notest(a *action) error {
   1258 	fmt.Printf("?   \t%s\t[no test files]\n", a.p.ImportPath)
   1259 	return nil
   1260 }
   1261 
   1262 // isTestFunc tells whether fn has the type of a testing function. arg
   1263 // specifies the parameter type we look for: B, M or T.
   1264 func isTestFunc(fn *ast.FuncDecl, arg string) bool {
   1265 	if fn.Type.Results != nil && len(fn.Type.Results.List) > 0 ||
   1266 		fn.Type.Params.List == nil ||
   1267 		len(fn.Type.Params.List) != 1 ||
   1268 		len(fn.Type.Params.List[0].Names) > 1 {
   1269 		return false
   1270 	}
   1271 	ptr, ok := fn.Type.Params.List[0].Type.(*ast.StarExpr)
   1272 	if !ok {
   1273 		return false
   1274 	}
   1275 	// We can't easily check that the type is *testing.M
   1276 	// because we don't know how testing has been imported,
   1277 	// but at least check that it's *M or *something.M.
   1278 	// Same applies for B and T.
   1279 	if name, ok := ptr.X.(*ast.Ident); ok && name.Name == arg {
   1280 		return true
   1281 	}
   1282 	if sel, ok := ptr.X.(*ast.SelectorExpr); ok && sel.Sel.Name == arg {
   1283 		return true
   1284 	}
   1285 	return false
   1286 }
   1287 
   1288 // isTest tells whether name looks like a test (or benchmark, according to prefix).
   1289 // It is a Test (say) if there is a character after Test that is not a lower-case letter.
   1290 // We don't want TesticularCancer.
   1291 func isTest(name, prefix string) bool {
   1292 	if !strings.HasPrefix(name, prefix) {
   1293 		return false
   1294 	}
   1295 	if len(name) == len(prefix) { // "Test" is ok
   1296 		return true
   1297 	}
   1298 	rune, _ := utf8.DecodeRuneInString(name[len(prefix):])
   1299 	return !unicode.IsLower(rune)
   1300 }
   1301 
   1302 type coverInfo struct {
   1303 	Package *Package
   1304 	Vars    map[string]*CoverVar
   1305 }
   1306 
   1307 // loadTestFuncs returns the testFuncs describing the tests that will be run.
   1308 func loadTestFuncs(ptest *Package) (*testFuncs, error) {
   1309 	t := &testFuncs{
   1310 		Package: ptest,
   1311 	}
   1312 	for _, file := range ptest.TestGoFiles {
   1313 		if err := t.load(filepath.Join(ptest.Dir, file), "_test", &t.ImportTest, &t.NeedTest); err != nil {
   1314 			return nil, err
   1315 		}
   1316 	}
   1317 	for _, file := range ptest.XTestGoFiles {
   1318 		if err := t.load(filepath.Join(ptest.Dir, file), "_xtest", &t.ImportXtest, &t.NeedXtest); err != nil {
   1319 			return nil, err
   1320 		}
   1321 	}
   1322 	return t, nil
   1323 }
   1324 
   1325 // writeTestmain writes the _testmain.go file for t to the file named out.
   1326 func writeTestmain(out string, t *testFuncs) error {
   1327 	f, err := os.Create(out)
   1328 	if err != nil {
   1329 		return err
   1330 	}
   1331 	defer f.Close()
   1332 
   1333 	if err := testmainTmpl.Execute(f, t); err != nil {
   1334 		return err
   1335 	}
   1336 
   1337 	return nil
   1338 }
   1339 
   1340 type testFuncs struct {
   1341 	Tests       []testFunc
   1342 	Benchmarks  []testFunc
   1343 	Examples    []testFunc
   1344 	TestMain    *testFunc
   1345 	Package     *Package
   1346 	ImportTest  bool
   1347 	NeedTest    bool
   1348 	ImportXtest bool
   1349 	NeedXtest   bool
   1350 	NeedOS      bool
   1351 	IsIOS       bool
   1352 	Cover       []coverInfo
   1353 }
   1354 
   1355 func (t *testFuncs) CoverMode() string {
   1356 	return testCoverMode
   1357 }
   1358 
   1359 func (t *testFuncs) CoverEnabled() bool {
   1360 	return testCover
   1361 }
   1362 
   1363 // Covered returns a string describing which packages are being tested for coverage.
   1364 // If the covered package is the same as the tested package, it returns the empty string.
   1365 // Otherwise it is a comma-separated human-readable list of packages beginning with
   1366 // " in", ready for use in the coverage message.
   1367 func (t *testFuncs) Covered() string {
   1368 	if testCoverPaths == nil {
   1369 		return ""
   1370 	}
   1371 	return " in " + strings.Join(testCoverPaths, ", ")
   1372 }
   1373 
   1374 // Tested returns the name of the package being tested.
   1375 func (t *testFuncs) Tested() string {
   1376 	return t.Package.Name
   1377 }
   1378 
   1379 type testFunc struct {
   1380 	Package   string // imported package name (_test or _xtest)
   1381 	Name      string // function name
   1382 	Output    string // output, for examples
   1383 	Unordered bool   // output is allowed to be unordered.
   1384 }
   1385 
   1386 var testFileSet = token.NewFileSet()
   1387 
   1388 func (t *testFuncs) load(filename, pkg string, doImport, seen *bool) error {
   1389 	f, err := parser.ParseFile(testFileSet, filename, nil, parser.ParseComments)
   1390 	if err != nil {
   1391 		return expandScanner(err)
   1392 	}
   1393 	for _, d := range f.Decls {
   1394 		n, ok := d.(*ast.FuncDecl)
   1395 		if !ok {
   1396 			continue
   1397 		}
   1398 		if n.Recv != nil {
   1399 			continue
   1400 		}
   1401 		name := n.Name.String()
   1402 		switch {
   1403 		case name == "TestMain" && isTestFunc(n, "M"):
   1404 			if t.TestMain != nil {
   1405 				return errors.New("multiple definitions of TestMain")
   1406 			}
   1407 			t.TestMain = &testFunc{pkg, name, "", false}
   1408 			*doImport, *seen = true, true
   1409 		case isTest(name, "Test"):
   1410 			err := checkTestFunc(n, "T")
   1411 			if err != nil {
   1412 				return err
   1413 			}
   1414 			t.Tests = append(t.Tests, testFunc{pkg, name, "", false})
   1415 			*doImport, *seen = true, true
   1416 		case isTest(name, "Benchmark"):
   1417 			err := checkTestFunc(n, "B")
   1418 			if err != nil {
   1419 				return err
   1420 			}
   1421 			t.Benchmarks = append(t.Benchmarks, testFunc{pkg, name, "", false})
   1422 			*doImport, *seen = true, true
   1423 		}
   1424 	}
   1425 	ex := doc.Examples(f)
   1426 	sort.Slice(ex, func(i, j int) bool { return ex[i].Order < ex[j].Order })
   1427 	for _, e := range ex {
   1428 		*doImport = true // import test file whether executed or not
   1429 		if e.Output == "" && !e.EmptyOutput {
   1430 			// Don't run examples with no output.
   1431 			continue
   1432 		}
   1433 		t.Examples = append(t.Examples, testFunc{pkg, "Example" + e.Name, e.Output, e.Unordered})
   1434 		*seen = true
   1435 	}
   1436 	return nil
   1437 }
   1438 
   1439 func checkTestFunc(fn *ast.FuncDecl, arg string) error {
   1440 	if !isTestFunc(fn, arg) {
   1441 		name := fn.Name.String()
   1442 		pos := testFileSet.Position(fn.Pos())
   1443 		return fmt.Errorf("%s: wrong signature for %s, must be: func %s(%s *testing.%s)", pos, name, name, strings.ToLower(arg), arg)
   1444 	}
   1445 	return nil
   1446 }
   1447 
   1448 var testmainTmpl = template.Must(template.New("main").Parse(`
   1449 package main
   1450 
   1451 import (
   1452 {{if .NeedOS}}
   1453 	"os"
   1454 {{end}}
   1455 	"testing"
   1456 	"testing/internal/testdeps"
   1457 
   1458 {{if .ImportTest}}
   1459 	{{if .NeedTest}}_test{{else}}_{{end}} {{.Package.ImportPath | printf "%q"}}
   1460 {{end}}
   1461 {{if .ImportXtest}}
   1462 	{{if .NeedXtest}}_xtest{{else}}_{{end}} {{.Package.ImportPath | printf "%s_test" | printf "%q"}}
   1463 {{end}}
   1464 {{range $i, $p := .Cover}}
   1465 	_cover{{$i}} {{$p.Package.ImportPath | printf "%q"}}
   1466 {{end}}
   1467 
   1468 {{if .IsIOS}}
   1469 	"os/signal"
   1470 	_ "runtime/cgo"
   1471 	"syscall"
   1472 {{end}}
   1473 )
   1474 
   1475 var tests = []testing.InternalTest{
   1476 {{range .Tests}}
   1477 	{"{{.Name}}", {{.Package}}.{{.Name}}},
   1478 {{end}}
   1479 }
   1480 
   1481 var benchmarks = []testing.InternalBenchmark{
   1482 {{range .Benchmarks}}
   1483 	{"{{.Name}}", {{.Package}}.{{.Name}}},
   1484 {{end}}
   1485 }
   1486 
   1487 var examples = []testing.InternalExample{
   1488 {{range .Examples}}
   1489 	{"{{.Name}}", {{.Package}}.{{.Name}}, {{.Output | printf "%q"}}, {{.Unordered}}},
   1490 {{end}}
   1491 }
   1492 
   1493 {{if .CoverEnabled}}
   1494 
   1495 // Only updated by init functions, so no need for atomicity.
   1496 var (
   1497 	coverCounters = make(map[string][]uint32)
   1498 	coverBlocks = make(map[string][]testing.CoverBlock)
   1499 )
   1500 
   1501 func init() {
   1502 	{{range $i, $p := .Cover}}
   1503 	{{range $file, $cover := $p.Vars}}
   1504 	coverRegisterFile({{printf "%q" $cover.File}}, _cover{{$i}}.{{$cover.Var}}.Count[:], _cover{{$i}}.{{$cover.Var}}.Pos[:], _cover{{$i}}.{{$cover.Var}}.NumStmt[:])
   1505 	{{end}}
   1506 	{{end}}
   1507 }
   1508 
   1509 func coverRegisterFile(fileName string, counter []uint32, pos []uint32, numStmts []uint16) {
   1510 	if 3*len(counter) != len(pos) || len(counter) != len(numStmts) {
   1511 		panic("coverage: mismatched sizes")
   1512 	}
   1513 	if coverCounters[fileName] != nil {
   1514 		// Already registered.
   1515 		return
   1516 	}
   1517 	coverCounters[fileName] = counter
   1518 	block := make([]testing.CoverBlock, len(counter))
   1519 	for i := range counter {
   1520 		block[i] = testing.CoverBlock{
   1521 			Line0: pos[3*i+0],
   1522 			Col0: uint16(pos[3*i+2]),
   1523 			Line1: pos[3*i+1],
   1524 			Col1: uint16(pos[3*i+2]>>16),
   1525 			Stmts: numStmts[i],
   1526 		}
   1527 	}
   1528 	coverBlocks[fileName] = block
   1529 }
   1530 {{end}}
   1531 
   1532 func main() {
   1533 {{if .IsIOS}}
   1534 	// Send a SIGUSR2, which will be intercepted by LLDB to
   1535 	// tell the test harness that installation was successful.
   1536 	// See misc/ios/go_darwin_arm_exec.go.
   1537 	signal.Notify(make(chan os.Signal), syscall.SIGUSR2)
   1538 	syscall.Kill(0, syscall.SIGUSR2)
   1539 	signal.Reset(syscall.SIGUSR2)
   1540 
   1541 	// The first argument supplied to an iOS test is an offset
   1542 	// suffix for the current working directory.
   1543 	// Process it here, and remove it from os.Args.
   1544 	const hdr = "cwdSuffix="
   1545 	if len(os.Args) < 2 || len(os.Args[1]) <= len(hdr) || os.Args[1][:len(hdr)] != hdr {
   1546 		panic("iOS test not passed a working directory suffix")
   1547 	}
   1548 	suffix := os.Args[1][len(hdr):]
   1549 	dir, err := os.Getwd()
   1550 	if err != nil {
   1551 		panic(err)
   1552 	}
   1553 	if err := os.Chdir(dir + "/" + suffix); err != nil {
   1554 		panic(err)
   1555 	}
   1556 	os.Args = append([]string{os.Args[0]}, os.Args[2:]...)
   1557 {{end}}
   1558 
   1559 {{if .CoverEnabled}}
   1560 	testing.RegisterCover(testing.Cover{
   1561 		Mode: {{printf "%q" .CoverMode}},
   1562 		Counters: coverCounters,
   1563 		Blocks: coverBlocks,
   1564 		CoveredPackages: {{printf "%q" .Covered}},
   1565 	})
   1566 {{end}}
   1567 	m := testing.MainStart(testdeps.TestDeps{}, tests, benchmarks, examples)
   1568 {{with .TestMain}}
   1569 	{{.Package}}.{{.Name}}(m)
   1570 {{else}}
   1571 	os.Exit(m.Run())
   1572 {{end}}
   1573 }
   1574 
   1575 `))
   1576