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