github.com/dannin/go@v0.0.0-20161031215817-d35dfd405eaa/src/cmd/go/test.go (about)

     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  	"io"
    17  	"os"
    18  	"os/exec"
    19  	"path"
    20  	"path/filepath"
    21  	"regexp"
    22  	"runtime"
    23  	"sort"
    24  	"strings"
    25  	"text/template"
    26  	"time"
    27  	"unicode"
    28  	"unicode/utf8"
    29  )
    30  
    31  // Break init loop.
    32  func init() {
    33  	cmdTest.Run = runTest
    34  }
    35  
    36  const testUsage = "test [build/test flags] [packages] [build/test flags & test binary flags]"
    37  
    38  var cmdTest = &Command{
    39  	CustomFlags: true,
    40  	UsageLine:   testUsage,
    41  	Short:       "test packages",
    42  	Long: `
    43  'Go test' automates testing the packages named by the import paths.
    44  It prints a summary of the test results in the format:
    45  
    46  	ok   archive/tar   0.011s
    47  	FAIL archive/zip   0.022s
    48  	ok   compress/gzip 0.033s
    49  	...
    50  
    51  followed by detailed output for each failed package.
    52  
    53  'Go test' recompiles each package along with any files with names matching
    54  the file pattern "*_test.go".
    55  Files whose names begin with "_" (including "_test.go") or "." are ignored.
    56  These additional files can contain test functions, benchmark functions, and
    57  example functions.  See 'go help testfunc' for more.
    58  Each listed package causes the execution of a separate test binary.
    59  
    60  Test files that declare a package with the suffix "_test" will be compiled as a
    61  separate package, and then linked and run with the main test binary.
    62  
    63  The go tool will ignore a directory named "testdata", making it available
    64  to hold ancillary data needed by the tests.
    65  
    66  By default, go test needs no arguments.  It compiles and tests the package
    67  with source in the current directory, including tests, and runs the tests.
    68  
    69  The package is built in a temporary directory so it does not interfere with the
    70  non-test installation.
    71  
    72  ` + strings.TrimSpace(testFlag1) + ` See 'go help testflag' for details.
    73  
    74  For more about build flags, see 'go help build'.
    75  For more about specifying packages, see 'go help packages'.
    76  
    77  See also: go build, go vet.
    78  `,
    79  }
    80  
    81  const testFlag1 = `
    82  In addition to the build flags, the flags handled by 'go test' itself are:
    83  
    84  	-args
    85  	    Pass the remainder of the command line (everything after -args)
    86  	    to the test binary, uninterpreted and unchanged.
    87  	    Because this flag consumes the remainder of the command line,
    88  	    the package list (if present) must appear before this flag.
    89  
    90  	-c
    91  	    Compile the test binary to pkg.test but do not run it
    92  	    (where pkg is the last element of the package's import path).
    93  	    The file name can be changed with the -o flag.
    94  
    95  	-exec xprog
    96  	    Run the test binary using xprog. The behavior is the same as
    97  	    in 'go run'. See 'go help run' for details.
    98  
    99  	-i
   100  	    Install packages that are dependencies of the test.
   101  	    Do not run the test.
   102  
   103  	-o file
   104  	    Compile the test binary to the named file.
   105  	    The test still runs (unless -c or -i is specified).
   106  
   107  The test binary also accepts flags that control execution of the test; these
   108  flags are also accessible by 'go test'.
   109  `
   110  
   111  var helpTestflag = &Command{
   112  	UsageLine: "testflag",
   113  	Short:     "description of testing flags",
   114  	Long: `
   115  The 'go test' command takes both flags that apply to 'go test' itself
   116  and flags that apply to the resulting test binary.
   117  
   118  Several of the flags control profiling and write an execution profile
   119  suitable for "go tool pprof"; run "go tool pprof -h" for more
   120  information.  The --alloc_space, --alloc_objects, and --show_bytes
   121  options of pprof control how the information is presented.
   122  
   123  The following flags are recognized by the 'go test' command and
   124  control the execution of any test:
   125  
   126  	` + strings.TrimSpace(testFlag2) + `
   127  `,
   128  }
   129  
   130  const testFlag2 = `
   131  	-bench regexp
   132  	    Run (sub)benchmarks matching a regular expression.
   133  	    The given regular expression is split into smaller ones by
   134  	    top-level '/', where each must match the corresponding part of a
   135  	    benchmark's identifier.
   136  	    By default, no benchmarks run. To run all benchmarks,
   137  	    use '-bench .' or '-bench=.'.
   138  
   139  	-benchtime t
   140  	    Run enough iterations of each benchmark to take t, specified
   141  	    as a time.Duration (for example, -benchtime 1h30s).
   142  	    The default is 1 second (1s).
   143  
   144  	-count n
   145  	    Run each test and benchmark n times (default 1).
   146  	    If -cpu is set, run n times for each GOMAXPROCS value.
   147  	    Examples are always run once.
   148  
   149  	-cover
   150  	    Enable coverage analysis.
   151  
   152  	-covermode set,count,atomic
   153  	    Set the mode for coverage analysis for the package[s]
   154  	    being tested. The default is "set" unless -race is enabled,
   155  	    in which case it is "atomic".
   156  	    The values:
   157  		set: bool: does this statement run?
   158  		count: int: how many times does this statement run?
   159  		atomic: int: count, but correct in multithreaded tests;
   160  			significantly more expensive.
   161  	    Sets -cover.
   162  
   163  	-coverpkg pkg1,pkg2,pkg3
   164  	    Apply coverage analysis in each test to the given list of packages.
   165  	    The default is for each test to analyze only the package being tested.
   166  	    Packages are specified as import paths.
   167  	    Sets -cover.
   168  
   169  	-cpu 1,2,4
   170  	    Specify a list of GOMAXPROCS values for which the tests or
   171  	    benchmarks should be executed.  The default is the current value
   172  	    of GOMAXPROCS.
   173  
   174  	-parallel n
   175  	    Allow parallel execution of test functions that call t.Parallel.
   176  	    The value of this flag is the maximum number of tests to run
   177  	    simultaneously; by default, it is set to the value of GOMAXPROCS.
   178  	    Note that -parallel only applies within a single test binary.
   179  	    The 'go test' command may run tests for different packages
   180  	    in parallel as well, according to the setting of the -p flag
   181  	    (see 'go help build').
   182  
   183  	-run regexp
   184  	    Run only those tests and examples matching the regular expression.
   185  	    For tests the regular expression is split into smaller ones by
   186  	    top-level '/', where each must match the corresponding part of a
   187  	    test's identifier.
   188  
   189  	-short
   190  	    Tell long-running tests to shorten their run time.
   191  	    It is off by default but set during all.bash so that installing
   192  	    the Go tree can run a sanity check but not spend time running
   193  	    exhaustive tests.
   194  
   195  	-timeout t
   196  	    If a test runs longer than t, panic.
   197  	    The default is 10 minutes (10m).
   198  
   199  	-v
   200  	    Verbose output: log all tests as they are run. Also print all
   201  	    text from Log and Logf calls even if the test succeeds.
   202  
   203  The following flags are also recognized by 'go test' and can be used to
   204  profile the tests during execution::
   205  
   206  	-benchmem
   207  	    Print memory allocation statistics for benchmarks.
   208  
   209  	-blockprofile block.out
   210  	    Write a goroutine blocking profile to the specified file
   211  	    when all tests are complete.
   212  	    Writes test binary as -c would.
   213  
   214  	-blockprofilerate n
   215  	    Control the detail provided in goroutine blocking profiles by
   216  	    calling runtime.SetBlockProfileRate with n.
   217  	    See 'go doc runtime.SetBlockProfileRate'.
   218  	    The profiler aims to sample, on average, one blocking event every
   219  	    n nanoseconds the program spends blocked.  By default,
   220  	    if -test.blockprofile is set without this flag, all blocking events
   221  	    are recorded, equivalent to -test.blockprofilerate=1.
   222  
   223  	-coverprofile cover.out
   224  	    Write a coverage profile to the file after all tests have passed.
   225  	    Sets -cover.
   226  
   227  	-cpuprofile cpu.out
   228  	    Write a CPU profile to the specified file before exiting.
   229  	    Writes test binary as -c would.
   230  
   231  	-memprofile mem.out
   232  	    Write a memory profile to the file after all tests have passed.
   233  	    Writes test binary as -c would.
   234  
   235  	-memprofilerate n
   236  	    Enable more precise (and expensive) memory profiles by setting
   237  	    runtime.MemProfileRate.  See 'go doc runtime.MemProfileRate'.
   238  	    To profile all memory allocations, use -test.memprofilerate=1
   239  	    and pass --alloc_space flag to the pprof tool.
   240  
   241  	-mutexprofile mutex.out
   242  	    Write a mutex contention profile to the specified file
   243  	    when all tests are complete.
   244  	    Writes test binary as -c would.
   245  
   246  	-mutexprofilefraction n
   247   	    Sample 1 in n stack traces of goroutines holding a
   248  	    contended mutex.
   249  
   250  	-outputdir directory
   251  	    Place output files from profiling in the specified directory,
   252  	    by default the directory in which "go test" is running.
   253  
   254  	-trace trace.out
   255  	    Write an execution trace to the specified file before exiting.
   256  
   257  Each of these flags is also recognized with an optional 'test.' prefix,
   258  as in -test.v. When invoking the generated test binary (the result of
   259  'go test -c') directly, however, the prefix is mandatory.
   260  
   261  The 'go test' command rewrites or removes recognized flags,
   262  as appropriate, both before and after the optional package list,
   263  before invoking the test binary.
   264  
   265  For instance, the command
   266  
   267  	go test -v -myflag testdata -cpuprofile=prof.out -x
   268  
   269  will compile the test binary and then run it as
   270  
   271  	pkg.test -test.v -myflag testdata -test.cpuprofile=prof.out
   272  
   273  (The -x flag is removed because it applies only to the go command's
   274  execution, not to the test itself.)
   275  
   276  The test flags that generate profiles (other than for coverage) also
   277  leave the test binary in pkg.test for use when analyzing the profiles.
   278  
   279  When 'go test' runs a test binary, it does so from within the
   280  corresponding package's source code directory. Depending on the test,
   281  it may be necessary to do the same when invoking a generated test
   282  binary directly.
   283  
   284  The command-line package list, if present, must appear before any
   285  flag not known to the go test command. Continuing the example above,
   286  the package list would have to appear before -myflag, but could appear
   287  on either side of -v.
   288  
   289  To keep an argument for a test binary from being interpreted as a
   290  known flag or a package name, use -args (see 'go help test') which
   291  passes the remainder of the command line through to the test binary
   292  uninterpreted and unaltered.
   293  
   294  For instance, the command
   295  
   296  	go test -v -args -x -v
   297  
   298  will compile the test binary and then run it as
   299  
   300  	pkg.test -test.v -x -v
   301  
   302  Similarly,
   303  
   304  	go test -args math
   305  
   306  will compile the test binary and then run it as
   307  
   308  	pkg.test math
   309  
   310  In the first example, the -x and the second -v are passed through to the
   311  test binary unchanged and with no effect on the go command itself.
   312  In the second example, the argument math is passed through to the test
   313  binary, instead of being interpreted as the package list.
   314  `
   315  
   316  var helpTestfunc = &Command{
   317  	UsageLine: "testfunc",
   318  	Short:     "description of testing functions",
   319  	Long: `
   320  The 'go test' command expects to find test, benchmark, and example functions
   321  in the "*_test.go" files corresponding to the package under test.
   322  
   323  A test function is one named TestXXX (where XXX is any alphanumeric string
   324  not starting with a lower case letter) and should have the signature,
   325  
   326  	func TestXXX(t *testing.T) { ... }
   327  
   328  A benchmark function is one named BenchmarkXXX and should have the signature,
   329  
   330  	func BenchmarkXXX(b *testing.B) { ... }
   331  
   332  An example function is similar to a test function but, instead of using
   333  *testing.T to report success or failure, prints output to os.Stdout.
   334  If the last comment in the function starts with "Output:" then the output
   335  is compared exactly against the comment (see examples below). If the last
   336  comment begins with "Unordered output:" then the output is compared to the
   337  comment, however the order of the lines is ignored. An example with no such
   338  comment, or with no text after "Output:" is compiled but not executed.
   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  	"regexp":  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) > 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.NeedCgo = true
   898  		}
   899  	}
   900  
   901  	for _, cp := range pmain.imports {
   902  		if len(cp.coverVars) > 0 {
   903  			t.Cover = append(t.Cover, coverInfo{cp, cp.coverVars})
   904  		}
   905  	}
   906  
   907  	if !buildN {
   908  		// writeTestmain writes _testmain.go. This must happen after recompileForTest,
   909  		// because recompileForTest modifies XXX.
   910  		if err := writeTestmain(filepath.Join(testDir, "_testmain.go"), t); err != nil {
   911  			return nil, nil, nil, err
   912  		}
   913  	}
   914  
   915  	computeStale(pmain)
   916  
   917  	if ptest != p {
   918  		a := b.action(modeBuild, modeBuild, ptest)
   919  		a.objdir = testDir + string(filepath.Separator) + "_obj_test" + string(filepath.Separator)
   920  		a.objpkg = ptestObj
   921  		a.target = ptestObj
   922  		a.link = false
   923  	}
   924  
   925  	if pxtest != nil {
   926  		a := b.action(modeBuild, modeBuild, pxtest)
   927  		a.objdir = testDir + string(filepath.Separator) + "_obj_xtest" + string(filepath.Separator)
   928  		a.objpkg = buildToolchain.pkgpath(testDir, pxtest)
   929  		a.target = a.objpkg
   930  	}
   931  
   932  	a := b.action(modeBuild, modeBuild, pmain)
   933  	a.objdir = testDir + string(filepath.Separator)
   934  	a.objpkg = filepath.Join(testDir, "main.a")
   935  	a.target = filepath.Join(testDir, testBinary) + exeSuffix
   936  	if goos == "windows" {
   937  		// There are many reserved words on Windows that,
   938  		// if used in the name of an executable, cause Windows
   939  		// to try to ask for extra permissions.
   940  		// The word list includes setup, install, update, and patch,
   941  		// but it does not appear to be defined anywhere.
   942  		// We have run into this trying to run the
   943  		// go.codereview/patch tests.
   944  		// For package names containing those words, use test.test.exe
   945  		// instead of pkgname.test.exe.
   946  		// Note that this file name is only used in the Go command's
   947  		// temporary directory. If the -c or other flags are
   948  		// given, the code below will still use pkgname.test.exe.
   949  		// There are two user-visible effects of this change.
   950  		// First, you can actually run 'go test' in directories that
   951  		// have names that Windows thinks are installer-like,
   952  		// without getting a dialog box asking for more permissions.
   953  		// Second, in the Windows process listing during go test,
   954  		// the test shows up as test.test.exe, not pkgname.test.exe.
   955  		// That second one is a drawback, but it seems a small
   956  		// price to pay for the test running at all.
   957  		// If maintaining the list of bad words is too onerous,
   958  		// we could just do this always on Windows.
   959  		for _, bad := range windowsBadWords {
   960  			if strings.Contains(testBinary, bad) {
   961  				a.target = filepath.Join(testDir, "test.test") + exeSuffix
   962  				break
   963  			}
   964  		}
   965  	}
   966  	buildAction = a
   967  
   968  	if testC || testNeedBinary {
   969  		// -c or profiling flag: create action to copy binary to ./test.out.
   970  		target := filepath.Join(cwd, testBinary+exeSuffix)
   971  		if testO != "" {
   972  			target = testO
   973  			if !filepath.IsAbs(target) {
   974  				target = filepath.Join(cwd, target)
   975  			}
   976  		}
   977  		buildAction = &action{
   978  			f:      (*builder).install,
   979  			deps:   []*action{buildAction},
   980  			p:      pmain,
   981  			target: target,
   982  		}
   983  		runAction = buildAction // make sure runAction != nil even if not running test
   984  	}
   985  	if testC {
   986  		printAction = &action{p: p, deps: []*action{runAction}} // nop
   987  	} else {
   988  		// run test
   989  		runAction = &action{
   990  			f:          (*builder).runTest,
   991  			deps:       []*action{buildAction},
   992  			p:          p,
   993  			ignoreFail: true,
   994  		}
   995  		cleanAction := &action{
   996  			f:    (*builder).cleanTest,
   997  			deps: []*action{runAction},
   998  			p:    p,
   999  		}
  1000  		printAction = &action{
  1001  			f:    (*builder).printTest,
  1002  			deps: []*action{cleanAction},
  1003  			p:    p,
  1004  		}
  1005  	}
  1006  
  1007  	return buildAction, runAction, printAction, nil
  1008  }
  1009  
  1010  func testImportStack(top string, p *Package, target string) []string {
  1011  	stk := []string{top, p.ImportPath}
  1012  Search:
  1013  	for p.ImportPath != target {
  1014  		for _, p1 := range p.imports {
  1015  			if p1.ImportPath == target || contains(p1.Deps, target) {
  1016  				stk = append(stk, p1.ImportPath)
  1017  				p = p1
  1018  				continue Search
  1019  			}
  1020  		}
  1021  		// Can't happen, but in case it does...
  1022  		stk = append(stk, "<lost path to cycle>")
  1023  		break
  1024  	}
  1025  	return stk
  1026  }
  1027  
  1028  func recompileForTest(pmain, preal, ptest *Package, testDir string) {
  1029  	// The "test copy" of preal is ptest.
  1030  	// For each package that depends on preal, make a "test copy"
  1031  	// that depends on ptest. And so on, up the dependency tree.
  1032  	testCopy := map[*Package]*Package{preal: ptest}
  1033  	for _, p := range packageList([]*Package{pmain}) {
  1034  		// Copy on write.
  1035  		didSplit := false
  1036  		split := func() {
  1037  			if didSplit {
  1038  				return
  1039  			}
  1040  			didSplit = true
  1041  			if p.pkgdir != testDir {
  1042  				p1 := new(Package)
  1043  				testCopy[p] = p1
  1044  				*p1 = *p
  1045  				p1.imports = make([]*Package, len(p.imports))
  1046  				copy(p1.imports, p.imports)
  1047  				p = p1
  1048  				p.pkgdir = testDir
  1049  				p.target = ""
  1050  				p.fake = true
  1051  				p.Stale = true
  1052  				p.StaleReason = "depends on package being tested"
  1053  			}
  1054  		}
  1055  
  1056  		// Update p.deps and p.imports to use at test copies.
  1057  		for i, dep := range p.deps {
  1058  			if p1 := testCopy[dep]; p1 != nil && p1 != dep {
  1059  				split()
  1060  				p.deps[i] = p1
  1061  			}
  1062  		}
  1063  		for i, imp := range p.imports {
  1064  			if p1 := testCopy[imp]; p1 != nil && p1 != imp {
  1065  				split()
  1066  				p.imports[i] = p1
  1067  			}
  1068  		}
  1069  	}
  1070  }
  1071  
  1072  var coverIndex = 0
  1073  
  1074  // isTestFile reports whether the source file is a set of tests and should therefore
  1075  // be excluded from coverage analysis.
  1076  func isTestFile(file string) bool {
  1077  	// We don't cover tests, only the code they test.
  1078  	return strings.HasSuffix(file, "_test.go")
  1079  }
  1080  
  1081  // declareCoverVars attaches the required cover variables names
  1082  // to the files, to be used when annotating the files.
  1083  func declareCoverVars(importPath string, files ...string) map[string]*CoverVar {
  1084  	coverVars := make(map[string]*CoverVar)
  1085  	for _, file := range files {
  1086  		if isTestFile(file) {
  1087  			continue
  1088  		}
  1089  		coverVars[file] = &CoverVar{
  1090  			File: filepath.Join(importPath, file),
  1091  			Var:  fmt.Sprintf("GoCover_%d", coverIndex),
  1092  		}
  1093  		coverIndex++
  1094  	}
  1095  	return coverVars
  1096  }
  1097  
  1098  var noTestsToRun = []byte("\ntesting: warning: no tests to run\n")
  1099  
  1100  // runTest is the action for running a test binary.
  1101  func (b *builder) runTest(a *action) error {
  1102  	args := stringList(findExecCmd(), a.deps[0].target, testArgs)
  1103  	a.testOutput = new(bytes.Buffer)
  1104  
  1105  	if buildN || buildX {
  1106  		b.showcmd("", "%s", strings.Join(args, " "))
  1107  		if buildN {
  1108  			return nil
  1109  		}
  1110  	}
  1111  
  1112  	if a.failed {
  1113  		// We were unable to build the binary.
  1114  		a.failed = false
  1115  		fmt.Fprintf(a.testOutput, "FAIL\t%s [build failed]\n", a.p.ImportPath)
  1116  		setExitStatus(1)
  1117  		return nil
  1118  	}
  1119  
  1120  	cmd := exec.Command(args[0], args[1:]...)
  1121  	cmd.Dir = a.p.Dir
  1122  	cmd.Env = envForDir(cmd.Dir, origEnv)
  1123  	var buf bytes.Buffer
  1124  	if testStreamOutput {
  1125  		// The only way to keep the ordering of the messages and still
  1126  		// intercept its contents. os/exec will share the same Pipe for
  1127  		// both Stdout and Stderr when running the test program.
  1128  		mw := io.MultiWriter(os.Stdout, &buf)
  1129  		cmd.Stdout = mw
  1130  		cmd.Stderr = mw
  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 && !testStreamOutput {
  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  		if !testStreamOutput {
  1208  			a.testOutput.Write(out)
  1209  		}
  1210  		// assume printing the test binary's exit status is superfluous
  1211  	} else {
  1212  		fmt.Fprintf(a.testOutput, "%s\n", err)
  1213  	}
  1214  	fmt.Fprintf(a.testOutput, "FAIL\t%s\t%s\n", a.p.ImportPath, t)
  1215  
  1216  	return nil
  1217  }
  1218  
  1219  // coveragePercentage returns the coverage results (if enabled) for the
  1220  // test. It uncovers the data by scanning the output from the test run.
  1221  func coveragePercentage(out []byte) string {
  1222  	if !testCover {
  1223  		return ""
  1224  	}
  1225  	// The string looks like
  1226  	//	test coverage for encoding/binary: 79.9% of statements
  1227  	// Extract the piece from the percentage to the end of the line.
  1228  	re := regexp.MustCompile(`coverage: (.*)\n`)
  1229  	matches := re.FindSubmatch(out)
  1230  	if matches == nil {
  1231  		// Probably running "go test -cover" not "go test -cover fmt".
  1232  		// The coverage output will appear in the output directly.
  1233  		return ""
  1234  	}
  1235  	return fmt.Sprintf("\tcoverage: %s", matches[1])
  1236  }
  1237  
  1238  // cleanTest is the action for cleaning up after a test.
  1239  func (b *builder) cleanTest(a *action) error {
  1240  	if buildWork {
  1241  		return nil
  1242  	}
  1243  	run := a.deps[0]
  1244  	testDir := filepath.Join(b.work, filepath.FromSlash(run.p.ImportPath+"/_test"))
  1245  	os.RemoveAll(testDir)
  1246  	return nil
  1247  }
  1248  
  1249  // printTest is the action for printing a test result.
  1250  func (b *builder) printTest(a *action) error {
  1251  	clean := a.deps[0]
  1252  	run := clean.deps[0]
  1253  	os.Stdout.Write(run.testOutput.Bytes())
  1254  	run.testOutput = nil
  1255  	return nil
  1256  }
  1257  
  1258  // notest is the action for testing a package with no test files.
  1259  func (b *builder) notest(a *action) error {
  1260  	fmt.Printf("?   \t%s\t[no test files]\n", a.p.ImportPath)
  1261  	return nil
  1262  }
  1263  
  1264  // isTestFunc tells whether fn has the type of a testing function. arg
  1265  // specifies the parameter type we look for: B, M or T.
  1266  func isTestFunc(fn *ast.FuncDecl, arg string) bool {
  1267  	if fn.Type.Results != nil && len(fn.Type.Results.List) > 0 ||
  1268  		fn.Type.Params.List == nil ||
  1269  		len(fn.Type.Params.List) != 1 ||
  1270  		len(fn.Type.Params.List[0].Names) > 1 {
  1271  		return false
  1272  	}
  1273  	ptr, ok := fn.Type.Params.List[0].Type.(*ast.StarExpr)
  1274  	if !ok {
  1275  		return false
  1276  	}
  1277  	// We can't easily check that the type is *testing.M
  1278  	// because we don't know how testing has been imported,
  1279  	// but at least check that it's *M or *something.M.
  1280  	// Same applies for B and T.
  1281  	if name, ok := ptr.X.(*ast.Ident); ok && name.Name == arg {
  1282  		return true
  1283  	}
  1284  	if sel, ok := ptr.X.(*ast.SelectorExpr); ok && sel.Sel.Name == arg {
  1285  		return true
  1286  	}
  1287  	return false
  1288  }
  1289  
  1290  // isTest tells whether name looks like a test (or benchmark, according to prefix).
  1291  // It is a Test (say) if there is a character after Test that is not a lower-case letter.
  1292  // We don't want TesticularCancer.
  1293  func isTest(name, prefix string) bool {
  1294  	if !strings.HasPrefix(name, prefix) {
  1295  		return false
  1296  	}
  1297  	if len(name) == len(prefix) { // "Test" is ok
  1298  		return true
  1299  	}
  1300  	rune, _ := utf8.DecodeRuneInString(name[len(prefix):])
  1301  	return !unicode.IsLower(rune)
  1302  }
  1303  
  1304  type coverInfo struct {
  1305  	Package *Package
  1306  	Vars    map[string]*CoverVar
  1307  }
  1308  
  1309  // loadTestFuncs returns the testFuncs describing the tests that will be run.
  1310  func loadTestFuncs(ptest *Package) (*testFuncs, error) {
  1311  	t := &testFuncs{
  1312  		Package: ptest,
  1313  	}
  1314  	for _, file := range ptest.TestGoFiles {
  1315  		if err := t.load(filepath.Join(ptest.Dir, file), "_test", &t.ImportTest, &t.NeedTest); err != nil {
  1316  			return nil, err
  1317  		}
  1318  	}
  1319  	for _, file := range ptest.XTestGoFiles {
  1320  		if err := t.load(filepath.Join(ptest.Dir, file), "_xtest", &t.ImportXtest, &t.NeedXtest); err != nil {
  1321  			return nil, err
  1322  		}
  1323  	}
  1324  	return t, nil
  1325  }
  1326  
  1327  // writeTestmain writes the _testmain.go file for t to the file named out.
  1328  func writeTestmain(out string, t *testFuncs) error {
  1329  	f, err := os.Create(out)
  1330  	if err != nil {
  1331  		return err
  1332  	}
  1333  	defer f.Close()
  1334  
  1335  	if err := testmainTmpl.Execute(f, t); err != nil {
  1336  		return err
  1337  	}
  1338  
  1339  	return nil
  1340  }
  1341  
  1342  type testFuncs struct {
  1343  	Tests       []testFunc
  1344  	Benchmarks  []testFunc
  1345  	Examples    []testFunc
  1346  	TestMain    *testFunc
  1347  	Package     *Package
  1348  	ImportTest  bool
  1349  	NeedTest    bool
  1350  	ImportXtest bool
  1351  	NeedXtest   bool
  1352  	NeedCgo     bool
  1353  	Cover       []coverInfo
  1354  }
  1355  
  1356  func (t *testFuncs) CoverMode() string {
  1357  	return testCoverMode
  1358  }
  1359  
  1360  func (t *testFuncs) CoverEnabled() bool {
  1361  	return testCover
  1362  }
  1363  
  1364  // Covered returns a string describing which packages are being tested for coverage.
  1365  // If the covered package is the same as the tested package, it returns the empty string.
  1366  // Otherwise it is a comma-separated human-readable list of packages beginning with
  1367  // " in", ready for use in the coverage message.
  1368  func (t *testFuncs) Covered() string {
  1369  	if testCoverPaths == nil {
  1370  		return ""
  1371  	}
  1372  	return " in " + strings.Join(testCoverPaths, ", ")
  1373  }
  1374  
  1375  // Tested returns the name of the package being tested.
  1376  func (t *testFuncs) Tested() string {
  1377  	return t.Package.Name
  1378  }
  1379  
  1380  type testFunc struct {
  1381  	Package   string // imported package name (_test or _xtest)
  1382  	Name      string // function name
  1383  	Output    string // output, for examples
  1384  	Unordered bool   // output is allowed to be unordered.
  1385  }
  1386  
  1387  var testFileSet = token.NewFileSet()
  1388  
  1389  func (t *testFuncs) load(filename, pkg string, doImport, seen *bool) error {
  1390  	f, err := parser.ParseFile(testFileSet, filename, nil, parser.ParseComments)
  1391  	if err != nil {
  1392  		return expandScanner(err)
  1393  	}
  1394  	for _, d := range f.Decls {
  1395  		n, ok := d.(*ast.FuncDecl)
  1396  		if !ok {
  1397  			continue
  1398  		}
  1399  		if n.Recv != nil {
  1400  			continue
  1401  		}
  1402  		name := n.Name.String()
  1403  		switch {
  1404  		case name == "TestMain" && isTestFunc(n, "M"):
  1405  			if t.TestMain != nil {
  1406  				return errors.New("multiple definitions of TestMain")
  1407  			}
  1408  			t.TestMain = &testFunc{pkg, name, "", false}
  1409  			*doImport, *seen = true, true
  1410  		case isTest(name, "Test"):
  1411  			err := checkTestFunc(n, "T")
  1412  			if err != nil {
  1413  				return err
  1414  			}
  1415  			t.Tests = append(t.Tests, testFunc{pkg, name, "", false})
  1416  			*doImport, *seen = true, true
  1417  		case isTest(name, "Benchmark"):
  1418  			err := checkTestFunc(n, "B")
  1419  			if err != nil {
  1420  				return err
  1421  			}
  1422  			t.Benchmarks = append(t.Benchmarks, testFunc{pkg, name, "", false})
  1423  			*doImport, *seen = true, true
  1424  		}
  1425  	}
  1426  	ex := doc.Examples(f)
  1427  	sort.Slice(ex, func(i, j int) bool { return ex[i].Order < ex[j].Order })
  1428  	for _, e := range ex {
  1429  		*doImport = true // import test file whether executed or not
  1430  		if e.Output == "" && !e.EmptyOutput {
  1431  			// Don't run examples with no output.
  1432  			continue
  1433  		}
  1434  		t.Examples = append(t.Examples, testFunc{pkg, "Example" + e.Name, e.Output, e.Unordered})
  1435  		*seen = true
  1436  	}
  1437  	return nil
  1438  }
  1439  
  1440  func checkTestFunc(fn *ast.FuncDecl, arg string) error {
  1441  	if !isTestFunc(fn, arg) {
  1442  		name := fn.Name.String()
  1443  		pos := testFileSet.Position(fn.Pos())
  1444  		return fmt.Errorf("%s: wrong signature for %s, must be: func %s(%s *testing.%s)", pos, name, name, strings.ToLower(arg), arg)
  1445  	}
  1446  	return nil
  1447  }
  1448  
  1449  var testmainTmpl = template.Must(template.New("main").Parse(`
  1450  package main
  1451  
  1452  import (
  1453  {{if not .TestMain}}
  1454  	"os"
  1455  {{end}}
  1456  	"regexp"
  1457  	"testing"
  1458  
  1459  {{if .ImportTest}}
  1460  	{{if .NeedTest}}_test{{else}}_{{end}} {{.Package.ImportPath | printf "%q"}}
  1461  {{end}}
  1462  {{if .ImportXtest}}
  1463  	{{if .NeedXtest}}_xtest{{else}}_{{end}} {{.Package.ImportPath | printf "%s_test" | printf "%q"}}
  1464  {{end}}
  1465  {{range $i, $p := .Cover}}
  1466  	_cover{{$i}} {{$p.Package.ImportPath | printf "%q"}}
  1467  {{end}}
  1468  
  1469  {{if .NeedCgo}}
  1470  	_ "runtime/cgo"
  1471  {{end}}
  1472  )
  1473  
  1474  var tests = []testing.InternalTest{
  1475  {{range .Tests}}
  1476  	{"{{.Name}}", {{.Package}}.{{.Name}}},
  1477  {{end}}
  1478  }
  1479  
  1480  var benchmarks = []testing.InternalBenchmark{
  1481  {{range .Benchmarks}}
  1482  	{"{{.Name}}", {{.Package}}.{{.Name}}},
  1483  {{end}}
  1484  }
  1485  
  1486  var examples = []testing.InternalExample{
  1487  {{range .Examples}}
  1488  	{"{{.Name}}", {{.Package}}.{{.Name}}, {{.Output | printf "%q"}}, {{.Unordered}}},
  1489  {{end}}
  1490  }
  1491  
  1492  var matchPat string
  1493  var matchRe *regexp.Regexp
  1494  
  1495  func matchString(pat, str string) (result bool, err error) {
  1496  	if matchRe == nil || matchPat != pat {
  1497  		matchPat = pat
  1498  		matchRe, err = regexp.Compile(matchPat)
  1499  		if err != nil {
  1500  			return
  1501  		}
  1502  	}
  1503  	return matchRe.MatchString(str), nil
  1504  }
  1505  
  1506  {{if .CoverEnabled}}
  1507  
  1508  // Only updated by init functions, so no need for atomicity.
  1509  var (
  1510  	coverCounters = make(map[string][]uint32)
  1511  	coverBlocks = make(map[string][]testing.CoverBlock)
  1512  )
  1513  
  1514  func init() {
  1515  	{{range $i, $p := .Cover}}
  1516  	{{range $file, $cover := $p.Vars}}
  1517  	coverRegisterFile({{printf "%q" $cover.File}}, _cover{{$i}}.{{$cover.Var}}.Count[:], _cover{{$i}}.{{$cover.Var}}.Pos[:], _cover{{$i}}.{{$cover.Var}}.NumStmt[:])
  1518  	{{end}}
  1519  	{{end}}
  1520  }
  1521  
  1522  func coverRegisterFile(fileName string, counter []uint32, pos []uint32, numStmts []uint16) {
  1523  	if 3*len(counter) != len(pos) || len(counter) != len(numStmts) {
  1524  		panic("coverage: mismatched sizes")
  1525  	}
  1526  	if coverCounters[fileName] != nil {
  1527  		// Already registered.
  1528  		return
  1529  	}
  1530  	coverCounters[fileName] = counter
  1531  	block := make([]testing.CoverBlock, len(counter))
  1532  	for i := range counter {
  1533  		block[i] = testing.CoverBlock{
  1534  			Line0: pos[3*i+0],
  1535  			Col0: uint16(pos[3*i+2]),
  1536  			Line1: pos[3*i+1],
  1537  			Col1: uint16(pos[3*i+2]>>16),
  1538  			Stmts: numStmts[i],
  1539  		}
  1540  	}
  1541  	coverBlocks[fileName] = block
  1542  }
  1543  {{end}}
  1544  
  1545  func main() {
  1546  {{if .CoverEnabled}}
  1547  	testing.RegisterCover(testing.Cover{
  1548  		Mode: {{printf "%q" .CoverMode}},
  1549  		Counters: coverCounters,
  1550  		Blocks: coverBlocks,
  1551  		CoveredPackages: {{printf "%q" .Covered}},
  1552  	})
  1553  {{end}}
  1554  	m := testing.MainStart(matchString, tests, benchmarks, examples)
  1555  {{with .TestMain}}
  1556  	{{.Package}}.{{.Name}}(m)
  1557  {{else}}
  1558  	os.Exit(m.Run())
  1559  {{end}}
  1560  }
  1561  
  1562  `))