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