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