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