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