github.com/epfl-dcsl/gotee@v0.0.0-20200909122901-014b35f5e5e9/src/cmd/go/internal/test/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 test
     6  
     7  import (
     8  	"bytes"
     9  	"crypto/sha256"
    10  	"errors"
    11  	"fmt"
    12  	"go/ast"
    13  	"go/build"
    14  	"go/doc"
    15  	"go/parser"
    16  	"go/token"
    17  	"io"
    18  	"io/ioutil"
    19  	"os"
    20  	"os/exec"
    21  	"path"
    22  	"path/filepath"
    23  	"regexp"
    24  	"sort"
    25  	"strconv"
    26  	"strings"
    27  	"sync"
    28  	"text/template"
    29  	"time"
    30  	"unicode"
    31  	"unicode/utf8"
    32  
    33  	"cmd/go/internal/base"
    34  	"cmd/go/internal/cache"
    35  	"cmd/go/internal/cfg"
    36  	"cmd/go/internal/load"
    37  	"cmd/go/internal/str"
    38  	"cmd/go/internal/work"
    39  	"cmd/internal/test2json"
    40  )
    41  
    42  // Break init loop.
    43  func init() {
    44  	CmdTest.Run = runTest
    45  }
    46  
    47  const testUsage = "test [build/test flags] [packages] [build/test flags & test binary flags]"
    48  
    49  var CmdTest = &base.Command{
    50  	CustomFlags: true,
    51  	UsageLine:   testUsage,
    52  	Short:       "test packages",
    53  	Long: `
    54  'Go test' automates testing the packages named by the import paths.
    55  It prints a summary of the test results in the format:
    56  
    57  	ok   archive/tar   0.011s
    58  	FAIL archive/zip   0.022s
    59  	ok   compress/gzip 0.033s
    60  	...
    61  
    62  followed by detailed output for each failed package.
    63  
    64  'Go test' recompiles each package along with any files with names matching
    65  the file pattern "*_test.go".
    66  These additional files can contain test functions, benchmark functions, and
    67  example functions. See 'go help testfunc' for more.
    68  Each listed package causes the execution of a separate test binary.
    69  Files whose names begin with "_" (including "_test.go") or "." are ignored.
    70  
    71  Test files that declare a package with the suffix "_test" will be compiled as a
    72  separate package, and then linked and run with the main test binary.
    73  
    74  The go tool will ignore a directory named "testdata", making it available
    75  to hold ancillary data needed by the tests.
    76  
    77  As part of building a test binary, go test runs go vet on the package
    78  and its test source files to identify significant problems. If go vet
    79  finds any problems, go test reports those and does not run the test binary.
    80  Only a high-confidence subset of the default go vet checks are used.
    81  To disable the running of go vet, use the -vet=off flag.
    82  
    83  All test output and summary lines are printed to the go command's
    84  standard output, even if the test printed them to its own standard
    85  error. (The go command's standard error is reserved for printing
    86  errors building the tests.)
    87  
    88  Go test runs in two different modes:
    89  
    90  The first, called local directory mode, occurs when go test is
    91  invoked with no package arguments (for example, 'go test' or 'go
    92  test -v'). In this mode, go test compiles the package sources and
    93  tests found in the current directory and then runs the resulting
    94  test binary. In this mode, caching (discussed below) is disabled.
    95  After the package test finishes, go test prints a summary line
    96  showing the test status ('ok' or 'FAIL'), package name, and elapsed
    97  time.
    98  
    99  The second, called package list mode, occurs when go test is invoked
   100  with explicit package arguments (for example 'go test math', 'go
   101  test ./...', and even 'go test .'). In this mode, go test compiles
   102  and tests each of the packages listed on the command line. If a
   103  package test passes, go test prints only the final 'ok' summary
   104  line. If a package test fails, go test prints the full test output.
   105  If invoked with the -bench or -v flag, go test prints the full
   106  output even for passing package tests, in order to display the
   107  requested benchmark results or verbose logging.
   108  
   109  In package list mode only, go test caches successful package test
   110  results to avoid unnecessary repeated running of tests. When the
   111  result of a test can be recovered from the cache, go test will
   112  redisplay the previous output instead of running the test binary
   113  again. When this happens, go test prints '(cached)' in place of the
   114  elapsed time in the summary line.
   115  
   116  The rule for a match in the cache is that the run involves the same
   117  test binary and the flags on the command line come entirely from a
   118  restricted set of 'cacheable' test flags, defined as -cpu, -list,
   119  -parallel, -run, -short, and -v. If a run of go test has any test
   120  or non-test flags outside this set, the result is not cached. To
   121  disable test caching, use any test flag or argument other than the
   122  cacheable flags. The idiomatic way to disable test caching explicitly
   123  is to use -count=1. Tests that open files within the package's source
   124  root (usually $GOPATH) or that consult environment variables only
   125  match future runs in which the files and environment variables are unchanged.
   126  A cached test result is treated as executing in no time at all,
   127  so a successful package test result will be cached and reused
   128  regardless of -timeout setting.
   129  
   130  ` + strings.TrimSpace(testFlag1) + ` See 'go help testflag' for details.
   131  
   132  For more about build flags, see 'go help build'.
   133  For more about specifying packages, see 'go help packages'.
   134  
   135  See also: go build, go vet.
   136  `,
   137  }
   138  
   139  const testFlag1 = `
   140  In addition to the build flags, the flags handled by 'go test' itself are:
   141  
   142  	-args
   143  	    Pass the remainder of the command line (everything after -args)
   144  	    to the test binary, uninterpreted and unchanged.
   145  	    Because this flag consumes the remainder of the command line,
   146  	    the package list (if present) must appear before this flag.
   147  
   148  	-c
   149  	    Compile the test binary to pkg.test but do not run it
   150  	    (where pkg is the last element of the package's import path).
   151  	    The file name can be changed with the -o flag.
   152  
   153  	-exec xprog
   154  	    Run the test binary using xprog. The behavior is the same as
   155  	    in 'go run'. See 'go help run' for details.
   156  
   157  	-i
   158  	    Install packages that are dependencies of the test.
   159  	    Do not run the test.
   160  
   161  	-json
   162  	    Convert test output to JSON suitable for automated processing.
   163  	    See 'go doc test2json' for the encoding details.
   164  
   165  	-o file
   166  	    Compile the test binary to the named file.
   167  	    The test still runs (unless -c or -i is specified).
   168  
   169  The test binary also accepts flags that control execution of the test; these
   170  flags are also accessible by 'go test'.
   171  `
   172  
   173  // Usage prints the usage message for 'go test -h' and exits.
   174  func Usage() {
   175  	os.Stderr.WriteString(testUsage + "\n\n" +
   176  		strings.TrimSpace(testFlag1) + "\n\n\t" +
   177  		strings.TrimSpace(testFlag2) + "\n")
   178  	os.Exit(2)
   179  }
   180  
   181  var HelpTestflag = &base.Command{
   182  	UsageLine: "testflag",
   183  	Short:     "testing flags",
   184  	Long: `
   185  The 'go test' command takes both flags that apply to 'go test' itself
   186  and flags that apply to the resulting test binary.
   187  
   188  Several of the flags control profiling and write an execution profile
   189  suitable for "go tool pprof"; run "go tool pprof -h" for more
   190  information. The --alloc_space, --alloc_objects, and --show_bytes
   191  options of pprof control how the information is presented.
   192  
   193  The following flags are recognized by the 'go test' command and
   194  control the execution of any test:
   195  
   196  	` + strings.TrimSpace(testFlag2) + `
   197  `,
   198  }
   199  
   200  const testFlag2 = `
   201  	-bench regexp
   202  	    Run only those benchmarks matching a regular expression.
   203  	    By default, no benchmarks are run.
   204  	    To run all benchmarks, use '-bench .' or '-bench=.'.
   205  	    The regular expression is split by unbracketed slash (/)
   206  	    characters into a sequence of regular expressions, and each
   207  	    part of a benchmark's identifier must match the corresponding
   208  	    element in the sequence, if any. Possible parents of matches
   209  	    are run with b.N=1 to identify sub-benchmarks. For example,
   210  	    given -bench=X/Y, top-level benchmarks matching X are run
   211  	    with b.N=1 to find any sub-benchmarks matching Y, which are
   212  	    then run in full.
   213  
   214  	-benchtime t
   215  	    Run enough iterations of each benchmark to take t, specified
   216  	    as a time.Duration (for example, -benchtime 1h30s).
   217  	    The default is 1 second (1s).
   218  
   219  	-count n
   220  	    Run each test and benchmark n times (default 1).
   221  	    If -cpu is set, run n times for each GOMAXPROCS value.
   222  	    Examples are always run once.
   223  
   224  	-cover
   225  	    Enable coverage analysis.
   226  	    Note that because coverage works by annotating the source
   227  	    code before compilation, compilation and test failures with
   228  	    coverage enabled may report line numbers that don't correspond
   229  	    to the original sources.
   230  
   231  	-covermode set,count,atomic
   232  	    Set the mode for coverage analysis for the package[s]
   233  	    being tested. The default is "set" unless -race is enabled,
   234  	    in which case it is "atomic".
   235  	    The values:
   236  		set: bool: does this statement run?
   237  		count: int: how many times does this statement run?
   238  		atomic: int: count, but correct in multithreaded tests;
   239  			significantly more expensive.
   240  	    Sets -cover.
   241  
   242  	-coverpkg pattern1,pattern2,pattern3
   243  	    Apply coverage analysis in each test to packages matching the patterns.
   244  	    The default is for each test to analyze only the package being tested.
   245  	    See 'go help packages' for a description of package patterns.
   246  	    Sets -cover.
   247  
   248  	-cpu 1,2,4
   249  	    Specify a list of GOMAXPROCS values for which the tests or
   250  	    benchmarks should be executed. The default is the current value
   251  	    of GOMAXPROCS.
   252  
   253  	-failfast
   254  	    Do not start new tests after the first test failure.
   255  
   256  	-list regexp
   257  	    List tests, benchmarks, or examples matching the regular expression.
   258  	    No tests, benchmarks or examples will be run. This will only
   259  	    list top-level tests. No subtest or subbenchmarks will be shown.
   260  
   261  	-parallel n
   262  	    Allow parallel execution of test functions that call t.Parallel.
   263  	    The value of this flag is the maximum number of tests to run
   264  	    simultaneously; by default, it is set to the value of GOMAXPROCS.
   265  	    Note that -parallel only applies within a single test binary.
   266  	    The 'go test' command may run tests for different packages
   267  	    in parallel as well, according to the setting of the -p flag
   268  	    (see 'go help build').
   269  
   270  	-run regexp
   271  	    Run only those tests and examples matching the regular expression.
   272  	    For tests, the regular expression is split by unbracketed slash (/)
   273  	    characters into a sequence of regular expressions, and each part
   274  	    of a test's identifier must match the corresponding element in
   275  	    the sequence, if any. Note that possible parents of matches are
   276  	    run too, so that -run=X/Y matches and runs and reports the result
   277  	    of all tests matching X, even those without sub-tests matching Y,
   278  	    because it must run them to look for those sub-tests.
   279  
   280  	-short
   281  	    Tell long-running tests to shorten their run time.
   282  	    It is off by default but set during all.bash so that installing
   283  	    the Go tree can run a sanity check but not spend time running
   284  	    exhaustive tests.
   285  
   286  	-timeout d
   287  	    If a test binary runs longer than duration d, panic.
   288  	    If d is 0, the timeout is disabled.
   289  	    The default is 10 minutes (10m).
   290  
   291  	-v
   292  	    Verbose output: log all tests as they are run. Also print all
   293  	    text from Log and Logf calls even if the test succeeds.
   294  
   295  	-vet list
   296  	    Configure the invocation of "go vet" during "go test"
   297  	    to use the comma-separated list of vet checks.
   298  	    If list is empty, "go test" runs "go vet" with a curated list of
   299  	    checks believed to be always worth addressing.
   300  	    If list is "off", "go test" does not run "go vet" at all.
   301  
   302  The following flags are also recognized by 'go test' and can be used to
   303  profile the tests during execution:
   304  
   305  	-benchmem
   306  	    Print memory allocation statistics for benchmarks.
   307  
   308  	-blockprofile block.out
   309  	    Write a goroutine blocking profile to the specified file
   310  	    when all tests are complete.
   311  	    Writes test binary as -c would.
   312  
   313  	-blockprofilerate n
   314  	    Control the detail provided in goroutine blocking profiles by
   315  	    calling runtime.SetBlockProfileRate with n.
   316  	    See 'go doc runtime.SetBlockProfileRate'.
   317  	    The profiler aims to sample, on average, one blocking event every
   318  	    n nanoseconds the program spends blocked. By default,
   319  	    if -test.blockprofile is set without this flag, all blocking events
   320  	    are recorded, equivalent to -test.blockprofilerate=1.
   321  
   322  	-coverprofile cover.out
   323  	    Write a coverage profile to the file after all tests have passed.
   324  	    Sets -cover.
   325  
   326  	-cpuprofile cpu.out
   327  	    Write a CPU profile to the specified file before exiting.
   328  	    Writes test binary as -c would.
   329  
   330  	-memprofile mem.out
   331  	    Write a memory profile to the file after all tests have passed.
   332  	    Writes test binary as -c would.
   333  
   334  	-memprofilerate n
   335  	    Enable more precise (and expensive) memory profiles by setting
   336  	    runtime.MemProfileRate. See 'go doc runtime.MemProfileRate'.
   337  	    To profile all memory allocations, use -test.memprofilerate=1
   338  	    and pass --alloc_space flag to the pprof tool.
   339  
   340  	-mutexprofile mutex.out
   341  	    Write a mutex contention profile to the specified file
   342  	    when all tests are complete.
   343  	    Writes test binary as -c would.
   344  
   345  	-mutexprofilefraction n
   346  	    Sample 1 in n stack traces of goroutines holding a
   347  	    contended mutex.
   348  
   349  	-outputdir directory
   350  	    Place output files from profiling in the specified directory,
   351  	    by default the directory in which "go test" is running.
   352  
   353  	-trace trace.out
   354  	    Write an execution trace to the specified file before exiting.
   355  
   356  Each of these flags is also recognized with an optional 'test.' prefix,
   357  as in -test.v. When invoking the generated test binary (the result of
   358  'go test -c') directly, however, the prefix is mandatory.
   359  
   360  The 'go test' command rewrites or removes recognized flags,
   361  as appropriate, both before and after the optional package list,
   362  before invoking the test binary.
   363  
   364  For instance, the command
   365  
   366  	go test -v -myflag testdata -cpuprofile=prof.out -x
   367  
   368  will compile the test binary and then run it as
   369  
   370  	pkg.test -test.v -myflag testdata -test.cpuprofile=prof.out
   371  
   372  (The -x flag is removed because it applies only to the go command's
   373  execution, not to the test itself.)
   374  
   375  The test flags that generate profiles (other than for coverage) also
   376  leave the test binary in pkg.test for use when analyzing the profiles.
   377  
   378  When 'go test' runs a test binary, it does so from within the
   379  corresponding package's source code directory. Depending on the test,
   380  it may be necessary to do the same when invoking a generated test
   381  binary directly.
   382  
   383  The command-line package list, if present, must appear before any
   384  flag not known to the go test command. Continuing the example above,
   385  the package list would have to appear before -myflag, but could appear
   386  on either side of -v.
   387  
   388  To keep an argument for a test binary from being interpreted as a
   389  known flag or a package name, use -args (see 'go help test') which
   390  passes the remainder of the command line through to the test binary
   391  uninterpreted and unaltered.
   392  
   393  For instance, the command
   394  
   395  	go test -v -args -x -v
   396  
   397  will compile the test binary and then run it as
   398  
   399  	pkg.test -test.v -x -v
   400  
   401  Similarly,
   402  
   403  	go test -args math
   404  
   405  will compile the test binary and then run it as
   406  
   407  	pkg.test math
   408  
   409  In the first example, the -x and the second -v are passed through to the
   410  test binary unchanged and with no effect on the go command itself.
   411  In the second example, the argument math is passed through to the test
   412  binary, instead of being interpreted as the package list.
   413  `
   414  
   415  var HelpTestfunc = &base.Command{
   416  	UsageLine: "testfunc",
   417  	Short:     "testing functions",
   418  	Long: `
   419  The 'go test' command expects to find test, benchmark, and example functions
   420  in the "*_test.go" files corresponding to the package under test.
   421  
   422  A test function is one named TestXxx (where Xxx does not start with a
   423  lower case letter) and should have the signature,
   424  
   425  	func TestXxx(t *testing.T) { ... }
   426  
   427  A benchmark function is one named BenchmarkXxx and should have the signature,
   428  
   429  	func BenchmarkXxx(b *testing.B) { ... }
   430  
   431  An example function is similar to a test function but, instead of using
   432  *testing.T to report success or failure, prints output to os.Stdout.
   433  If the last comment in the function starts with "Output:" then the output
   434  is compared exactly against the comment (see examples below). If the last
   435  comment begins with "Unordered output:" then the output is compared to the
   436  comment, however the order of the lines is ignored. An example with no such
   437  comment is compiled but not executed. An example with no text after
   438  "Output:" is compiled, executed, and expected to produce no output.
   439  
   440  Godoc displays the body of ExampleXxx to demonstrate the use
   441  of the function, constant, or variable Xxx. An example of a method M with
   442  receiver type T or *T is named ExampleT_M. There may be multiple examples
   443  for a given function, constant, or variable, distinguished by a trailing _xxx,
   444  where xxx is a suffix not beginning with an upper case letter.
   445  
   446  Here is an example of an example:
   447  
   448  	func ExamplePrintln() {
   449  		Println("The output of\nthis example.")
   450  		// Output: The output of
   451  		// this example.
   452  	}
   453  
   454  Here is another example where the ordering of the output is ignored:
   455  
   456  	func ExamplePerm() {
   457  		for _, value := range Perm(4) {
   458  			fmt.Println(value)
   459  		}
   460  
   461  		// Unordered output: 4
   462  		// 2
   463  		// 1
   464  		// 3
   465  		// 0
   466  	}
   467  
   468  The entire test file is presented as the example when it contains a single
   469  example function, at least one other function, type, variable, or constant
   470  declaration, and no test or benchmark functions.
   471  
   472  See the documentation of the testing package for more information.
   473  `,
   474  }
   475  
   476  var (
   477  	testC            bool            // -c flag
   478  	testCover        bool            // -cover flag
   479  	testCoverMode    string          // -covermode flag
   480  	testCoverPaths   []string        // -coverpkg flag
   481  	testCoverPkgs    []*load.Package // -coverpkg flag
   482  	testCoverProfile string          // -coverprofile flag
   483  	testOutputDir    string          // -outputdir flag
   484  	testO            string          // -o flag
   485  	testProfile      string          // profiling flag that limits test to one package
   486  	testNeedBinary   bool            // profile needs to keep binary around
   487  	testJSON         bool            // -json flag
   488  	testV            bool            // -v flag
   489  	testTimeout      string          // -timeout flag
   490  	testArgs         []string
   491  	testBench        bool
   492  	testList         bool
   493  	testShowPass     bool   // show passing output
   494  	testVetList      string // -vet flag
   495  	pkgArgs          []string
   496  	pkgs             []*load.Package
   497  
   498  	testKillTimeout = 10 * time.Minute
   499  	testCacheExpire time.Time // ignore cached test results before this time
   500  )
   501  
   502  var testMainDeps = []string{
   503  	// Dependencies for testmain.
   504  	"os",
   505  	"testing",
   506  	"testing/internal/testdeps",
   507  }
   508  
   509  // testVetFlags is the list of flags to pass to vet when invoked automatically during go test.
   510  var testVetFlags = []string{
   511  	// TODO(rsc): Decide which tests are enabled by default.
   512  	// See golang.org/issue/18085.
   513  	// "-asmdecl",
   514  	// "-assign",
   515  	"-atomic",
   516  	"-bool",
   517  	"-buildtags",
   518  	// "-cgocall",
   519  	// "-composites",
   520  	// "-copylocks",
   521  	// "-httpresponse",
   522  	// "-lostcancel",
   523  	// "-methods",
   524  	"-nilfunc",
   525  	"-printf",
   526  	// "-rangeloops",
   527  	// "-shift",
   528  	// "-structtags",
   529  	// "-tests",
   530  	// "-unreachable",
   531  	// "-unsafeptr",
   532  	// "-unusedresult",
   533  }
   534  
   535  func runTest(cmd *base.Command, args []string) {
   536  	pkgArgs, testArgs = testFlags(args)
   537  
   538  	work.FindExecCmd() // initialize cached result
   539  
   540  	work.BuildInit()
   541  	work.VetFlags = testVetFlags
   542  
   543  	pkgs = load.PackagesForBuild(pkgArgs)
   544  	if len(pkgs) == 0 {
   545  		base.Fatalf("no packages to test")
   546  	}
   547  
   548  	if testC && len(pkgs) != 1 {
   549  		base.Fatalf("cannot use -c flag with multiple packages")
   550  	}
   551  	if testO != "" && len(pkgs) != 1 {
   552  		base.Fatalf("cannot use -o flag with multiple packages")
   553  	}
   554  	if testProfile != "" && len(pkgs) != 1 {
   555  		base.Fatalf("cannot use %s flag with multiple packages", testProfile)
   556  	}
   557  	initCoverProfile()
   558  	defer closeCoverProfile()
   559  
   560  	// If a test timeout was given and is parseable, set our kill timeout
   561  	// to that timeout plus one minute. This is a backup alarm in case
   562  	// the test wedges with a goroutine spinning and its background
   563  	// timer does not get a chance to fire.
   564  	if dt, err := time.ParseDuration(testTimeout); err == nil && dt > 0 {
   565  		testKillTimeout = dt + 1*time.Minute
   566  	} else if err == nil && dt == 0 {
   567  		// An explicit zero disables the test timeout.
   568  		// Let it have one century (almost) before we kill it.
   569  		testKillTimeout = 100 * 365 * 24 * time.Hour
   570  	}
   571  
   572  	// show passing test output (after buffering) with -v flag.
   573  	// must buffer because tests are running in parallel, and
   574  	// otherwise the output will get mixed.
   575  	testShowPass = testV || testList
   576  
   577  	// For 'go test -i -o x.test', we want to build x.test. Imply -c to make the logic easier.
   578  	if cfg.BuildI && testO != "" {
   579  		testC = true
   580  	}
   581  
   582  	// Read testcache expiration time, if present.
   583  	// (We implement go clean -testcache by writing an expiration date
   584  	// instead of searching out and deleting test result cache entries.)
   585  	if dir := cache.DefaultDir(); dir != "off" {
   586  		if data, _ := ioutil.ReadFile(filepath.Join(dir, "testexpire.txt")); len(data) > 0 && data[len(data)-1] == '\n' {
   587  			if t, err := strconv.ParseInt(string(data[:len(data)-1]), 10, 64); err == nil {
   588  				testCacheExpire = time.Unix(0, t)
   589  			}
   590  		}
   591  	}
   592  
   593  	var b work.Builder
   594  	b.Init()
   595  
   596  	if cfg.BuildI {
   597  		cfg.BuildV = testV
   598  
   599  		deps := make(map[string]bool)
   600  		for _, dep := range testMainDeps {
   601  			deps[dep] = true
   602  		}
   603  
   604  		for _, p := range pkgs {
   605  			// Dependencies for each test.
   606  			for _, path := range p.Imports {
   607  				deps[path] = true
   608  			}
   609  			for _, path := range p.Resolve(p.TestImports) {
   610  				deps[path] = true
   611  			}
   612  			for _, path := range p.Resolve(p.XTestImports) {
   613  				deps[path] = true
   614  			}
   615  		}
   616  
   617  		// translate C to runtime/cgo
   618  		if deps["C"] {
   619  			delete(deps, "C")
   620  			deps["runtime/cgo"] = true
   621  		}
   622  		// Ignore pseudo-packages.
   623  		delete(deps, "unsafe")
   624  
   625  		all := []string{}
   626  		for path := range deps {
   627  			if !build.IsLocalImport(path) {
   628  				all = append(all, path)
   629  			}
   630  		}
   631  		sort.Strings(all)
   632  
   633  		a := &work.Action{Mode: "go test -i"}
   634  		for _, p := range load.PackagesForBuild(all) {
   635  			a.Deps = append(a.Deps, b.CompileAction(work.ModeInstall, work.ModeInstall, p))
   636  		}
   637  		b.Do(a)
   638  		if !testC || a.Failed {
   639  			return
   640  		}
   641  		b.Init()
   642  	}
   643  
   644  	var builds, runs, prints []*work.Action
   645  
   646  	if testCoverPaths != nil {
   647  		match := make([]func(*load.Package) bool, len(testCoverPaths))
   648  		matched := make([]bool, len(testCoverPaths))
   649  		for i := range testCoverPaths {
   650  			match[i] = load.MatchPackage(testCoverPaths[i], base.Cwd)
   651  		}
   652  
   653  		// Select for coverage all dependencies matching the testCoverPaths patterns.
   654  		for _, p := range load.PackageList(pkgs) {
   655  			haveMatch := false
   656  			for i := range testCoverPaths {
   657  				if match[i](p) {
   658  					matched[i] = true
   659  					haveMatch = true
   660  				}
   661  			}
   662  
   663  			// Silently ignore attempts to run coverage on
   664  			// sync/atomic when using atomic coverage mode.
   665  			// Atomic coverage mode uses sync/atomic, so
   666  			// we can't also do coverage on it.
   667  			if testCoverMode == "atomic" && p.Standard && p.ImportPath == "sync/atomic" {
   668  				continue
   669  			}
   670  
   671  			// If using the race detector, silently ignore
   672  			// attempts to run coverage on the runtime
   673  			// packages. It will cause the race detector
   674  			// to be invoked before it has been initialized.
   675  			if cfg.BuildRace && p.Standard && (p.ImportPath == "runtime" || strings.HasPrefix(p.ImportPath, "runtime/internal")) {
   676  				continue
   677  			}
   678  
   679  			if haveMatch {
   680  				testCoverPkgs = append(testCoverPkgs, p)
   681  			}
   682  		}
   683  
   684  		// Warn about -coverpkg arguments that are not actually used.
   685  		for i := range testCoverPaths {
   686  			if !matched[i] {
   687  				fmt.Fprintf(os.Stderr, "warning: no packages being tested depend on matches for pattern %s\n", testCoverPaths[i])
   688  			}
   689  		}
   690  
   691  		// Mark all the coverage packages for rebuilding with coverage.
   692  		for _, p := range testCoverPkgs {
   693  			// There is nothing to cover in package unsafe; it comes from the compiler.
   694  			if p.ImportPath == "unsafe" {
   695  				continue
   696  			}
   697  			p.Internal.CoverMode = testCoverMode
   698  			var coverFiles []string
   699  			coverFiles = append(coverFiles, p.GoFiles...)
   700  			coverFiles = append(coverFiles, p.CgoFiles...)
   701  			coverFiles = append(coverFiles, p.TestGoFiles...)
   702  			p.Internal.CoverVars = declareCoverVars(p.ImportPath, coverFiles...)
   703  			if testCover && testCoverMode == "atomic" {
   704  				ensureImport(p, "sync/atomic")
   705  			}
   706  		}
   707  	}
   708  
   709  	// Prepare build + run + print actions for all packages being tested.
   710  	for _, p := range pkgs {
   711  		// sync/atomic import is inserted by the cover tool. See #18486
   712  		if testCover && testCoverMode == "atomic" {
   713  			ensureImport(p, "sync/atomic")
   714  		}
   715  
   716  		buildTest, runTest, printTest, err := builderTest(&b, p)
   717  		if err != nil {
   718  			str := err.Error()
   719  			if strings.HasPrefix(str, "\n") {
   720  				str = str[1:]
   721  			}
   722  			failed := fmt.Sprintf("FAIL\t%s [setup failed]\n", p.ImportPath)
   723  
   724  			if p.ImportPath != "" {
   725  				base.Errorf("# %s\n%s\n%s", p.ImportPath, str, failed)
   726  			} else {
   727  				base.Errorf("%s\n%s", str, failed)
   728  			}
   729  			continue
   730  		}
   731  		builds = append(builds, buildTest)
   732  		runs = append(runs, runTest)
   733  		prints = append(prints, printTest)
   734  	}
   735  
   736  	// Ultimately the goal is to print the output.
   737  	root := &work.Action{Mode: "go test", Deps: prints}
   738  
   739  	// Force the printing of results to happen in order,
   740  	// one at a time.
   741  	for i, a := range prints {
   742  		if i > 0 {
   743  			a.Deps = append(a.Deps, prints[i-1])
   744  		}
   745  	}
   746  
   747  	// Force benchmarks to run in serial.
   748  	if !testC && testBench {
   749  		// The first run must wait for all builds.
   750  		// Later runs must wait for the previous run's print.
   751  		for i, run := range runs {
   752  			if i == 0 {
   753  				run.Deps = append(run.Deps, builds...)
   754  			} else {
   755  				run.Deps = append(run.Deps, prints[i-1])
   756  			}
   757  		}
   758  	}
   759  
   760  	b.Do(root)
   761  }
   762  
   763  // ensures that package p imports the named package
   764  func ensureImport(p *load.Package, pkg string) {
   765  	for _, d := range p.Internal.Imports {
   766  		if d.Name == pkg {
   767  			return
   768  		}
   769  	}
   770  
   771  	p1 := load.LoadPackage(pkg, &load.ImportStack{})
   772  	if p1.Error != nil {
   773  		base.Fatalf("load %s: %v", pkg, p1.Error)
   774  	}
   775  
   776  	p.Internal.Imports = append(p.Internal.Imports, p1)
   777  }
   778  
   779  var windowsBadWords = []string{
   780  	"install",
   781  	"patch",
   782  	"setup",
   783  	"update",
   784  }
   785  
   786  func builderTest(b *work.Builder, p *load.Package) (buildAction, runAction, printAction *work.Action, err error) {
   787  	if len(p.TestGoFiles)+len(p.XTestGoFiles) == 0 {
   788  		build := b.CompileAction(work.ModeBuild, work.ModeBuild, p)
   789  		run := &work.Action{Mode: "test run", Package: p, Deps: []*work.Action{build}}
   790  		addTestVet(b, p, run, nil)
   791  		print := &work.Action{Mode: "test print", Func: builderNoTest, Package: p, Deps: []*work.Action{run}}
   792  		return build, run, print, nil
   793  	}
   794  
   795  	// Build Package structs describing:
   796  	//	ptest - package + test files
   797  	//	pxtest - package of external test files
   798  	//	pmain - pkg.test binary
   799  	var ptest, pxtest, pmain *load.Package
   800  
   801  	localCover := testCover && testCoverPaths == nil
   802  
   803  	ptest, pxtest, err = load.TestPackagesFor(p, localCover || p.Name == "main")
   804  	if err != nil {
   805  		return nil, nil, nil, err
   806  	}
   807  
   808  	// Use last element of import path, not package name.
   809  	// They differ when package name is "main".
   810  	// But if the import path is "command-line-arguments",
   811  	// like it is during 'go run', use the package name.
   812  	var elem string
   813  	if p.ImportPath == "command-line-arguments" {
   814  		elem = p.Name
   815  	} else {
   816  		_, elem = path.Split(p.ImportPath)
   817  	}
   818  	testBinary := elem + ".test"
   819  
   820  	// Should we apply coverage analysis locally,
   821  	// only for this package and only for this test?
   822  	// Yes, if -cover is on but -coverpkg has not specified
   823  	// a list of packages for global coverage.
   824  	if localCover {
   825  		ptest.Internal.CoverMode = testCoverMode
   826  		var coverFiles []string
   827  		coverFiles = append(coverFiles, ptest.GoFiles...)
   828  		coverFiles = append(coverFiles, ptest.CgoFiles...)
   829  		ptest.Internal.CoverVars = declareCoverVars(ptest.ImportPath, coverFiles...)
   830  	}
   831  
   832  	testDir := b.NewObjdir()
   833  	if err := b.Mkdir(testDir); err != nil {
   834  		return nil, nil, nil, err
   835  	}
   836  
   837  	// Action for building pkg.test.
   838  	pmain = &load.Package{
   839  		PackagePublic: load.PackagePublic{
   840  			Name:       "main",
   841  			Dir:        testDir,
   842  			GoFiles:    []string{"_testmain.go"},
   843  			ImportPath: p.ImportPath + " (testmain)",
   844  			Root:       p.Root,
   845  		},
   846  		Internal: load.PackageInternal{
   847  			Build:     &build.Package{Name: "main"},
   848  			OmitDebug: !testC && !testNeedBinary,
   849  
   850  			Asmflags:   p.Internal.Asmflags,
   851  			Gcflags:    p.Internal.Gcflags,
   852  			Ldflags:    p.Internal.Ldflags,
   853  			Gccgoflags: p.Internal.Gccgoflags,
   854  		},
   855  	}
   856  
   857  	// The generated main also imports testing, regexp, and os.
   858  	// Also the linker introduces implicit dependencies reported by LinkerDeps.
   859  	var stk load.ImportStack
   860  	stk.Push("testmain")
   861  	deps := testMainDeps // cap==len, so safe for append
   862  	for _, d := range load.LinkerDeps(p) {
   863  		deps = append(deps, d)
   864  	}
   865  	for _, dep := range deps {
   866  		if dep == ptest.ImportPath {
   867  			pmain.Internal.Imports = append(pmain.Internal.Imports, ptest)
   868  		} else {
   869  			p1 := load.LoadImport(dep, "", nil, &stk, nil, 0)
   870  			if p1.Error != nil {
   871  				return nil, nil, nil, p1.Error
   872  			}
   873  			pmain.Internal.Imports = append(pmain.Internal.Imports, p1)
   874  		}
   875  	}
   876  
   877  	if testCoverPkgs != nil {
   878  		// Add imports, but avoid duplicates.
   879  		seen := map[*load.Package]bool{p: true, ptest: true}
   880  		for _, p1 := range pmain.Internal.Imports {
   881  			seen[p1] = true
   882  		}
   883  		for _, p1 := range testCoverPkgs {
   884  			if !seen[p1] {
   885  				seen[p1] = true
   886  				pmain.Internal.Imports = append(pmain.Internal.Imports, p1)
   887  			}
   888  		}
   889  	}
   890  
   891  	// Do initial scan for metadata needed for writing _testmain.go
   892  	// Use that metadata to update the list of imports for package main.
   893  	// The list of imports is used by recompileForTest and by the loop
   894  	// afterward that gathers t.Cover information.
   895  	t, err := loadTestFuncs(ptest)
   896  	if err != nil {
   897  		return nil, nil, nil, err
   898  	}
   899  	if len(ptest.GoFiles)+len(ptest.CgoFiles) > 0 {
   900  		pmain.Internal.Imports = append(pmain.Internal.Imports, ptest)
   901  		t.ImportTest = true
   902  	}
   903  	if pxtest != nil {
   904  		pmain.Internal.Imports = append(pmain.Internal.Imports, pxtest)
   905  		t.ImportXtest = true
   906  	}
   907  
   908  	if ptest != p {
   909  		// We have made modifications to the package p being tested
   910  		// and are rebuilding p (as ptest).
   911  		// Arrange to rebuild all packages q such that
   912  		// the test depends on q and q depends on p.
   913  		// This makes sure that q sees the modifications to p.
   914  		// Strictly speaking, the rebuild is only necessary if the
   915  		// modifications to p change its export metadata, but
   916  		// determining that is a bit tricky, so we rebuild always.
   917  		recompileForTest(pmain, p, ptest, pxtest)
   918  	}
   919  
   920  	for _, cp := range pmain.Internal.Imports {
   921  		if len(cp.Internal.CoverVars) > 0 {
   922  			t.Cover = append(t.Cover, coverInfo{cp, cp.Internal.CoverVars})
   923  		}
   924  	}
   925  
   926  	if !cfg.BuildN {
   927  		// writeTestmain writes _testmain.go,
   928  		// using the test description gathered in t.
   929  		if err := writeTestmain(testDir+"_testmain.go", t); err != nil {
   930  			return nil, nil, nil, err
   931  		}
   932  	}
   933  
   934  	// Set compile objdir to testDir we've already created,
   935  	// so that the default file path stripping applies to _testmain.go.
   936  	b.CompileAction(work.ModeBuild, work.ModeBuild, pmain).Objdir = testDir
   937  
   938  	a := b.LinkAction(work.ModeBuild, work.ModeBuild, pmain)
   939  	a.Target = testDir + testBinary + cfg.ExeSuffix
   940  	if cfg.Goos == "windows" {
   941  		// There are many reserved words on Windows that,
   942  		// if used in the name of an executable, cause Windows
   943  		// to try to ask for extra permissions.
   944  		// The word list includes setup, install, update, and patch,
   945  		// but it does not appear to be defined anywhere.
   946  		// We have run into this trying to run the
   947  		// go.codereview/patch tests.
   948  		// For package names containing those words, use test.test.exe
   949  		// instead of pkgname.test.exe.
   950  		// Note that this file name is only used in the Go command's
   951  		// temporary directory. If the -c or other flags are
   952  		// given, the code below will still use pkgname.test.exe.
   953  		// There are two user-visible effects of this change.
   954  		// First, you can actually run 'go test' in directories that
   955  		// have names that Windows thinks are installer-like,
   956  		// without getting a dialog box asking for more permissions.
   957  		// Second, in the Windows process listing during go test,
   958  		// the test shows up as test.test.exe, not pkgname.test.exe.
   959  		// That second one is a drawback, but it seems a small
   960  		// price to pay for the test running at all.
   961  		// If maintaining the list of bad words is too onerous,
   962  		// we could just do this always on Windows.
   963  		for _, bad := range windowsBadWords {
   964  			if strings.Contains(testBinary, bad) {
   965  				a.Target = testDir + "test.test" + cfg.ExeSuffix
   966  				break
   967  			}
   968  		}
   969  	}
   970  	buildAction = a
   971  	var installAction, cleanAction *work.Action
   972  	if testC || testNeedBinary {
   973  		// -c or profiling flag: create action to copy binary to ./test.out.
   974  		target := filepath.Join(base.Cwd, testBinary+cfg.ExeSuffix)
   975  		if testO != "" {
   976  			target = testO
   977  			if !filepath.IsAbs(target) {
   978  				target = filepath.Join(base.Cwd, target)
   979  			}
   980  		}
   981  		pmain.Target = target
   982  		installAction = &work.Action{
   983  			Mode:    "test build",
   984  			Func:    work.BuildInstallFunc,
   985  			Deps:    []*work.Action{buildAction},
   986  			Package: pmain,
   987  			Target:  target,
   988  		}
   989  		runAction = installAction // make sure runAction != nil even if not running test
   990  	}
   991  	if testC {
   992  		printAction = &work.Action{Mode: "test print (nop)", Package: p, Deps: []*work.Action{runAction}} // nop
   993  	} else {
   994  		// run test
   995  		c := new(runCache)
   996  		runAction = &work.Action{
   997  			Mode:       "test run",
   998  			Func:       c.builderRunTest,
   999  			Deps:       []*work.Action{buildAction},
  1000  			Package:    p,
  1001  			IgnoreFail: true, // run (prepare output) even if build failed
  1002  			TryCache:   c.tryCache,
  1003  			Objdir:     testDir,
  1004  		}
  1005  		if len(ptest.GoFiles)+len(ptest.CgoFiles) > 0 {
  1006  			addTestVet(b, ptest, runAction, installAction)
  1007  		}
  1008  		if pxtest != nil {
  1009  			addTestVet(b, pxtest, runAction, installAction)
  1010  		}
  1011  		cleanAction = &work.Action{
  1012  			Mode:       "test clean",
  1013  			Func:       builderCleanTest,
  1014  			Deps:       []*work.Action{runAction},
  1015  			Package:    p,
  1016  			IgnoreFail: true, // clean even if test failed
  1017  			Objdir:     testDir,
  1018  		}
  1019  		printAction = &work.Action{
  1020  			Mode:       "test print",
  1021  			Func:       builderPrintTest,
  1022  			Deps:       []*work.Action{cleanAction},
  1023  			Package:    p,
  1024  			IgnoreFail: true, // print even if test failed
  1025  		}
  1026  	}
  1027  	if installAction != nil {
  1028  		if runAction != installAction {
  1029  			installAction.Deps = append(installAction.Deps, runAction)
  1030  		}
  1031  		if cleanAction != nil {
  1032  			cleanAction.Deps = append(cleanAction.Deps, installAction)
  1033  		}
  1034  	}
  1035  
  1036  	return buildAction, runAction, printAction, nil
  1037  }
  1038  
  1039  func addTestVet(b *work.Builder, p *load.Package, runAction, installAction *work.Action) {
  1040  	if testVetList == "off" {
  1041  		return
  1042  	}
  1043  
  1044  	vet := b.VetAction(work.ModeBuild, work.ModeBuild, p)
  1045  	runAction.Deps = append(runAction.Deps, vet)
  1046  	// Install will clean the build directory.
  1047  	// Make sure vet runs first.
  1048  	// The install ordering in b.VetAction does not apply here
  1049  	// because we are using a custom installAction (created above).
  1050  	if installAction != nil {
  1051  		installAction.Deps = append(installAction.Deps, vet)
  1052  	}
  1053  }
  1054  
  1055  func recompileForTest(pmain, preal, ptest, pxtest *load.Package) {
  1056  	// The "test copy" of preal is ptest.
  1057  	// For each package that depends on preal, make a "test copy"
  1058  	// that depends on ptest. And so on, up the dependency tree.
  1059  	testCopy := map[*load.Package]*load.Package{preal: ptest}
  1060  	for _, p := range load.PackageList([]*load.Package{pmain}) {
  1061  		if p == preal {
  1062  			continue
  1063  		}
  1064  		// Copy on write.
  1065  		didSplit := p == pmain || p == pxtest
  1066  		split := func() {
  1067  			if didSplit {
  1068  				return
  1069  			}
  1070  			didSplit = true
  1071  			if testCopy[p] != nil {
  1072  				panic("recompileForTest loop")
  1073  			}
  1074  			p1 := new(load.Package)
  1075  			testCopy[p] = p1
  1076  			*p1 = *p
  1077  			p1.Internal.Imports = make([]*load.Package, len(p.Internal.Imports))
  1078  			copy(p1.Internal.Imports, p.Internal.Imports)
  1079  			p = p1
  1080  			p.Target = ""
  1081  		}
  1082  
  1083  		// Update p.Internal.Imports to use test copies.
  1084  		for i, imp := range p.Internal.Imports {
  1085  			if p1 := testCopy[imp]; p1 != nil && p1 != imp {
  1086  				split()
  1087  				p.Internal.Imports[i] = p1
  1088  			}
  1089  		}
  1090  	}
  1091  }
  1092  
  1093  // isTestFile reports whether the source file is a set of tests and should therefore
  1094  // be excluded from coverage analysis.
  1095  func isTestFile(file string) bool {
  1096  	// We don't cover tests, only the code they test.
  1097  	return strings.HasSuffix(file, "_test.go")
  1098  }
  1099  
  1100  // declareCoverVars attaches the required cover variables names
  1101  // to the files, to be used when annotating the files.
  1102  func declareCoverVars(importPath string, files ...string) map[string]*load.CoverVar {
  1103  	coverVars := make(map[string]*load.CoverVar)
  1104  	coverIndex := 0
  1105  	// We create the cover counters as new top-level variables in the package.
  1106  	// We need to avoid collisions with user variables (GoCover_0 is unlikely but still)
  1107  	// and more importantly with dot imports of other covered packages,
  1108  	// so we append 12 hex digits from the SHA-256 of the import path.
  1109  	// The point is only to avoid accidents, not to defeat users determined to
  1110  	// break things.
  1111  	sum := sha256.Sum256([]byte(importPath))
  1112  	h := fmt.Sprintf("%x", sum[:6])
  1113  	for _, file := range files {
  1114  		if isTestFile(file) {
  1115  			continue
  1116  		}
  1117  		coverVars[file] = &load.CoverVar{
  1118  			File: filepath.Join(importPath, file),
  1119  			Var:  fmt.Sprintf("GoCover_%d_%x", coverIndex, h),
  1120  		}
  1121  		coverIndex++
  1122  	}
  1123  	return coverVars
  1124  }
  1125  
  1126  var noTestsToRun = []byte("\ntesting: warning: no tests to run\n")
  1127  
  1128  type runCache struct {
  1129  	disableCache bool // cache should be disabled for this run
  1130  
  1131  	buf *bytes.Buffer
  1132  	id1 cache.ActionID
  1133  	id2 cache.ActionID
  1134  }
  1135  
  1136  // stdoutMu and lockedStdout provide a locked standard output
  1137  // that guarantees never to interlace writes from multiple
  1138  // goroutines, so that we can have multiple JSON streams writing
  1139  // to a lockedStdout simultaneously and know that events will
  1140  // still be intelligible.
  1141  var stdoutMu sync.Mutex
  1142  
  1143  type lockedStdout struct{}
  1144  
  1145  func (lockedStdout) Write(b []byte) (int, error) {
  1146  	stdoutMu.Lock()
  1147  	defer stdoutMu.Unlock()
  1148  	return os.Stdout.Write(b)
  1149  }
  1150  
  1151  // builderRunTest is the action for running a test binary.
  1152  func (c *runCache) builderRunTest(b *work.Builder, a *work.Action) error {
  1153  	if a.Failed {
  1154  		// We were unable to build the binary.
  1155  		a.Failed = false
  1156  		a.TestOutput = new(bytes.Buffer)
  1157  		fmt.Fprintf(a.TestOutput, "FAIL\t%s [build failed]\n", a.Package.ImportPath)
  1158  		base.SetExitStatus(1)
  1159  		return nil
  1160  	}
  1161  
  1162  	var stdout io.Writer = os.Stdout
  1163  	if testJSON {
  1164  		json := test2json.NewConverter(lockedStdout{}, a.Package.ImportPath, test2json.Timestamp)
  1165  		defer json.Close()
  1166  		stdout = json
  1167  	}
  1168  
  1169  	var buf bytes.Buffer
  1170  	if len(pkgArgs) == 0 || testBench {
  1171  		// Stream test output (no buffering) when no package has
  1172  		// been given on the command line (implicit current directory)
  1173  		// or when benchmarking.
  1174  		// No change to stdout.
  1175  	} else {
  1176  		// If we're only running a single package under test or if parallelism is
  1177  		// set to 1, and if we're displaying all output (testShowPass), we can
  1178  		// hurry the output along, echoing it as soon as it comes in.
  1179  		// We still have to copy to &buf for caching the result. This special
  1180  		// case was introduced in Go 1.5 and is intentionally undocumented:
  1181  		// the exact details of output buffering are up to the go command and
  1182  		// subject to change. It would be nice to remove this special case
  1183  		// entirely, but it is surely very helpful to see progress being made
  1184  		// when tests are run on slow single-CPU ARM systems.
  1185  		//
  1186  		// If we're showing JSON output, then display output as soon as
  1187  		// possible even when multiple tests are being run: the JSON output
  1188  		// events are attributed to specific package tests, so interlacing them
  1189  		// is OK.
  1190  		if testShowPass && (len(pkgs) == 1 || cfg.BuildP == 1) || testJSON {
  1191  			// Write both to stdout and buf, for possible saving
  1192  			// to cache, and for looking for the "no tests to run" message.
  1193  			stdout = io.MultiWriter(stdout, &buf)
  1194  		} else {
  1195  			stdout = &buf
  1196  		}
  1197  	}
  1198  
  1199  	if c.buf == nil {
  1200  		// We did not find a cached result using the link step action ID,
  1201  		// so we ran the link step. Try again now with the link output
  1202  		// content ID. The attempt using the action ID makes sure that
  1203  		// if the link inputs don't change, we reuse the cached test
  1204  		// result without even rerunning the linker. The attempt using
  1205  		// the link output (test binary) content ID makes sure that if
  1206  		// we have different link inputs but the same final binary,
  1207  		// we still reuse the cached test result.
  1208  		// c.saveOutput will store the result under both IDs.
  1209  		c.tryCacheWithID(b, a, a.Deps[0].BuildContentID())
  1210  	}
  1211  	if c.buf != nil {
  1212  		if stdout != &buf {
  1213  			stdout.Write(c.buf.Bytes())
  1214  			c.buf.Reset()
  1215  		}
  1216  		a.TestOutput = c.buf
  1217  		return nil
  1218  	}
  1219  
  1220  	execCmd := work.FindExecCmd()
  1221  	testlogArg := []string{}
  1222  	if !c.disableCache && len(execCmd) == 0 {
  1223  		testlogArg = []string{"-test.testlogfile=" + a.Objdir + "testlog.txt"}
  1224  	}
  1225  	args := str.StringList(execCmd, a.Deps[0].BuiltTarget(), testlogArg, testArgs)
  1226  
  1227  	if testCoverProfile != "" {
  1228  		// Write coverage to temporary profile, for merging later.
  1229  		for i, arg := range args {
  1230  			if strings.HasPrefix(arg, "-test.coverprofile=") {
  1231  				args[i] = "-test.coverprofile=" + a.Objdir + "_cover_.out"
  1232  			}
  1233  		}
  1234  	}
  1235  
  1236  	if cfg.BuildN || cfg.BuildX {
  1237  		b.Showcmd("", "%s", strings.Join(args, " "))
  1238  		if cfg.BuildN {
  1239  			return nil
  1240  		}
  1241  	}
  1242  
  1243  	cmd := exec.Command(args[0], args[1:]...)
  1244  	cmd.Dir = a.Package.Dir
  1245  	cmd.Env = base.EnvForDir(cmd.Dir, cfg.OrigEnv)
  1246  	cmd.Stdout = stdout
  1247  	cmd.Stderr = stdout
  1248  
  1249  	// If there are any local SWIG dependencies, we want to load
  1250  	// the shared library from the build directory.
  1251  	if a.Package.UsesSwig() {
  1252  		env := cmd.Env
  1253  		found := false
  1254  		prefix := "LD_LIBRARY_PATH="
  1255  		for i, v := range env {
  1256  			if strings.HasPrefix(v, prefix) {
  1257  				env[i] = v + ":."
  1258  				found = true
  1259  				break
  1260  			}
  1261  		}
  1262  		if !found {
  1263  			env = append(env, "LD_LIBRARY_PATH=.")
  1264  		}
  1265  		cmd.Env = env
  1266  	}
  1267  
  1268  	t0 := time.Now()
  1269  	err := cmd.Start()
  1270  
  1271  	// This is a last-ditch deadline to detect and
  1272  	// stop wedged test binaries, to keep the builders
  1273  	// running.
  1274  	if err == nil {
  1275  		tick := time.NewTimer(testKillTimeout)
  1276  		base.StartSigHandlers()
  1277  		done := make(chan error)
  1278  		go func() {
  1279  			done <- cmd.Wait()
  1280  		}()
  1281  	Outer:
  1282  		select {
  1283  		case err = <-done:
  1284  			// ok
  1285  		case <-tick.C:
  1286  			if base.SignalTrace != nil {
  1287  				// Send a quit signal in the hope that the program will print
  1288  				// a stack trace and exit. Give it five seconds before resorting
  1289  				// to Kill.
  1290  				cmd.Process.Signal(base.SignalTrace)
  1291  				select {
  1292  				case err = <-done:
  1293  					fmt.Fprintf(cmd.Stdout, "*** Test killed with %v: ran too long (%v).\n", base.SignalTrace, testKillTimeout)
  1294  					break Outer
  1295  				case <-time.After(5 * time.Second):
  1296  				}
  1297  			}
  1298  			cmd.Process.Kill()
  1299  			err = <-done
  1300  			fmt.Fprintf(cmd.Stdout, "*** Test killed: ran too long (%v).\n", testKillTimeout)
  1301  		}
  1302  		tick.Stop()
  1303  	}
  1304  	out := buf.Bytes()
  1305  	a.TestOutput = &buf
  1306  	t := fmt.Sprintf("%.3fs", time.Since(t0).Seconds())
  1307  
  1308  	mergeCoverProfile(cmd.Stdout, a.Objdir+"_cover_.out")
  1309  
  1310  	if err == nil {
  1311  		norun := ""
  1312  		if !testShowPass && !testJSON {
  1313  			buf.Reset()
  1314  		}
  1315  		if bytes.HasPrefix(out, noTestsToRun[1:]) || bytes.Contains(out, noTestsToRun) {
  1316  			norun = " [no tests to run]"
  1317  		}
  1318  		fmt.Fprintf(cmd.Stdout, "ok  \t%s\t%s%s%s\n", a.Package.ImportPath, t, coveragePercentage(out), norun)
  1319  		c.saveOutput(a)
  1320  	} else {
  1321  		base.SetExitStatus(1)
  1322  		// If there was test output, assume we don't need to print the exit status.
  1323  		// Buf there's no test output, do print the exit status.
  1324  		if len(out) == 0 {
  1325  			fmt.Fprintf(cmd.Stdout, "%s\n", err)
  1326  		}
  1327  		fmt.Fprintf(cmd.Stdout, "FAIL\t%s\t%s\n", a.Package.ImportPath, t)
  1328  	}
  1329  
  1330  	if cmd.Stdout != &buf {
  1331  		buf.Reset() // cmd.Stdout was going to os.Stdout already
  1332  	}
  1333  	return nil
  1334  }
  1335  
  1336  // tryCache is called just before the link attempt,
  1337  // to see if the test result is cached and therefore the link is unneeded.
  1338  // It reports whether the result can be satisfied from cache.
  1339  func (c *runCache) tryCache(b *work.Builder, a *work.Action) bool {
  1340  	return c.tryCacheWithID(b, a, a.Deps[0].BuildActionID())
  1341  }
  1342  
  1343  func (c *runCache) tryCacheWithID(b *work.Builder, a *work.Action, id string) bool {
  1344  	if len(pkgArgs) == 0 {
  1345  		// Caching does not apply to "go test",
  1346  		// only to "go test foo" (including "go test .").
  1347  		if cache.DebugTest {
  1348  			fmt.Fprintf(os.Stderr, "testcache: caching disabled in local directory mode\n")
  1349  		}
  1350  		c.disableCache = true
  1351  		return false
  1352  	}
  1353  
  1354  	var cacheArgs []string
  1355  	for _, arg := range testArgs {
  1356  		i := strings.Index(arg, "=")
  1357  		if i < 0 || !strings.HasPrefix(arg, "-test.") {
  1358  			if cache.DebugTest {
  1359  				fmt.Fprintf(os.Stderr, "testcache: caching disabled for test argument: %s\n", arg)
  1360  			}
  1361  			c.disableCache = true
  1362  			return false
  1363  		}
  1364  		switch arg[:i] {
  1365  		case "-test.cpu",
  1366  			"-test.list",
  1367  			"-test.parallel",
  1368  			"-test.run",
  1369  			"-test.short",
  1370  			"-test.v":
  1371  			// These are cacheable.
  1372  			// Note that this list is documented above,
  1373  			// so if you add to this list, update the docs too.
  1374  			cacheArgs = append(cacheArgs, arg)
  1375  
  1376  		case "-test.timeout":
  1377  			// Special case: this is cacheable but ignored during the hash.
  1378  			// Do not add to cacheArgs.
  1379  
  1380  		default:
  1381  			// nothing else is cacheable
  1382  			if cache.DebugTest {
  1383  				fmt.Fprintf(os.Stderr, "testcache: caching disabled for test argument: %s\n", arg)
  1384  			}
  1385  			c.disableCache = true
  1386  			return false
  1387  		}
  1388  	}
  1389  
  1390  	if cache.Default() == nil {
  1391  		if cache.DebugTest {
  1392  			fmt.Fprintf(os.Stderr, "testcache: GOCACHE=off\n")
  1393  		}
  1394  		c.disableCache = true
  1395  		return false
  1396  	}
  1397  
  1398  	// The test cache result fetch is a two-level lookup.
  1399  	//
  1400  	// First, we use the content hash of the test binary
  1401  	// and its command-line arguments to find the
  1402  	// list of environment variables and files consulted
  1403  	// the last time the test was run with those arguments.
  1404  	// (To avoid unnecessary links, we store this entry
  1405  	// under two hashes: id1 uses the linker inputs as a
  1406  	// proxy for the test binary, and id2 uses the actual
  1407  	// test binary. If the linker inputs are unchanged,
  1408  	// this way we avoid the link step, even though we
  1409  	// do not cache link outputs.)
  1410  	//
  1411  	// Second, we compute a hash of the values of the
  1412  	// environment variables and the content of the files
  1413  	// listed in the log from the previous run.
  1414  	// Then we look up test output using a combination of
  1415  	// the hash from the first part (testID) and the hash of the
  1416  	// test inputs (testInputsID).
  1417  	//
  1418  	// In order to store a new test result, we must redo the
  1419  	// testInputsID computation using the log from the run
  1420  	// we want to cache, and then we store that new log and
  1421  	// the new outputs.
  1422  
  1423  	h := cache.NewHash("testResult")
  1424  	fmt.Fprintf(h, "test binary %s args %q execcmd %q", id, cacheArgs, work.ExecCmd)
  1425  	testID := h.Sum()
  1426  	if c.id1 == (cache.ActionID{}) {
  1427  		c.id1 = testID
  1428  	} else {
  1429  		c.id2 = testID
  1430  	}
  1431  	if cache.DebugTest {
  1432  		fmt.Fprintf(os.Stderr, "testcache: %s: test ID %x => %x\n", a.Package.ImportPath, id, testID)
  1433  	}
  1434  
  1435  	// Load list of referenced environment variables and files
  1436  	// from last run of testID, and compute hash of that content.
  1437  	data, entry, err := cache.Default().GetBytes(testID)
  1438  	if !bytes.HasPrefix(data, testlogMagic) || data[len(data)-1] != '\n' {
  1439  		if cache.DebugTest {
  1440  			if err != nil {
  1441  				fmt.Fprintf(os.Stderr, "testcache: %s: input list not found: %v\n", a.Package.ImportPath, err)
  1442  			} else {
  1443  				fmt.Fprintf(os.Stderr, "testcache: %s: input list malformed\n", a.Package.ImportPath)
  1444  			}
  1445  		}
  1446  		return false
  1447  	}
  1448  	testInputsID, err := computeTestInputsID(a, data)
  1449  	if err != nil {
  1450  		return false
  1451  	}
  1452  	if cache.DebugTest {
  1453  		fmt.Fprintf(os.Stderr, "testcache: %s: test ID %x => input ID %x => %x\n", a.Package.ImportPath, testID, testInputsID, testAndInputKey(testID, testInputsID))
  1454  	}
  1455  
  1456  	// Parse cached result in preparation for changing run time to "(cached)".
  1457  	// If we can't parse the cached result, don't use it.
  1458  	data, entry, err = cache.Default().GetBytes(testAndInputKey(testID, testInputsID))
  1459  	if len(data) == 0 || data[len(data)-1] != '\n' {
  1460  		if cache.DebugTest {
  1461  			if err != nil {
  1462  				fmt.Fprintf(os.Stderr, "testcache: %s: test output not found: %v\n", a.Package.ImportPath, err)
  1463  			} else {
  1464  				fmt.Fprintf(os.Stderr, "testcache: %s: test output malformed\n", a.Package.ImportPath)
  1465  			}
  1466  		}
  1467  		return false
  1468  	}
  1469  	if entry.Time.Before(testCacheExpire) {
  1470  		if cache.DebugTest {
  1471  			fmt.Fprintf(os.Stderr, "testcache: %s: test output expired due to go clean -testcache\n", a.Package.ImportPath)
  1472  		}
  1473  		return false
  1474  	}
  1475  	i := bytes.LastIndexByte(data[:len(data)-1], '\n') + 1
  1476  	if !bytes.HasPrefix(data[i:], []byte("ok  \t")) {
  1477  		if cache.DebugTest {
  1478  			fmt.Fprintf(os.Stderr, "testcache: %s: test output malformed\n", a.Package.ImportPath)
  1479  		}
  1480  		return false
  1481  	}
  1482  	j := bytes.IndexByte(data[i+len("ok  \t"):], '\t')
  1483  	if j < 0 {
  1484  		if cache.DebugTest {
  1485  			fmt.Fprintf(os.Stderr, "testcache: %s: test output malformed\n", a.Package.ImportPath)
  1486  		}
  1487  		return false
  1488  	}
  1489  	j += i + len("ok  \t") + 1
  1490  
  1491  	// Committed to printing.
  1492  	c.buf = new(bytes.Buffer)
  1493  	c.buf.Write(data[:j])
  1494  	c.buf.WriteString("(cached)")
  1495  	for j < len(data) && ('0' <= data[j] && data[j] <= '9' || data[j] == '.' || data[j] == 's') {
  1496  		j++
  1497  	}
  1498  	c.buf.Write(data[j:])
  1499  	return true
  1500  }
  1501  
  1502  var errBadTestInputs = errors.New("error parsing test inputs")
  1503  var testlogMagic = []byte("# test log\n") // known to testing/internal/testdeps/deps.go
  1504  
  1505  // computeTestInputsID computes the "test inputs ID"
  1506  // (see comment in tryCacheWithID above) for the
  1507  // test log.
  1508  func computeTestInputsID(a *work.Action, testlog []byte) (cache.ActionID, error) {
  1509  	testlog = bytes.TrimPrefix(testlog, testlogMagic)
  1510  	h := cache.NewHash("testInputs")
  1511  	pwd := a.Package.Dir
  1512  	for _, line := range bytes.Split(testlog, []byte("\n")) {
  1513  		if len(line) == 0 {
  1514  			continue
  1515  		}
  1516  		s := string(line)
  1517  		i := strings.Index(s, " ")
  1518  		if i < 0 {
  1519  			if cache.DebugTest {
  1520  				fmt.Fprintf(os.Stderr, "testcache: %s: input list malformed (%q)\n", a.Package.ImportPath, line)
  1521  			}
  1522  			return cache.ActionID{}, errBadTestInputs
  1523  		}
  1524  		op := s[:i]
  1525  		name := s[i+1:]
  1526  		switch op {
  1527  		default:
  1528  			if cache.DebugTest {
  1529  				fmt.Fprintf(os.Stderr, "testcache: %s: input list malformed (%q)\n", a.Package.ImportPath, line)
  1530  			}
  1531  			return cache.ActionID{}, errBadTestInputs
  1532  		case "getenv":
  1533  			fmt.Fprintf(h, "env %s %x\n", name, hashGetenv(name))
  1534  		case "chdir":
  1535  			pwd = name // always absolute
  1536  			fmt.Fprintf(h, "cbdir %s %x\n", name, hashStat(name))
  1537  		case "stat":
  1538  			if !filepath.IsAbs(name) {
  1539  				name = filepath.Join(pwd, name)
  1540  			}
  1541  			if !inDir(name, a.Package.Root) {
  1542  				// Do not recheck files outside the GOPATH or GOROOT root.
  1543  				break
  1544  			}
  1545  			fmt.Fprintf(h, "stat %s %x\n", name, hashStat(name))
  1546  		case "open":
  1547  			if !filepath.IsAbs(name) {
  1548  				name = filepath.Join(pwd, name)
  1549  			}
  1550  			if !inDir(name, a.Package.Root) {
  1551  				// Do not recheck files outside the GOPATH or GOROOT root.
  1552  				break
  1553  			}
  1554  			fh, err := hashOpen(name)
  1555  			if err != nil {
  1556  				if cache.DebugTest {
  1557  					fmt.Fprintf(os.Stderr, "testcache: %s: input file %s: %s\n", a.Package.ImportPath, name, err)
  1558  				}
  1559  				return cache.ActionID{}, err
  1560  			}
  1561  			fmt.Fprintf(h, "open %s %x\n", name, fh)
  1562  		}
  1563  	}
  1564  	sum := h.Sum()
  1565  	return sum, nil
  1566  }
  1567  
  1568  func inDir(path, dir string) bool {
  1569  	if str.HasFilePathPrefix(path, dir) {
  1570  		return true
  1571  	}
  1572  	xpath, err1 := filepath.EvalSymlinks(path)
  1573  	xdir, err2 := filepath.EvalSymlinks(dir)
  1574  	if err1 == nil && err2 == nil && str.HasFilePathPrefix(xpath, xdir) {
  1575  		return true
  1576  	}
  1577  	return false
  1578  }
  1579  
  1580  func hashGetenv(name string) cache.ActionID {
  1581  	h := cache.NewHash("getenv")
  1582  	v, ok := os.LookupEnv(name)
  1583  	if !ok {
  1584  		h.Write([]byte{0})
  1585  	} else {
  1586  		h.Write([]byte{1})
  1587  		h.Write([]byte(v))
  1588  	}
  1589  	return h.Sum()
  1590  }
  1591  
  1592  const modTimeCutoff = 2 * time.Second
  1593  
  1594  var errFileTooNew = errors.New("file used as input is too new")
  1595  
  1596  func hashOpen(name string) (cache.ActionID, error) {
  1597  	h := cache.NewHash("open")
  1598  	info, err := os.Stat(name)
  1599  	if err != nil {
  1600  		fmt.Fprintf(h, "err %v\n", err)
  1601  		return h.Sum(), nil
  1602  	}
  1603  	hashWriteStat(h, info)
  1604  	if info.IsDir() {
  1605  		names, err := ioutil.ReadDir(name)
  1606  		if err != nil {
  1607  			fmt.Fprintf(h, "err %v\n", err)
  1608  		}
  1609  		for _, f := range names {
  1610  			fmt.Fprintf(h, "file %s ", f.Name())
  1611  			hashWriteStat(h, f)
  1612  		}
  1613  	} else if info.Mode().IsRegular() {
  1614  		// Because files might be very large, do not attempt
  1615  		// to hash the entirety of their content. Instead assume
  1616  		// the mtime and size recorded in hashWriteStat above
  1617  		// are good enough.
  1618  		//
  1619  		// To avoid problems for very recent files where a new
  1620  		// write might not change the mtime due to file system
  1621  		// mtime precision, reject caching if a file was read that
  1622  		// is less than modTimeCutoff old.
  1623  		if time.Since(info.ModTime()) < modTimeCutoff {
  1624  			return cache.ActionID{}, errFileTooNew
  1625  		}
  1626  	}
  1627  	return h.Sum(), nil
  1628  }
  1629  
  1630  func hashStat(name string) cache.ActionID {
  1631  	h := cache.NewHash("stat")
  1632  	if info, err := os.Stat(name); err != nil {
  1633  		fmt.Fprintf(h, "err %v\n", err)
  1634  	} else {
  1635  		hashWriteStat(h, info)
  1636  	}
  1637  	if info, err := os.Lstat(name); err != nil {
  1638  		fmt.Fprintf(h, "err %v\n", err)
  1639  	} else {
  1640  		hashWriteStat(h, info)
  1641  	}
  1642  	return h.Sum()
  1643  }
  1644  
  1645  func hashWriteStat(h io.Writer, info os.FileInfo) {
  1646  	fmt.Fprintf(h, "stat %d %x %v %v\n", info.Size(), uint64(info.Mode()), info.ModTime(), info.IsDir())
  1647  }
  1648  
  1649  // testAndInputKey returns the actual cache key for the pair (testID, testInputsID).
  1650  func testAndInputKey(testID, testInputsID cache.ActionID) cache.ActionID {
  1651  	return cache.Subkey(testID, fmt.Sprintf("inputs:%x", testInputsID))
  1652  }
  1653  
  1654  func (c *runCache) saveOutput(a *work.Action) {
  1655  	if c.id1 == (cache.ActionID{}) && c.id2 == (cache.ActionID{}) {
  1656  		return
  1657  	}
  1658  
  1659  	// See comment about two-level lookup in tryCacheWithID above.
  1660  	testlog, err := ioutil.ReadFile(a.Objdir + "testlog.txt")
  1661  	if err != nil || !bytes.HasPrefix(testlog, testlogMagic) || testlog[len(testlog)-1] != '\n' {
  1662  		if cache.DebugTest {
  1663  			if err != nil {
  1664  				fmt.Fprintf(os.Stderr, "testcache: %s: reading testlog: %v\n", a.Package.ImportPath, err)
  1665  			} else {
  1666  				fmt.Fprintf(os.Stderr, "testcache: %s: reading testlog: malformed\n", a.Package.ImportPath)
  1667  			}
  1668  		}
  1669  		return
  1670  	}
  1671  	testInputsID, err := computeTestInputsID(a, testlog)
  1672  	if err != nil {
  1673  		return
  1674  	}
  1675  	if c.id1 != (cache.ActionID{}) {
  1676  		if cache.DebugTest {
  1677  			fmt.Fprintf(os.Stderr, "testcache: %s: save test ID %x => input ID %x => %x\n", a.Package.ImportPath, c.id1, testInputsID, testAndInputKey(c.id1, testInputsID))
  1678  		}
  1679  		cache.Default().PutNoVerify(c.id1, bytes.NewReader(testlog))
  1680  		cache.Default().PutNoVerify(testAndInputKey(c.id1, testInputsID), bytes.NewReader(a.TestOutput.Bytes()))
  1681  	}
  1682  	if c.id2 != (cache.ActionID{}) {
  1683  		if cache.DebugTest {
  1684  			fmt.Fprintf(os.Stderr, "testcache: %s: save test ID %x => input ID %x => %x\n", a.Package.ImportPath, c.id2, testInputsID, testAndInputKey(c.id2, testInputsID))
  1685  		}
  1686  		cache.Default().PutNoVerify(c.id2, bytes.NewReader(testlog))
  1687  		cache.Default().PutNoVerify(testAndInputKey(c.id2, testInputsID), bytes.NewReader(a.TestOutput.Bytes()))
  1688  	}
  1689  }
  1690  
  1691  // coveragePercentage returns the coverage results (if enabled) for the
  1692  // test. It uncovers the data by scanning the output from the test run.
  1693  func coveragePercentage(out []byte) string {
  1694  	if !testCover {
  1695  		return ""
  1696  	}
  1697  	// The string looks like
  1698  	//	test coverage for encoding/binary: 79.9% of statements
  1699  	// Extract the piece from the percentage to the end of the line.
  1700  	re := regexp.MustCompile(`coverage: (.*)\n`)
  1701  	matches := re.FindSubmatch(out)
  1702  	if matches == nil {
  1703  		// Probably running "go test -cover" not "go test -cover fmt".
  1704  		// The coverage output will appear in the output directly.
  1705  		return ""
  1706  	}
  1707  	return fmt.Sprintf("\tcoverage: %s", matches[1])
  1708  }
  1709  
  1710  // builderCleanTest is the action for cleaning up after a test.
  1711  func builderCleanTest(b *work.Builder, a *work.Action) error {
  1712  	if cfg.BuildWork {
  1713  		return nil
  1714  	}
  1715  	if cfg.BuildX {
  1716  		b.Showcmd("", "rm -r %s", a.Objdir)
  1717  	}
  1718  	os.RemoveAll(a.Objdir)
  1719  	return nil
  1720  }
  1721  
  1722  // builderPrintTest is the action for printing a test result.
  1723  func builderPrintTest(b *work.Builder, a *work.Action) error {
  1724  	clean := a.Deps[0]
  1725  	run := clean.Deps[0]
  1726  	if run.TestOutput != nil {
  1727  		os.Stdout.Write(run.TestOutput.Bytes())
  1728  		run.TestOutput = nil
  1729  	}
  1730  	return nil
  1731  }
  1732  
  1733  // builderNoTest is the action for testing a package with no test files.
  1734  func builderNoTest(b *work.Builder, a *work.Action) error {
  1735  	var stdout io.Writer = os.Stdout
  1736  	if testJSON {
  1737  		json := test2json.NewConverter(lockedStdout{}, a.Package.ImportPath, test2json.Timestamp)
  1738  		defer json.Close()
  1739  		stdout = json
  1740  	}
  1741  	fmt.Fprintf(stdout, "?   \t%s\t[no test files]\n", a.Package.ImportPath)
  1742  	return nil
  1743  }
  1744  
  1745  // isTestFunc tells whether fn has the type of a testing function. arg
  1746  // specifies the parameter type we look for: B, M or T.
  1747  func isTestFunc(fn *ast.FuncDecl, arg string) bool {
  1748  	if fn.Type.Results != nil && len(fn.Type.Results.List) > 0 ||
  1749  		fn.Type.Params.List == nil ||
  1750  		len(fn.Type.Params.List) != 1 ||
  1751  		len(fn.Type.Params.List[0].Names) > 1 {
  1752  		return false
  1753  	}
  1754  	ptr, ok := fn.Type.Params.List[0].Type.(*ast.StarExpr)
  1755  	if !ok {
  1756  		return false
  1757  	}
  1758  	// We can't easily check that the type is *testing.M
  1759  	// because we don't know how testing has been imported,
  1760  	// but at least check that it's *M or *something.M.
  1761  	// Same applies for B and T.
  1762  	if name, ok := ptr.X.(*ast.Ident); ok && name.Name == arg {
  1763  		return true
  1764  	}
  1765  	if sel, ok := ptr.X.(*ast.SelectorExpr); ok && sel.Sel.Name == arg {
  1766  		return true
  1767  	}
  1768  	return false
  1769  }
  1770  
  1771  // isTest tells whether name looks like a test (or benchmark, according to prefix).
  1772  // It is a Test (say) if there is a character after Test that is not a lower-case letter.
  1773  // We don't want TesticularCancer.
  1774  func isTest(name, prefix string) bool {
  1775  	if !strings.HasPrefix(name, prefix) {
  1776  		return false
  1777  	}
  1778  	if len(name) == len(prefix) { // "Test" is ok
  1779  		return true
  1780  	}
  1781  	rune, _ := utf8.DecodeRuneInString(name[len(prefix):])
  1782  	return !unicode.IsLower(rune)
  1783  }
  1784  
  1785  type coverInfo struct {
  1786  	Package *load.Package
  1787  	Vars    map[string]*load.CoverVar
  1788  }
  1789  
  1790  // loadTestFuncs returns the testFuncs describing the tests that will be run.
  1791  func loadTestFuncs(ptest *load.Package) (*testFuncs, error) {
  1792  	t := &testFuncs{
  1793  		Package: ptest,
  1794  	}
  1795  	for _, file := range ptest.TestGoFiles {
  1796  		if err := t.load(filepath.Join(ptest.Dir, file), "_test", &t.ImportTest, &t.NeedTest); err != nil {
  1797  			return nil, err
  1798  		}
  1799  	}
  1800  	for _, file := range ptest.XTestGoFiles {
  1801  		if err := t.load(filepath.Join(ptest.Dir, file), "_xtest", &t.ImportXtest, &t.NeedXtest); err != nil {
  1802  			return nil, err
  1803  		}
  1804  	}
  1805  	return t, nil
  1806  }
  1807  
  1808  // writeTestmain writes the _testmain.go file for t to the file named out.
  1809  func writeTestmain(out string, t *testFuncs) error {
  1810  	f, err := os.Create(out)
  1811  	if err != nil {
  1812  		return err
  1813  	}
  1814  	defer f.Close()
  1815  
  1816  	if err := testmainTmpl.Execute(f, t); err != nil {
  1817  		return err
  1818  	}
  1819  
  1820  	return nil
  1821  }
  1822  
  1823  type testFuncs struct {
  1824  	Tests       []testFunc
  1825  	Benchmarks  []testFunc
  1826  	Examples    []testFunc
  1827  	TestMain    *testFunc
  1828  	Package     *load.Package
  1829  	ImportTest  bool
  1830  	NeedTest    bool
  1831  	ImportXtest bool
  1832  	NeedXtest   bool
  1833  	Cover       []coverInfo
  1834  }
  1835  
  1836  func (t *testFuncs) CoverMode() string {
  1837  	return testCoverMode
  1838  }
  1839  
  1840  func (t *testFuncs) CoverEnabled() bool {
  1841  	return testCover
  1842  }
  1843  
  1844  // ImportPath returns the import path of the package being tested, if it is within GOPATH.
  1845  // This is printed by the testing package when running benchmarks.
  1846  func (t *testFuncs) ImportPath() string {
  1847  	pkg := t.Package.ImportPath
  1848  	if strings.HasPrefix(pkg, "_/") {
  1849  		return ""
  1850  	}
  1851  	if pkg == "command-line-arguments" {
  1852  		return ""
  1853  	}
  1854  	return pkg
  1855  }
  1856  
  1857  // Covered returns a string describing which packages are being tested for coverage.
  1858  // If the covered package is the same as the tested package, it returns the empty string.
  1859  // Otherwise it is a comma-separated human-readable list of packages beginning with
  1860  // " in", ready for use in the coverage message.
  1861  func (t *testFuncs) Covered() string {
  1862  	if testCoverPaths == nil {
  1863  		return ""
  1864  	}
  1865  	return " in " + strings.Join(testCoverPaths, ", ")
  1866  }
  1867  
  1868  // Tested returns the name of the package being tested.
  1869  func (t *testFuncs) Tested() string {
  1870  	return t.Package.Name
  1871  }
  1872  
  1873  type testFunc struct {
  1874  	Package   string // imported package name (_test or _xtest)
  1875  	Name      string // function name
  1876  	Output    string // output, for examples
  1877  	Unordered bool   // output is allowed to be unordered.
  1878  }
  1879  
  1880  var testFileSet = token.NewFileSet()
  1881  
  1882  func (t *testFuncs) load(filename, pkg string, doImport, seen *bool) error {
  1883  	f, err := parser.ParseFile(testFileSet, filename, nil, parser.ParseComments)
  1884  	if err != nil {
  1885  		return base.ExpandScanner(err)
  1886  	}
  1887  	for _, d := range f.Decls {
  1888  		n, ok := d.(*ast.FuncDecl)
  1889  		if !ok {
  1890  			continue
  1891  		}
  1892  		if n.Recv != nil {
  1893  			continue
  1894  		}
  1895  		name := n.Name.String()
  1896  		switch {
  1897  		case name == "TestMain":
  1898  			if isTestFunc(n, "T") {
  1899  				t.Tests = append(t.Tests, testFunc{pkg, name, "", false})
  1900  				*doImport, *seen = true, true
  1901  				continue
  1902  			}
  1903  			err := checkTestFunc(n, "M")
  1904  			if err != nil {
  1905  				return err
  1906  			}
  1907  			if t.TestMain != nil {
  1908  				return errors.New("multiple definitions of TestMain")
  1909  			}
  1910  			t.TestMain = &testFunc{pkg, name, "", false}
  1911  			*doImport, *seen = true, true
  1912  		case isTest(name, "Test"):
  1913  			err := checkTestFunc(n, "T")
  1914  			if err != nil {
  1915  				return err
  1916  			}
  1917  			t.Tests = append(t.Tests, testFunc{pkg, name, "", false})
  1918  			*doImport, *seen = true, true
  1919  		case isTest(name, "Benchmark"):
  1920  			err := checkTestFunc(n, "B")
  1921  			if err != nil {
  1922  				return err
  1923  			}
  1924  			t.Benchmarks = append(t.Benchmarks, testFunc{pkg, name, "", false})
  1925  			*doImport, *seen = true, true
  1926  		}
  1927  	}
  1928  	ex := doc.Examples(f)
  1929  	sort.Slice(ex, func(i, j int) bool { return ex[i].Order < ex[j].Order })
  1930  	for _, e := range ex {
  1931  		*doImport = true // import test file whether executed or not
  1932  		if e.Output == "" && !e.EmptyOutput {
  1933  			// Don't run examples with no output.
  1934  			continue
  1935  		}
  1936  		t.Examples = append(t.Examples, testFunc{pkg, "Example" + e.Name, e.Output, e.Unordered})
  1937  		*seen = true
  1938  	}
  1939  	return nil
  1940  }
  1941  
  1942  func checkTestFunc(fn *ast.FuncDecl, arg string) error {
  1943  	if !isTestFunc(fn, arg) {
  1944  		name := fn.Name.String()
  1945  		pos := testFileSet.Position(fn.Pos())
  1946  		return fmt.Errorf("%s: wrong signature for %s, must be: func %s(%s *testing.%s)", pos, name, name, strings.ToLower(arg), arg)
  1947  	}
  1948  	return nil
  1949  }
  1950  
  1951  var testmainTmpl = template.Must(template.New("main").Parse(`
  1952  package main
  1953  
  1954  import (
  1955  {{if not .TestMain}}
  1956  	"os"
  1957  {{end}}
  1958  	"testing"
  1959  	"testing/internal/testdeps"
  1960  
  1961  {{if .ImportTest}}
  1962  	{{if .NeedTest}}_test{{else}}_{{end}} {{.Package.ImportPath | printf "%q"}}
  1963  {{end}}
  1964  {{if .ImportXtest}}
  1965  	{{if .NeedXtest}}_xtest{{else}}_{{end}} {{.Package.ImportPath | printf "%s_test" | printf "%q"}}
  1966  {{end}}
  1967  {{range $i, $p := .Cover}}
  1968  	_cover{{$i}} {{$p.Package.ImportPath | printf "%q"}}
  1969  {{end}}
  1970  )
  1971  
  1972  var tests = []testing.InternalTest{
  1973  {{range .Tests}}
  1974  	{"{{.Name}}", {{.Package}}.{{.Name}}},
  1975  {{end}}
  1976  }
  1977  
  1978  var benchmarks = []testing.InternalBenchmark{
  1979  {{range .Benchmarks}}
  1980  	{"{{.Name}}", {{.Package}}.{{.Name}}},
  1981  {{end}}
  1982  }
  1983  
  1984  var examples = []testing.InternalExample{
  1985  {{range .Examples}}
  1986  	{"{{.Name}}", {{.Package}}.{{.Name}}, {{.Output | printf "%q"}}, {{.Unordered}}},
  1987  {{end}}
  1988  }
  1989  
  1990  func init() {
  1991  	testdeps.ImportPath = {{.ImportPath | printf "%q"}}
  1992  }
  1993  
  1994  {{if .CoverEnabled}}
  1995  
  1996  // Only updated by init functions, so no need for atomicity.
  1997  var (
  1998  	coverCounters = make(map[string][]uint32)
  1999  	coverBlocks = make(map[string][]testing.CoverBlock)
  2000  )
  2001  
  2002  func init() {
  2003  	{{range $i, $p := .Cover}}
  2004  	{{range $file, $cover := $p.Vars}}
  2005  	coverRegisterFile({{printf "%q" $cover.File}}, _cover{{$i}}.{{$cover.Var}}.Count[:], _cover{{$i}}.{{$cover.Var}}.Pos[:], _cover{{$i}}.{{$cover.Var}}.NumStmt[:])
  2006  	{{end}}
  2007  	{{end}}
  2008  }
  2009  
  2010  func coverRegisterFile(fileName string, counter []uint32, pos []uint32, numStmts []uint16) {
  2011  	if 3*len(counter) != len(pos) || len(counter) != len(numStmts) {
  2012  		panic("coverage: mismatched sizes")
  2013  	}
  2014  	if coverCounters[fileName] != nil {
  2015  		// Already registered.
  2016  		return
  2017  	}
  2018  	coverCounters[fileName] = counter
  2019  	block := make([]testing.CoverBlock, len(counter))
  2020  	for i := range counter {
  2021  		block[i] = testing.CoverBlock{
  2022  			Line0: pos[3*i+0],
  2023  			Col0: uint16(pos[3*i+2]),
  2024  			Line1: pos[3*i+1],
  2025  			Col1: uint16(pos[3*i+2]>>16),
  2026  			Stmts: numStmts[i],
  2027  		}
  2028  	}
  2029  	coverBlocks[fileName] = block
  2030  }
  2031  {{end}}
  2032  
  2033  func main() {
  2034  {{if .CoverEnabled}}
  2035  	testing.RegisterCover(testing.Cover{
  2036  		Mode: {{printf "%q" .CoverMode}},
  2037  		Counters: coverCounters,
  2038  		Blocks: coverBlocks,
  2039  		CoveredPackages: {{printf "%q" .Covered}},
  2040  	})
  2041  {{end}}
  2042  	m := testing.MainStart(testdeps.TestDeps{}, tests, benchmarks, examples)
  2043  {{with .TestMain}}
  2044  	{{.Package}}.{{.Name}}(m)
  2045  {{else}}
  2046  	os.Exit(m.Run())
  2047  {{end}}
  2048  }
  2049  
  2050  `))