Source file src/cmd/go/internal/test/test.go

     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  	"context"
    10  	"errors"
    11  	"fmt"
    12  	"internal/coverage"
    13  	"internal/platform"
    14  	"io"
    15  	"io/fs"
    16  	"maps"
    17  	"os"
    18  	"os/exec"
    19  	"path/filepath"
    20  	"regexp"
    21  	"runtime"
    22  	"slices"
    23  	"strconv"
    24  	"strings"
    25  	"sync"
    26  	"sync/atomic"
    27  	"time"
    28  
    29  	"cmd/go/internal/base"
    30  	"cmd/go/internal/cache"
    31  	"cmd/go/internal/cfg"
    32  	"cmd/go/internal/load"
    33  	"cmd/go/internal/lockedfile"
    34  	"cmd/go/internal/modload"
    35  	"cmd/go/internal/search"
    36  	"cmd/go/internal/str"
    37  	"cmd/go/internal/trace"
    38  	"cmd/go/internal/work"
    39  	"cmd/internal/par"
    40  	"cmd/internal/test2json"
    41  
    42  	"golang.org/x/mod/module"
    43  )
    44  
    45  // Break init loop.
    46  func init() {
    47  	CmdTest.Run = runTest
    48  }
    49  
    50  const testUsage = "go test [build/test flags] [packages] [build/test flags & test binary flags]"
    51  
    52  var CmdTest = &base.Command{
    53  	CustomFlags: true,
    54  	UsageLine:   testUsage,
    55  	Short:       "test packages",
    56  	Long: `
    57  'Go test' automates testing the packages named by the import paths.
    58  It prints a summary of the test results in the format:
    59  
    60  	ok   archive/tar   0.011s
    61  	FAIL archive/zip   0.022s
    62  	ok   compress/gzip 0.033s
    63  	...
    64  
    65  followed by detailed output for each failed package.
    66  
    67  'Go test' recompiles each package along with any files with names matching
    68  the file pattern "*_test.go".
    69  These additional files can contain test functions, benchmark functions, fuzz
    70  tests and example functions. See 'go help testfunc' for more.
    71  Each listed package causes the execution of a separate test binary.
    72  Files whose names begin with "_" (including "_test.go") or "." are ignored.
    73  
    74  Test files that declare a package with the suffix "_test" will be compiled as a
    75  separate package, and then linked and run with the main test binary.
    76  
    77  The go tool will ignore a directory named "testdata", making it available
    78  to hold ancillary data needed by the tests.
    79  
    80  As part of building a test binary, go test runs go vet on the package
    81  and its test source files to identify significant problems. If go vet
    82  finds any problems, go test reports those and does not run the test
    83  binary. Only a high-confidence subset of the default go vet checks are
    84  used. That subset is: atomic, bools, buildtag, directive, errorsas,
    85  ifaceassert, nilfunc, printf, slog, stdversion, stringintconv, and tests.
    86  You can see the documentation for these and other vet tests via
    87  "go doc cmd/vet". To disable the running of go vet, use the -vet=off flag.
    88  To run all checks, use the -vet=all flag.
    89  
    90  All test output and summary lines are printed to the go command's
    91  standard output, even if the test printed them to its own standard
    92  error. (The go command's standard error is reserved for printing
    93  errors building the tests.)
    94  
    95  The go command places $GOROOT/bin at the beginning of $PATH
    96  in the test's environment, so that tests that execute
    97  'go' commands use the same 'go' as the parent 'go test' command.
    98  
    99  Go test runs in two different modes:
   100  
   101  The first, called local directory mode, occurs when go test is
   102  invoked with no package arguments (for example, 'go test' or 'go
   103  test -v'). In this mode, go test compiles the package sources and
   104  tests found in the current directory and then runs the resulting
   105  test binary. In this mode, caching (discussed below) is disabled.
   106  After the package test finishes, go test prints a summary line
   107  showing the test status ('ok' or 'FAIL'), package name, and elapsed
   108  time.
   109  
   110  The second, called package list mode, occurs when go test is invoked
   111  with explicit package arguments (for example 'go test math', 'go
   112  test ./...', and even 'go test .'). In this mode, go test compiles
   113  and tests each of the packages listed on the command line. If a
   114  package test passes, go test prints only the final 'ok' summary
   115  line. If a package test fails, go test prints the full test output.
   116  If invoked with the -bench or -v flag, go test prints the full
   117  output even for passing package tests, in order to display the
   118  requested benchmark results or verbose logging. After the package
   119  tests for all of the listed packages finish, and their output is
   120  printed, go test prints a final 'FAIL' status if any package test
   121  has failed.
   122  
   123  In package list mode only, go test caches successful package test
   124  results to avoid unnecessary repeated running of tests. When the
   125  result of a test can be recovered from the cache, go test will
   126  redisplay the previous output instead of running the test binary
   127  again. When this happens, go test prints '(cached)' in place of the
   128  elapsed time in the summary line.
   129  
   130  The rule for a match in the cache is that the run involves the same
   131  test binary and the flags on the command line come entirely from a
   132  restricted set of 'cacheable' test flags, defined as -benchtime,
   133  -coverprofile, -cpu, -failfast, -fullpath, -list, -outputdir, -parallel,
   134  -run, -short, -skip, -timeout and -v.
   135  If a run of go test has any test or non-test flags outside this set,
   136  the result is not cached. To disable test caching, use any test flag
   137  or argument other than the cacheable flags. The idiomatic way to disable
   138  test caching explicitly is to use -count=1. Tests that open files within
   139  the package's module or that consult environment variables only
   140  match future runs in which the files and environment variables are
   141  unchanged. A cached test result is treated as executing in no time
   142  at all, so a successful package test result will be cached and
   143  reused regardless of -timeout setting.
   144  
   145  In addition to the build flags, the flags handled by 'go test' itself are:
   146  
   147  	-args
   148  	    Pass the remainder of the command line (everything after -args)
   149  	    to the test binary, uninterpreted and unchanged.
   150  	    Because this flag consumes the remainder of the command line,
   151  	    the package list (if present) must appear before this flag.
   152  
   153  	-c
   154  	    Compile the test binary to pkg.test in the current directory but do not run it
   155  	    (where pkg is the last element of the package's import path).
   156  	    The file name or target directory can be changed with the -o flag.
   157  
   158  	-exec xprog
   159  	    Run the test binary using xprog. The behavior is the same as
   160  	    in 'go run'. See 'go help run' for details.
   161  
   162  	-json
   163  	    Convert test output to JSON suitable for automated processing.
   164  	    See 'go doc test2json' for the encoding details.
   165  	    Also emits build output in JSON. See 'go help buildjson'.
   166  
   167  	-o file
   168  	    Save a copy of the test binary to the named file.
   169  	    The test still runs (unless -c is specified).
   170  	    If file ends in a slash or names an existing directory,
   171  	    the test is written to pkg.test in that directory.
   172  
   173  The test binary also accepts flags that control execution of the test; these
   174  flags are also accessible by 'go test'. See 'go help testflag' for details.
   175  
   176  For more about build flags, see 'go help build'.
   177  For more about specifying packages, see 'go help packages'.
   178  
   179  See also: go build, go vet.
   180  `,
   181  }
   182  
   183  var HelpTestflag = &base.Command{
   184  	UsageLine: "testflag",
   185  	Short:     "testing flags",
   186  	Long: `
   187  The 'go test' command takes both flags that apply to 'go test' itself
   188  and flags that apply to the resulting test binary.
   189  
   190  Several of the flags control profiling and write an execution profile
   191  suitable for "go tool pprof"; run "go tool pprof -h" for more
   192  information. The -sample_index=alloc_space, -sample_index=alloc_objects,
   193  and -show_bytes options of pprof control how the information is presented.
   194  
   195  The following flags are recognized by the 'go test' command and
   196  control the execution of any test:
   197  
   198  	-artifacts
   199  	    Save test artifacts in the directory specified by -outputdir.
   200  	    See 'go doc testing.T.ArtifactDir'.
   201  
   202  	-bench regexp
   203  	    Run only those benchmarks matching a regular expression.
   204  	    By default, no benchmarks are run.
   205  	    To run all benchmarks, use '-bench .' or '-bench=.'.
   206  	    The regular expression is split by unbracketed slash (/)
   207  	    characters into a sequence of regular expressions, and each
   208  	    part of a benchmark's identifier must match the corresponding
   209  	    element in the sequence, if any. Possible parents of matches
   210  	    are run with b.N=1 to identify sub-benchmarks. For example,
   211  	    given -bench=X/Y, top-level benchmarks matching X are run
   212  	    with b.N=1 to find any sub-benchmarks matching Y, which are
   213  	    then run in full.
   214  
   215  	-benchtime t
   216  	    Run enough iterations of each benchmark to take t, specified
   217  	    as a time.Duration (for example, -benchtime 1h30s).
   218  	    The default is 1 second (1s).
   219  	    The special syntax Nx means to run the benchmark N times
   220  	    (for example, -benchtime 100x).
   221  
   222  	-count n
   223  	    Run each test, benchmark, and fuzz seed n times (default 1).
   224  	    If -cpu is set, run n times for each GOMAXPROCS value.
   225  	    Examples are always run once. -count does not apply to
   226  	    fuzz tests matched by -fuzz.
   227  
   228  	-cover
   229  	    Enable coverage analysis.
   230  	    Note that because coverage works by annotating the source
   231  	    code before compilation, compilation and test failures with
   232  	    coverage enabled may report line numbers that don't correspond
   233  	    to the original sources.
   234  
   235  	-covermode set,count,atomic
   236  	    Set the mode for coverage analysis for the package[s]
   237  	    being tested. The default is "set" unless -race is enabled,
   238  	    in which case it is "atomic".
   239  	    The values:
   240  		set: bool: does this statement run?
   241  		count: int: how many times does this statement run?
   242  		atomic: int: count, but correct in multithreaded tests;
   243  			significantly more expensive.
   244  	    Sets -cover.
   245  
   246  	-coverpkg pattern1,pattern2,pattern3
   247  	    Apply coverage analysis in each test to packages whose import paths
   248  	    match the patterns. The default is for each test to analyze only
   249  	    the package being tested. See 'go help packages' for a description
   250  	    of package patterns. Sets -cover.
   251  
   252  	-cpu 1,2,4
   253  	    Specify a list of GOMAXPROCS values for which the tests, benchmarks or
   254  	    fuzz tests should be executed. The default is the current value
   255  	    of GOMAXPROCS. -cpu does not apply to fuzz tests matched by -fuzz.
   256  
   257  	-failfast
   258  	    Do not start new tests after the first test failure.
   259  
   260  	-fullpath
   261  	    Show full file names in the error messages.
   262  
   263  	-fuzz regexp
   264  	    Run the fuzz test matching the regular expression. When specified,
   265  	    the command line argument must match exactly one package within the
   266  	    main module, and regexp must match exactly one fuzz test within
   267  	    that package. Fuzzing will occur after tests, benchmarks, seed corpora
   268  	    of other fuzz tests, and examples have completed. See the Fuzzing
   269  	    section of the testing package documentation for details.
   270  
   271  	-fuzztime t
   272  	    Run enough iterations of the fuzz target during fuzzing to take t,
   273  	    specified as a time.Duration (for example, -fuzztime 1h30s).
   274  		The default is to run forever.
   275  	    The special syntax Nx means to run the fuzz target N times
   276  	    (for example, -fuzztime 1000x).
   277  
   278  	-fuzzminimizetime t
   279  	    Run enough iterations of the fuzz target during each minimization
   280  	    attempt to take t, as specified as a time.Duration (for example,
   281  	    -fuzzminimizetime 30s).
   282  		The default is 60s.
   283  	    The special syntax Nx means to run the fuzz target N times
   284  	    (for example, -fuzzminimizetime 100x).
   285  
   286  	-json
   287  	    Log verbose output and test results in JSON. This presents the
   288  	    same information as the -v flag in a machine-readable format.
   289  
   290  	-list regexp
   291  	    List tests, benchmarks, fuzz tests, or examples matching the regular
   292  	    expression. No tests, benchmarks, fuzz tests, or examples will be run.
   293  	    This will only list top-level tests. No subtest or subbenchmarks will be
   294  	    shown.
   295  
   296  	-outputdir directory
   297  	    Place output files from profiling and test artifacts in the
   298  	    specified directory, by default the directory in which "go test" is running.
   299  
   300  	-parallel n
   301  	    Allow parallel execution of test functions that call t.Parallel, and
   302  	    fuzz targets that call t.Parallel when running the seed corpus.
   303  	    The value of this flag is the maximum number of tests to run
   304  	    simultaneously.
   305  	    While fuzzing, the value of this flag is the maximum number of
   306  	    subprocesses that may call the fuzz function simultaneously, regardless of
   307  	    whether T.Parallel is called.
   308  	    By default, -parallel is set to the value of GOMAXPROCS.
   309  	    Setting -parallel to values higher than GOMAXPROCS may cause degraded
   310  	    performance due to CPU contention, especially when fuzzing.
   311  	    Note that -parallel only applies within a single test binary.
   312  	    The 'go test' command may run tests for different packages
   313  	    in parallel as well, according to the setting of the -p flag
   314  	    (see 'go help build').
   315  
   316  	-run regexp
   317  	    Run only those tests, examples, and fuzz tests matching the regular
   318  	    expression. For tests, the regular expression is split by unbracketed
   319  	    slash (/) characters into a sequence of regular expressions, and each
   320  	    part of a test's identifier must match the corresponding element in
   321  	    the sequence, if any. Note that possible parents of matches are
   322  	    run too, so that -run=X/Y matches and runs and reports the result
   323  	    of all tests matching X, even those without sub-tests matching Y,
   324  	    because it must run them to look for those sub-tests.
   325  	    See also -skip.
   326  
   327  	-short
   328  	    Tell long-running tests to shorten their run time.
   329  	    It is off by default but set during all.bash so that installing
   330  	    the Go tree can run a sanity check but not spend time running
   331  	    exhaustive tests.
   332  
   333  	-shuffle off,on,N
   334  	    Randomize the execution order of tests and benchmarks.
   335  	    It is off by default. If -shuffle is set to on, then it will seed
   336  	    the randomizer using the system clock. If -shuffle is set to an
   337  	    integer N, then N will be used as the seed value. In both cases,
   338  	    the seed will be reported for reproducibility.
   339  
   340  	-skip regexp
   341  	    Run only those tests, examples, fuzz tests, and benchmarks that
   342  	    do not match the regular expression. Like for -run and -bench,
   343  	    for tests and benchmarks, the regular expression is split by unbracketed
   344  	    slash (/) characters into a sequence of regular expressions, and each
   345  	    part of a test's identifier must match the corresponding element in
   346  	    the sequence, if any.
   347  
   348  	-timeout d
   349  	    If a test binary runs longer than duration d, panic.
   350  	    If d is 0, the timeout is disabled.
   351  	    The default is 10 minutes (10m).
   352  
   353  	-v
   354  	    Verbose output: log all tests as they are run. Also print all
   355  	    text from Log and Logf calls even if the test succeeds.
   356  
   357  	-vet list
   358  	    Configure the invocation of "go vet" during "go test"
   359  	    to use the comma-separated list of vet checks.
   360  	    If list is empty, "go test" runs "go vet" with a curated list of
   361  	    checks believed to be always worth addressing.
   362  	    If list is "off", "go test" does not run "go vet" at all.
   363  
   364  The following flags are also recognized by 'go test' and can be used to
   365  profile the tests during execution:
   366  
   367  	-benchmem
   368  	    Print memory allocation statistics for benchmarks.
   369  	    Allocations made in C or using C.malloc are not counted.
   370  
   371  	-blockprofile block.out
   372  	    Write a goroutine blocking profile to the specified file
   373  	    when all tests are complete.
   374  	    Writes test binary as -c would.
   375  
   376  	-blockprofilerate n
   377  	    Control the detail provided in goroutine blocking profiles by
   378  	    calling runtime.SetBlockProfileRate with n.
   379  	    See 'go doc runtime.SetBlockProfileRate'.
   380  	    The profiler aims to sample, on average, one blocking event every
   381  	    n nanoseconds the program spends blocked. By default,
   382  	    if -test.blockprofile is set without this flag, all blocking events
   383  	    are recorded, equivalent to -test.blockprofilerate=1.
   384  
   385  	-coverprofile cover.out
   386  	    Write a coverage profile to the file after all tests have passed.
   387  	    Sets -cover.
   388  
   389  	-cpuprofile cpu.out
   390  	    Write a CPU profile to the specified file before exiting.
   391  	    Writes test binary as -c would.
   392  
   393  	-memprofile mem.out
   394  	    Write an allocation profile to the file after all tests have passed.
   395  	    Writes test binary as -c would.
   396  
   397  	-memprofilerate n
   398  	    Enable more precise (and expensive) memory allocation profiles by
   399  	    setting runtime.MemProfileRate. See 'go doc runtime.MemProfileRate'.
   400  	    To profile all memory allocations, use -test.memprofilerate=1.
   401  
   402  	-mutexprofile mutex.out
   403  	    Write a mutex contention profile to the specified file
   404  	    when all tests are complete.
   405  	    Writes test binary as -c would.
   406  
   407  	-mutexprofilefraction n
   408  	    Sample 1 in n stack traces of goroutines holding a
   409  	    contended mutex.
   410  
   411  	-trace trace.out
   412  	    Write an execution trace to the specified file before exiting.
   413  
   414  Each of these flags is also recognized with an optional 'test.' prefix,
   415  as in -test.v. When invoking the generated test binary (the result of
   416  'go test -c') directly, however, the prefix is mandatory.
   417  
   418  The 'go test' command rewrites or removes recognized flags,
   419  as appropriate, both before and after the optional package list,
   420  before invoking the test binary.
   421  
   422  For instance, the command
   423  
   424  	go test -v -myflag testdata -cpuprofile=prof.out -x
   425  
   426  will compile the test binary and then run it as
   427  
   428  	pkg.test -test.v -myflag testdata -test.cpuprofile=prof.out
   429  
   430  (The -x flag is removed because it applies only to the go command's
   431  execution, not to the test itself.)
   432  
   433  The test flags that generate profiles (other than for coverage) also
   434  leave the test binary in pkg.test for use when analyzing the profiles.
   435  
   436  When 'go test' runs a test binary, it does so from within the
   437  corresponding package's source code directory. Depending on the test,
   438  it may be necessary to do the same when invoking a generated test
   439  binary directly. Because that directory may be located within the
   440  module cache, which may be read-only and is verified by checksums, the
   441  test must not write to it or any other directory within the module
   442  unless explicitly requested by the user (such as with the -fuzz flag,
   443  which writes failures to testdata/fuzz).
   444  
   445  The command-line package list, if present, must appear before any
   446  flag not known to the go test command. Continuing the example above,
   447  the package list would have to appear before -myflag, but could appear
   448  on either side of -v.
   449  
   450  When 'go test' runs in package list mode, 'go test' caches successful
   451  package test results to avoid unnecessary repeated running of tests. To
   452  disable test caching, use any test flag or argument other than the
   453  cacheable flags. The idiomatic way to disable test caching explicitly
   454  is to use -count=1.
   455  
   456  To keep an argument for a test binary from being interpreted as a
   457  known flag or a package name, use -args (see 'go help test') which
   458  passes the remainder of the command line through to the test binary
   459  uninterpreted and unaltered.
   460  
   461  For instance, the command
   462  
   463  	go test -v -args -x -v
   464  
   465  will compile the test binary and then run it as
   466  
   467  	pkg.test -test.v -x -v
   468  
   469  Similarly,
   470  
   471  	go test -args math
   472  
   473  will compile the test binary and then run it as
   474  
   475  	pkg.test math
   476  
   477  In the first example, the -x and the second -v are passed through to the
   478  test binary unchanged and with no effect on the go command itself.
   479  In the second example, the argument math is passed through to the test
   480  binary, instead of being interpreted as the package list.
   481  `,
   482  }
   483  
   484  var HelpTestfunc = &base.Command{
   485  	UsageLine: "testfunc",
   486  	Short:     "testing functions",
   487  	Long: `
   488  The 'go test' command expects to find test, benchmark, and example functions
   489  in the "*_test.go" files corresponding to the package under test.
   490  
   491  A test function is one named TestXxx (where Xxx does not start with a
   492  lower case letter) and should have the signature,
   493  
   494  	func TestXxx(t *testing.T) { ... }
   495  
   496  A benchmark function is one named BenchmarkXxx and should have the signature,
   497  
   498  	func BenchmarkXxx(b *testing.B) { ... }
   499  
   500  A fuzz test is one named FuzzXxx and should have the signature,
   501  
   502  	func FuzzXxx(f *testing.F) { ... }
   503  
   504  An example function is similar to a test function but, instead of using
   505  *testing.T to report success or failure, prints output to os.Stdout.
   506  If the last comment in the function starts with "Output:" then the output
   507  is compared exactly against the comment (see examples below). If the last
   508  comment begins with "Unordered output:" then the output is compared to the
   509  comment, however the order of the lines is ignored. An example with no such
   510  comment is compiled but not executed. An example with no text after
   511  "Output:" is compiled, executed, and expected to produce no output.
   512  
   513  Godoc displays the body of ExampleXxx to demonstrate the use
   514  of the function, constant, or variable Xxx. An example of a method M with
   515  receiver type T or *T is named ExampleT_M. There may be multiple examples
   516  for a given function, constant, or variable, distinguished by a trailing _xxx,
   517  where xxx is a suffix not beginning with an upper case letter.
   518  
   519  Here is an example of an example:
   520  
   521  	func ExamplePrintln() {
   522  		Println("The output of\nthis example.")
   523  		// Output: The output of
   524  		// this example.
   525  	}
   526  
   527  Here is another example where the ordering of the output is ignored:
   528  
   529  	func ExamplePerm() {
   530  		for _, value := range Perm(4) {
   531  			fmt.Println(value)
   532  		}
   533  
   534  		// Unordered output: 4
   535  		// 2
   536  		// 1
   537  		// 3
   538  		// 0
   539  	}
   540  
   541  The entire test file is presented as the example when it contains a single
   542  example function, at least one other function, type, variable, or constant
   543  declaration, and no tests, benchmarks, or fuzz tests.
   544  
   545  See the documentation of the testing package for more information.
   546  `,
   547  }
   548  
   549  var (
   550  	testArtifacts    bool                              // -artifacts flag
   551  	testBench        string                            // -bench flag
   552  	testC            bool                              // -c flag
   553  	testCoverPkgs    []*load.Package                   // -coverpkg flag
   554  	testCoverProfile string                            // -coverprofile flag
   555  	testFailFast     bool                              // -failfast flag
   556  	testFuzz         string                            // -fuzz flag
   557  	testJSON         bool                              // -json flag
   558  	testList         string                            // -list flag
   559  	testO            string                            // -o flag
   560  	testOutputDir    outputdirFlag                     // -outputdir flag
   561  	testShuffle      shuffleFlag                       // -shuffle flag
   562  	testTimeout      time.Duration                     // -timeout flag
   563  	testV            testVFlag                         // -v flag
   564  	testVet          = vetFlag{flags: defaultVetFlags} // -vet flag
   565  )
   566  
   567  type testVFlag struct {
   568  	on   bool // -v is set in some form
   569  	json bool // -v=test2json is set, to make output better for test2json
   570  }
   571  
   572  func (*testVFlag) IsBoolFlag() bool { return true }
   573  
   574  func (f *testVFlag) Set(arg string) error {
   575  	if v, err := strconv.ParseBool(arg); err == nil {
   576  		f.on = v
   577  		f.json = false
   578  		return nil
   579  	}
   580  	if arg == "test2json" {
   581  		f.on = true
   582  		f.json = true
   583  		return nil
   584  	}
   585  	return fmt.Errorf("invalid flag -test.v=%s", arg)
   586  }
   587  
   588  func (f *testVFlag) String() string {
   589  	if f.json {
   590  		return "test2json"
   591  	}
   592  	if f.on {
   593  		return "true"
   594  	}
   595  	return "false"
   596  }
   597  
   598  var (
   599  	testArgs []string
   600  	pkgArgs  []string
   601  	pkgs     []*load.Package
   602  
   603  	testHelp bool // -help option passed to test via -args
   604  
   605  	testKillTimeout    = 100 * 365 * 24 * time.Hour // backup alarm; defaults to about a century if no timeout is set
   606  	testWaitDelay      time.Duration                // how long to wait for output to close after a test binary exits; zero means unlimited
   607  	testCacheExpire    time.Time                    // ignore cached test results before this time
   608  	testShouldFailFast atomic.Bool                  // signals pending tests to fail fast
   609  
   610  	testBlockProfile, testCPUProfile, testMemProfile, testMutexProfile, testTrace string // profiling flag that limits test to one package
   611  
   612  	testODir = false
   613  )
   614  
   615  // testProfile returns the name of an arbitrary single-package profiling flag
   616  // that is set, if any.
   617  func testProfile() string {
   618  	switch {
   619  	case testBlockProfile != "":
   620  		return "-blockprofile"
   621  	case testCPUProfile != "":
   622  		return "-cpuprofile"
   623  	case testMemProfile != "":
   624  		return "-memprofile"
   625  	case testMutexProfile != "":
   626  		return "-mutexprofile"
   627  	case testTrace != "":
   628  		return "-trace"
   629  	default:
   630  		return ""
   631  	}
   632  }
   633  
   634  // testNeedBinary reports whether the test needs to keep the binary around.
   635  func testNeedBinary() bool {
   636  	switch {
   637  	case testBlockProfile != "":
   638  		return true
   639  	case testCPUProfile != "":
   640  		return true
   641  	case testMemProfile != "":
   642  		return true
   643  	case testMutexProfile != "":
   644  		return true
   645  	case testO != "":
   646  		return true
   647  	default:
   648  		return false
   649  	}
   650  }
   651  
   652  // testShowPass reports whether the output for a passing test should be shown.
   653  func testShowPass() bool {
   654  	return testV.on || testList != "" || testHelp
   655  }
   656  
   657  var defaultVetFlags = []string{
   658  	// TODO(rsc): Decide which tests are enabled by default.
   659  	// See golang.org/issue/18085.
   660  	// "-appends",
   661  	// "-asmdecl",
   662  	// "-assign",
   663  	"-atomic",
   664  	"-bools",
   665  	"-buildtag",
   666  	// "-cgocall",
   667  	// "-composites",
   668  	// "-copylocks",
   669  	// "-defers",
   670  	"-directive",
   671  	"-errorsas",
   672  	// "-framepointer",
   673  	// "-hostport",
   674  	// "-httpresponse",
   675  	"-ifaceassert",
   676  	// "-loopclosure",
   677  	// "-lostcancel",
   678  	"-nilfunc",
   679  	"-printf",
   680  	// "-shift",
   681  	// "-sigchanyzer",
   682  	"-slog",
   683  	// "-stdmethods",
   684  	"-stdversion",
   685  	"-stringintconv",
   686  	// "-structtag",
   687  	// "-testinggoroutine",
   688  	"-tests",
   689  	// "-timeformat",
   690  	// "-unmarshal",
   691  	// "-unreachable",
   692  	// "-unsafeptr",
   693  	// "-unusedresult",
   694  	// "-waitgroup",
   695  }
   696  
   697  func runTest(ctx context.Context, cmd *base.Command, args []string) {
   698  	moduleLoader := modload.NewLoader()
   699  	pkgArgs, testArgs = testFlags(args)
   700  	moduleLoader.InitWorkfile() // The test command does custom flag processing; initialize workspaces after that.
   701  
   702  	if cfg.DebugTrace != "" {
   703  		var close func() error
   704  		var err error
   705  		ctx, close, err = trace.Start(ctx, cfg.DebugTrace)
   706  		if err != nil {
   707  			base.Fatalf("failed to start trace: %v", err)
   708  		}
   709  		defer func() {
   710  			if err := close(); err != nil {
   711  				base.Fatalf("failed to stop trace: %v", err)
   712  			}
   713  		}()
   714  	}
   715  
   716  	ctx, span := trace.StartSpan(ctx, fmt.Sprint("Running ", cmd.Name(), " command"))
   717  	defer span.Done()
   718  
   719  	work.FindExecCmd() // initialize cached result
   720  
   721  	work.BuildInit(moduleLoader)
   722  	work.VetFlags = testVet.flags
   723  	work.VetExplicit = testVet.explicit
   724  	work.VetTool = base.Tool("vet")
   725  
   726  	pkgOpts := load.PackageOpts{ModResolveTests: true}
   727  	pkgs = load.PackagesAndErrors(moduleLoader, ctx, pkgOpts, pkgArgs)
   728  	// We *don't* call load.CheckPackageErrors here because we want to report
   729  	// loading errors as per-package test setup errors later.
   730  	if len(pkgs) == 0 {
   731  		base.Fatalf("no packages to test")
   732  	}
   733  
   734  	if testFuzz != "" {
   735  		if !platform.FuzzSupported(cfg.Goos, cfg.Goarch) {
   736  			base.Fatalf("-fuzz flag is not supported on %s/%s", cfg.Goos, cfg.Goarch)
   737  		}
   738  		if len(pkgs) != 1 {
   739  			base.Fatalf("cannot use -fuzz flag with multiple packages")
   740  		}
   741  		if testCoverProfile != "" {
   742  			base.Fatalf("cannot use -coverprofile flag with -fuzz flag")
   743  		}
   744  		if profileFlag := testProfile(); profileFlag != "" {
   745  			base.Fatalf("cannot use %s flag with -fuzz flag", profileFlag)
   746  		}
   747  
   748  		// Reject the '-fuzz' flag if the package is outside the main module.
   749  		// Otherwise, if fuzzing identifies a failure it could corrupt checksums in
   750  		// the module cache (or permanently alter the behavior of std tests for all
   751  		// users) by writing the failing input to the package's testdata directory.
   752  		// (See https://golang.org/issue/48495 and cmd/internal/fuzztest/test_fuzz_modcache.txt.)
   753  		mainMods := moduleLoader.MainModules
   754  		if m := pkgs[0].Module; m != nil && m.Path != "" {
   755  			if !mainMods.Contains(m.Path) {
   756  				base.Fatalf("cannot use -fuzz flag on package outside the main module")
   757  			}
   758  		} else if pkgs[0].Standard && moduleLoader.Enabled() {
   759  			// Because packages in 'std' and 'cmd' are part of the standard library,
   760  			// they are only treated as part of a module in 'go mod' subcommands and
   761  			// 'go get'. However, we still don't want to accidentally corrupt their
   762  			// testdata during fuzzing, nor do we want to fail with surprising errors
   763  			// if GOROOT isn't writable (as is often the case for Go toolchains
   764  			// installed through package managers).
   765  			//
   766  			// If the user is requesting to fuzz a standard-library package, ensure
   767  			// that they are in the same module as that package (just like when
   768  			// fuzzing any other package).
   769  			if strings.HasPrefix(pkgs[0].ImportPath, "cmd/") {
   770  				if !mainMods.Contains("cmd") || !mainMods.InGorootSrc(module.Version{Path: "cmd"}) {
   771  					base.Fatalf("cannot use -fuzz flag on package outside the main module")
   772  				}
   773  			} else {
   774  				if !mainMods.Contains("std") || !mainMods.InGorootSrc(module.Version{Path: "std"}) {
   775  					base.Fatalf("cannot use -fuzz flag on package outside the main module")
   776  				}
   777  			}
   778  		}
   779  	}
   780  	if testProfile() != "" && len(pkgs) != 1 {
   781  		base.Fatalf("cannot use %s flag with multiple packages", testProfile())
   782  	}
   783  
   784  	if testO != "" {
   785  		if strings.HasSuffix(testO, "/") || strings.HasSuffix(testO, string(os.PathSeparator)) {
   786  			testODir = true
   787  		} else if fi, err := os.Stat(testO); err == nil && fi.IsDir() {
   788  			testODir = true
   789  		}
   790  	}
   791  
   792  	if len(pkgs) > 1 && (testC || testO != "") && !base.IsNull(testO) {
   793  		if testO != "" && !testODir {
   794  			base.Fatalf("with multiple packages, -o must refer to a directory or %s", os.DevNull)
   795  		}
   796  
   797  		pkgsForBinary := map[string][]*load.Package{}
   798  
   799  		for _, p := range pkgs {
   800  			testBinary := testBinaryName(p)
   801  			pkgsForBinary[testBinary] = append(pkgsForBinary[testBinary], p)
   802  		}
   803  
   804  		for testBinary, pkgs := range pkgsForBinary {
   805  			if len(pkgs) > 1 {
   806  				var buf strings.Builder
   807  				for _, pkg := range pkgs {
   808  					buf.WriteString(pkg.ImportPath)
   809  					buf.WriteString("\n")
   810  				}
   811  
   812  				base.Errorf("cannot write test binary %s for multiple packages:\n%s", testBinary, buf.String())
   813  			}
   814  		}
   815  
   816  		base.ExitIfErrors()
   817  	}
   818  
   819  	initCoverProfile()
   820  	defer closeCoverProfile()
   821  
   822  	// If a test timeout is finite, set our kill timeout
   823  	// to that timeout plus one minute. This is a backup alarm in case
   824  	// the test wedges with a goroutine spinning and its background
   825  	// timer does not get a chance to fire.
   826  	// Don't set this if fuzzing or benchmarking, since it should be able to run
   827  	// indefinitely.
   828  	if testTimeout > 0 && testFuzz == "" && testBench == "" {
   829  		// The WaitDelay for the test process depends on both the OS I/O and
   830  		// scheduling overhead and the amount of I/O generated by the test just
   831  		// before it exits. We set the minimum at 5 seconds to account for the OS
   832  		// overhead, and scale it up from there proportional to the overall test
   833  		// timeout on the assumption that the time to write and read a goroutine
   834  		// dump from a timed-out test process scales roughly with the overall
   835  		// running time of the test.
   836  		//
   837  		// This is probably too generous when the timeout is very long, but it seems
   838  		// better to hard-code a scale factor than to hard-code a constant delay.
   839  		if wd := testTimeout / 10; wd < 5*time.Second {
   840  			testWaitDelay = 5 * time.Second
   841  		} else {
   842  			testWaitDelay = wd
   843  		}
   844  
   845  		// We expect the test binary to terminate itself (and dump stacks) after
   846  		// exactly testTimeout. We give it up to one WaitDelay or one minute,
   847  		// whichever is longer, to finish dumping stacks before we send it an
   848  		// external signal: if the process has a lot of goroutines, dumping stacks
   849  		// after the timeout can take a while.
   850  		//
   851  		// After the signal is delivered, the test process may have up to one
   852  		// additional WaitDelay to finish writing its output streams.
   853  		if testWaitDelay < 1*time.Minute {
   854  			testKillTimeout = testTimeout + 1*time.Minute
   855  		} else {
   856  			testKillTimeout = testTimeout + testWaitDelay
   857  		}
   858  	}
   859  
   860  	// Read testcache expiration time, if present.
   861  	// (We implement go clean -testcache by writing an expiration date
   862  	// instead of searching out and deleting test result cache entries.)
   863  	if dir, _, _ := cache.DefaultDir(); dir != "off" {
   864  		if data, _ := lockedfile.Read(filepath.Join(dir, "testexpire.txt")); len(data) > 0 && data[len(data)-1] == '\n' {
   865  			if t, err := strconv.ParseInt(string(data[:len(data)-1]), 10, 64); err == nil {
   866  				testCacheExpire = time.Unix(0, t)
   867  			}
   868  		}
   869  	}
   870  
   871  	b := work.NewBuilder("", moduleLoader.VendorDirOrEmpty)
   872  	defer func() {
   873  		if err := b.Close(); err != nil {
   874  			base.Fatal(err)
   875  		}
   876  	}()
   877  
   878  	var builds, runs, prints []*work.Action
   879  	var writeCoverMetaAct *work.Action
   880  
   881  	if cfg.BuildCoverPkg != nil {
   882  		match := make([]func(*modload.Loader, *load.Package) bool, len(cfg.BuildCoverPkg))
   883  		for i := range cfg.BuildCoverPkg {
   884  			match[i] = load.MatchPackage(cfg.BuildCoverPkg[i], base.Cwd())
   885  		}
   886  
   887  		// Select for coverage all dependencies matching the -coverpkg
   888  		// patterns.
   889  		plist := load.TestPackageList(moduleLoader, ctx, pkgOpts, pkgs)
   890  		testCoverPkgs = load.SelectCoverPackages(moduleLoader, plist, match, "test")
   891  		if len(testCoverPkgs) > 0 {
   892  			// create a new singleton action that will collect up the
   893  			// meta-data files from all of the packages mentioned in
   894  			// "-coverpkg" and write them to a summary file. This new
   895  			// action will depend on all the build actions for the
   896  			// test packages, and all the run actions for these
   897  			// packages will depend on it. Motivating example:
   898  			// supposed we have a top level directory with three
   899  			// package subdirs, "a", "b", and "c", and
   900  			// from the top level, a user runs "go test -coverpkg=./... ./...".
   901  			// This will result in (roughly) the following action graph:
   902  			//
   903  			//	build("a")       build("b")         build("c")
   904  			//	    |               |                   |
   905  			//	link("a.test")   link("b.test")     link("c.test")
   906  			//	    |               |                   |
   907  			//	run("a.test")    run("b.test")      run("c.test")
   908  			//	    |               |                   |
   909  			//	  print          print              print
   910  			//
   911  			// When -coverpkg=<pattern> is in effect, we want to
   912  			// express the coverage percentage for each package as a
   913  			// fraction of *all* the statements that match the
   914  			// pattern, hence if "c" doesn't import "a", we need to
   915  			// pass as meta-data file for "a" (emitted during the
   916  			// package "a" build) to the package "c" run action, so
   917  			// that it can be incorporated with "c"'s regular
   918  			// metadata. To do this, we add edges from each compile
   919  			// action to a "writeCoverMeta" action, then from the
   920  			// writeCoverMeta action to each run action. Updated
   921  			// graph:
   922  			//
   923  			//	build("a")       build("b")         build("c")
   924  			//	    |   \       /   |               /   |
   925  			//	    |    v     v    |              /    |
   926  			//	    |   writemeta <-|-------------+     |
   927  			//	    |         |||   |                   |
   928  			//	    |         ||\   |                   |
   929  			//	link("a.test")/\ \  link("b.test")      link("c.test")
   930  			//	    |        /  \ +-|--------------+    |
   931  			//	    |       /    \  |               \   |
   932  			//	    |      v      v |                v  |
   933  			//	run("a.test")    run("b.test")      run("c.test")
   934  			//	    |               |                   |
   935  			//	  print          print              print
   936  			//
   937  			writeCoverMetaAct = &work.Action{
   938  				Mode:   "write coverage meta-data file",
   939  				Actor:  work.ActorFunc(work.WriteCoverMetaFilesFile),
   940  				Objdir: b.NewObjdir(),
   941  			}
   942  			for _, p := range testCoverPkgs {
   943  				p.Internal.Cover.GenMeta = true
   944  			}
   945  		}
   946  	}
   947  
   948  	// Inform the compiler that it should instrument the binary at
   949  	// build-time when fuzzing is enabled.
   950  	if testFuzz != "" {
   951  		// Don't instrument packages which may affect coverage guidance but are
   952  		// unlikely to be useful. Most of these are used by the testing or
   953  		// internal/fuzz packages concurrently with fuzzing.
   954  		var skipInstrumentation = map[string]bool{
   955  			"context":               true,
   956  			"internal/fuzz":         true,
   957  			"internal/godebug":      true,
   958  			"internal/runtime/maps": true,
   959  			"internal/sync":         true,
   960  			"reflect":               true,
   961  			"runtime":               true,
   962  			"sync":                  true,
   963  			"sync/atomic":           true,
   964  			"syscall":               true,
   965  			"testing":               true,
   966  			"time":                  true,
   967  		}
   968  		for _, p := range load.TestPackageList(moduleLoader, ctx, pkgOpts, pkgs) {
   969  			if !skipInstrumentation[p.ImportPath] {
   970  				p.Internal.FuzzInstrument = true
   971  			}
   972  		}
   973  	}
   974  
   975  	// Collect all the packages imported by the packages being tested.
   976  	allImports := make(map[*load.Package]bool)
   977  	for _, p := range pkgs {
   978  		if p.Error != nil && p.Error.IsImportCycle {
   979  			continue
   980  		}
   981  		for _, p1 := range p.Internal.Imports {
   982  			allImports[p1] = true
   983  		}
   984  	}
   985  
   986  	if cfg.BuildCover {
   987  		for _, p := range pkgs {
   988  			// sync/atomic import is inserted by the cover tool if
   989  			// we're using atomic mode (and not compiling
   990  			// sync/atomic package itself). See #18486 and #57445.
   991  			// Note that this needs to be done prior to any of the
   992  			// builderTest invocations below, due to the fact that
   993  			// a given package in the 'pkgs' list may import
   994  			// package Q which appears later in the list (if this
   995  			// happens we'll wind up building the Q compile action
   996  			// before updating its deps to include sync/atomic).
   997  			if cfg.BuildCoverMode == "atomic" && p.ImportPath != "sync/atomic" {
   998  				load.EnsureImport(moduleLoader, p, "sync/atomic")
   999  			}
  1000  			// Tag the package for static meta-data generation if no
  1001  			// test files (this works only with the new coverage
  1002  			// design). Do this here (as opposed to in builderTest) so
  1003  			// as to handle the case where we're testing multiple
  1004  			// packages and one of the earlier packages imports a
  1005  			// later package. Note that if -coverpkg is in effect
  1006  			// p.Internal.Cover.GenMeta will wind up being set for
  1007  			// all matching packages.
  1008  			if len(p.TestGoFiles)+len(p.XTestGoFiles) == 0 && cfg.BuildCoverPkg == nil {
  1009  				p.Internal.Cover.GenMeta = true
  1010  			}
  1011  
  1012  			// Set coverage mode before building actions because it needs to be set
  1013  			// before the first package build action for the package under test is
  1014  			// created and cached, so that we can create the coverage action for it.
  1015  			if cfg.BuildCover {
  1016  				if p.Internal.Cover.GenMeta {
  1017  					p.Internal.Cover.Mode = cfg.BuildCoverMode
  1018  				}
  1019  			}
  1020  		}
  1021  	}
  1022  
  1023  	// Prepare build + run + print actions for all packages being tested.
  1024  	for _, p := range pkgs {
  1025  		reportErr := func(perr *load.Package, err error) {
  1026  			str := err.Error()
  1027  			if p.ImportPath != "" {
  1028  				load.DefaultPrinter().Errorf(perr, "# %s\n%s", p.ImportPath, str)
  1029  			} else {
  1030  				load.DefaultPrinter().Errorf(perr, "%s", str)
  1031  			}
  1032  		}
  1033  		reportSetupFailed := func(perr *load.Package, err error) {
  1034  			var stdout io.Writer = os.Stdout
  1035  			if testJSON {
  1036  				json := test2json.NewConverter(stdout, p.ImportPath, test2json.Timestamp)
  1037  				defer func() {
  1038  					json.Exited(err)
  1039  					json.Close()
  1040  				}()
  1041  				if gotestjsonbuildtext.Value() == "1" {
  1042  					// While this flag is about go build -json, the other effect
  1043  					// of that change was to include "FailedBuild" in the test JSON.
  1044  					gotestjsonbuildtext.IncNonDefault()
  1045  				} else {
  1046  					json.SetFailedBuild(perr.Desc())
  1047  				}
  1048  				stdout = json
  1049  			}
  1050  			fmt.Fprintf(stdout, "FAIL\t%s [setup failed]\n", p.ImportPath)
  1051  			base.SetExitStatus(1)
  1052  		}
  1053  
  1054  		var firstErrPkg *load.Package // arbitrarily report setup failed error for first error pkg reached in DFS
  1055  		load.PackageErrors([]*load.Package{p}, func(p *load.Package) {
  1056  			reportErr(p, p.Error)
  1057  			if firstErrPkg == nil {
  1058  				firstErrPkg = p
  1059  			}
  1060  		})
  1061  		if firstErrPkg != nil {
  1062  			reportSetupFailed(firstErrPkg, firstErrPkg.Error)
  1063  			continue
  1064  		}
  1065  		buildTest, runTest, printTest, perr, err := builderTest(moduleLoader, b, ctx, pkgOpts, p, allImports[p], writeCoverMetaAct)
  1066  		if err != nil {
  1067  			reportErr(perr, err)
  1068  			reportSetupFailed(perr, err)
  1069  			continue
  1070  		}
  1071  		builds = append(builds, buildTest)
  1072  		runs = append(runs, runTest)
  1073  		prints = append(prints, printTest)
  1074  	}
  1075  
  1076  	// Link the analysis tool, if any packages need it.
  1077  	if cfg.Experiment.VetFiles {
  1078  		buildAnalysisTool(moduleLoader, ctx, b, pkgOpts)
  1079  	}
  1080  
  1081  	// Order runs for coordinating start JSON prints via two mechanisms:
  1082  	// 1. Channel locking forces runTest actions to start in-order.
  1083  	// 2. Barrier tasks force runTest actions to be scheduled in-order.
  1084  	// We need both for performant behavior, as channel locking without the barrier tasks starves the worker pool,
  1085  	// and barrier tasks without channel locking doesn't guarantee start in-order behavior alone.
  1086  	var prevBarrier *work.Action
  1087  	ch := make(chan struct{})
  1088  	close(ch)
  1089  	for _, a := range runs {
  1090  		if r, ok := a.Actor.(*runTestActor); ok {
  1091  			// Inject a barrier task between the run action and its dependencies.
  1092  			// This barrier task wil also depend on the previous barrier task.
  1093  			// This prevents the run task from being scheduled until all previous run dependencies have finished.
  1094  			// The build graph will be augmented to look roughly like this:
  1095  			//	build("a")           build("b")           build("c")
  1096  			//	    |                   |                     |
  1097  			//	barrier("a.test") -> barrier("b.test") -> barrier("c.test")
  1098  			//	    |                   |                     |
  1099  			//	run("a.test")        run("b.test")        run("c.test")
  1100  
  1101  			barrier := &work.Action{
  1102  				Mode: "test barrier",
  1103  				Deps: slices.Clip(a.Deps),
  1104  			}
  1105  			if prevBarrier != nil {
  1106  				barrier.Deps = append(barrier.Deps, prevBarrier)
  1107  			}
  1108  			a.Deps = []*work.Action{barrier}
  1109  			prevBarrier = barrier
  1110  
  1111  			r.prev = ch
  1112  			ch = make(chan struct{})
  1113  			r.next = ch
  1114  		}
  1115  	}
  1116  
  1117  	// Ultimately the goal is to print the output.
  1118  	root := &work.Action{Mode: "go test", Actor: work.ActorFunc(printExitStatus), Deps: prints}
  1119  
  1120  	// Force the printing of results to happen in order,
  1121  	// one at a time.
  1122  	for i, a := range prints {
  1123  		if i > 0 {
  1124  			a.Deps = append(a.Deps, prints[i-1])
  1125  		}
  1126  	}
  1127  
  1128  	// Force benchmarks to run in serial.
  1129  	if !testC && (testBench != "") {
  1130  		// The first run must wait for all builds.
  1131  		// Later runs must wait for the previous run's print.
  1132  		for i, run := range runs {
  1133  			if i == 0 {
  1134  				run.Deps = append(run.Deps, builds...)
  1135  			} else {
  1136  				run.Deps = append(run.Deps, prints[i-1])
  1137  			}
  1138  		}
  1139  	}
  1140  
  1141  	b.Do(ctx, root)
  1142  }
  1143  
  1144  var windowsBadWords = []string{
  1145  	"install",
  1146  	"patch",
  1147  	"setup",
  1148  	"update",
  1149  }
  1150  
  1151  func builderTest(ld *modload.Loader, b *work.Builder, ctx context.Context, pkgOpts load.PackageOpts, p *load.Package, imported bool, writeCoverMetaAct *work.Action) (buildAction, runAction, printAction *work.Action, perr *load.Package, err error) {
  1152  	if len(p.TestGoFiles)+len(p.XTestGoFiles) == 0 {
  1153  		build := b.CompileAction(work.ModeBuild, work.ModeBuild, p)
  1154  		run := &work.Action{
  1155  			Mode:       "test run",
  1156  			Actor:      new(runTestActor),
  1157  			Deps:       []*work.Action{build},
  1158  			Objdir:     b.NewObjdir(),
  1159  			Package:    p,
  1160  			IgnoreFail: true, // run (prepare output) even if build failed
  1161  		}
  1162  		if writeCoverMetaAct != nil && build.Actor != nil {
  1163  			// There is no real "run" for this package (since there
  1164  			// are no tests), but if coverage is turned on, we can
  1165  			// collect coverage data for the code in the package by
  1166  			// asking cmd/cover for a static meta-data file as part of
  1167  			// the package build. This static meta-data file is then
  1168  			// consumed by a pseudo-action (writeCoverMetaAct) that
  1169  			// adds it to a summary file, then this summary file is
  1170  			// consumed by the various "run test" actions. Below we
  1171  			// add a dependence edge between the build action and the
  1172  			// "write meta files" pseudo-action, and then another dep
  1173  			// from writeCoverMetaAct to the run action. See the
  1174  			// comment in runTest() at the definition of
  1175  			// writeCoverMetaAct for more details.
  1176  			run.Deps = append(run.Deps, writeCoverMetaAct)
  1177  			writeCoverMetaAct.Deps = append(writeCoverMetaAct.Deps, build)
  1178  		}
  1179  		addTestVet(ld, b, p, run, nil)
  1180  		print := &work.Action{
  1181  			Mode:       "test print",
  1182  			Actor:      work.ActorFunc(builderPrintTest),
  1183  			Deps:       []*work.Action{run},
  1184  			Package:    p,
  1185  			IgnoreFail: true, // print even if test failed
  1186  		}
  1187  		return build, run, print, nil, nil
  1188  	}
  1189  
  1190  	// Build Package structs describing:
  1191  	//	pmain - pkg.test binary
  1192  	//	ptest - package + test files
  1193  	//	pxtest - package of external test files
  1194  	var cover *load.TestCover
  1195  	if cfg.BuildCover {
  1196  		cover = &load.TestCover{
  1197  			Mode:  cfg.BuildCoverMode,
  1198  			Local: cfg.BuildCoverPkg == nil,
  1199  			Pkgs:  testCoverPkgs,
  1200  			Paths: cfg.BuildCoverPkg,
  1201  		}
  1202  	}
  1203  	pmain, ptest, pxtest, perr := load.TestPackagesFor(ld, ctx, pkgOpts, p, cover)
  1204  	if perr != nil {
  1205  		return nil, nil, nil, perr, perr.Error
  1206  	}
  1207  
  1208  	// If imported is true then this package is imported by some
  1209  	// package being tested. Make building the test version of the
  1210  	// package depend on building the non-test version, so that we
  1211  	// only report build errors once. Issue #44624.
  1212  	if imported && ptest != p {
  1213  		exportTest := b.BuildExportAction(work.ModeBuild, work.ModeBuild, ptest)
  1214  		exportP := b.BuildExportAction(work.ModeBuild, work.ModeBuild, p)
  1215  		exportTest.Deps = append(exportTest.Deps, exportP)
  1216  	}
  1217  
  1218  	testBinary := testBinaryName(p)
  1219  
  1220  	// Set testdir to compile action's objdir.
  1221  	// so that the default file path stripping applies to _testmain.go.
  1222  	testDir := b.CompileAction(work.ModeBuild, work.ModeBuild, pmain).Objdir
  1223  	if err := b.BackgroundShell().Mkdir(testDir); err != nil {
  1224  		return nil, nil, nil, nil, err
  1225  	}
  1226  
  1227  	pmain.Dir = testDir
  1228  	pmain.Internal.OmitDebug = !testC && !testNeedBinary()
  1229  	if pmain.ImportPath == "runtime.test" {
  1230  		// The runtime package needs a symbolized binary for its tests.
  1231  		// See runtime/unsafepoint_test.go.
  1232  		pmain.Internal.OmitDebug = false
  1233  	}
  1234  
  1235  	if !cfg.BuildN {
  1236  		// writeTestmain writes _testmain.go,
  1237  		// using the test description gathered in t.
  1238  		if err := os.WriteFile(testDir+"_testmain.go", *pmain.Internal.TestmainGo, 0666); err != nil {
  1239  			return nil, nil, nil, nil, err
  1240  		}
  1241  	}
  1242  
  1243  	a := b.LinkAction(ld, work.ModeBuild, work.ModeBuild, pmain)
  1244  	a.Target = testDir + testBinary + cfg.ExeSuffix
  1245  	if cfg.Goos == "windows" {
  1246  		// There are many reserved words on Windows that,
  1247  		// if used in the name of an executable, cause Windows
  1248  		// to try to ask for extra permissions.
  1249  		// The word list includes setup, install, update, and patch,
  1250  		// but it does not appear to be defined anywhere.
  1251  		// We have run into this trying to run the
  1252  		// go.codereview/patch tests.
  1253  		// For package names containing those words, use test.test.exe
  1254  		// instead of pkgname.test.exe.
  1255  		// Note that this file name is only used in the Go command's
  1256  		// temporary directory. If the -c or other flags are
  1257  		// given, the code below will still use pkgname.test.exe.
  1258  		// There are two user-visible effects of this change.
  1259  		// First, you can actually run 'go test' in directories that
  1260  		// have names that Windows thinks are installer-like,
  1261  		// without getting a dialog box asking for more permissions.
  1262  		// Second, in the Windows process listing during go test,
  1263  		// the test shows up as test.test.exe, not pkgname.test.exe.
  1264  		// That second one is a drawback, but it seems a small
  1265  		// price to pay for the test running at all.
  1266  		// If maintaining the list of bad words is too onerous,
  1267  		// we could just do this always on Windows.
  1268  		for _, bad := range windowsBadWords {
  1269  			if strings.Contains(testBinary, bad) {
  1270  				a.Target = testDir + "test.test" + cfg.ExeSuffix
  1271  				break
  1272  			}
  1273  		}
  1274  	}
  1275  	buildAction = a
  1276  	var installAction, cleanAction *work.Action
  1277  	if testC || testNeedBinary() {
  1278  		// -c or profiling flag: create action to copy binary to ./test.out.
  1279  		target := filepath.Join(base.Cwd(), testBinary+cfg.ExeSuffix)
  1280  		isNull := false
  1281  
  1282  		if testO != "" {
  1283  			target = testO
  1284  
  1285  			if testODir {
  1286  				if filepath.IsAbs(target) {
  1287  					target = filepath.Join(target, testBinary+cfg.ExeSuffix)
  1288  				} else {
  1289  					target = filepath.Join(base.Cwd(), target, testBinary+cfg.ExeSuffix)
  1290  				}
  1291  			} else {
  1292  				if base.IsNull(target) {
  1293  					isNull = true
  1294  				} else if !filepath.IsAbs(target) {
  1295  					target = filepath.Join(base.Cwd(), target)
  1296  				}
  1297  			}
  1298  		}
  1299  
  1300  		if isNull {
  1301  			runAction = buildAction
  1302  		} else {
  1303  			pmain.Target = target
  1304  			installAction = &work.Action{
  1305  				Mode:    "test build",
  1306  				Actor:   work.ActorFunc(work.BuildInstallFunc),
  1307  				Deps:    []*work.Action{buildAction},
  1308  				Package: pmain,
  1309  				Target:  target,
  1310  			}
  1311  			runAction = installAction // make sure runAction != nil even if not running test
  1312  		}
  1313  	}
  1314  
  1315  	var vetRunAction *work.Action
  1316  	if testC {
  1317  		printAction = &work.Action{
  1318  			Mode:       "test print (nop)",
  1319  			Package:    p,
  1320  			Deps:       []*work.Action{runAction},
  1321  			IgnoreFail: true,
  1322  			Actor: work.ActorFunc(func(b *work.Builder, ctx context.Context, a *work.Action) error {
  1323  				if buildAction.Failed == nil {
  1324  					for _, dep := range a.Deps {
  1325  						if dep.Mode == "vet" && dep.Failed != nil {
  1326  							b.ReportDeferredVetError(dep.Failed)
  1327  						}
  1328  					}
  1329  				}
  1330  				return nil
  1331  			}),
  1332  		}
  1333  		vetRunAction = printAction
  1334  	} else {
  1335  		// run test
  1336  		rta := &runTestActor{
  1337  			writeCoverMetaAct: writeCoverMetaAct,
  1338  		}
  1339  		runAction = &work.Action{
  1340  			Mode:       "test run",
  1341  			Actor:      rta,
  1342  			Deps:       []*work.Action{buildAction},
  1343  			Package:    p,
  1344  			IgnoreFail: true, // run (prepare output) even if build failed
  1345  			TryCache:   rta.c.tryCache,
  1346  		}
  1347  		if writeCoverMetaAct != nil {
  1348  			// If writeCoverMetaAct != nil, this indicates that our
  1349  			// "go test -coverpkg" run actions will need to read the
  1350  			// meta-files summary file written by writeCoverMetaAct,
  1351  			// so add a dependence edge from writeCoverMetaAct to the
  1352  			// run action.
  1353  			runAction.Deps = append(runAction.Deps, writeCoverMetaAct)
  1354  			// The link action calls runAction.TryCache, which hashes
  1355  			// the build IDs of writeCoverMetaAct's dependencies. Those
  1356  			// include packages that are not linked into this test
  1357  			// binary, so add a dependence edge from writeCoverMetaAct
  1358  			// to the link action to make sure they have all finished
  1359  			// building before their build IDs are read.
  1360  			buildAction.Deps = append(buildAction.Deps, writeCoverMetaAct)
  1361  			if !p.IsTestOnly() {
  1362  				// Package p is not test only, meaning that the build
  1363  				// action for p may generate a static meta-data file.
  1364  				// Add a dependence edge from p to writeCoverMetaAct,
  1365  				// which needs to know the name of that meta-data
  1366  				// file.
  1367  				compileAction := b.CompileAction(work.ModeBuild, work.ModeBuild, p)
  1368  				writeCoverMetaAct.Deps = append(writeCoverMetaAct.Deps, compileAction)
  1369  			}
  1370  		}
  1371  		runAction.Objdir = testDir
  1372  		vetRunAction = runAction
  1373  		cleanAction = &work.Action{
  1374  			Mode:       "test clean",
  1375  			Actor:      work.ActorFunc(builderCleanTest),
  1376  			Deps:       []*work.Action{runAction},
  1377  			Package:    p,
  1378  			IgnoreFail: true, // clean even if test failed
  1379  			Objdir:     testDir,
  1380  		}
  1381  		printAction = &work.Action{
  1382  			Mode:       "test print",
  1383  			Actor:      work.ActorFunc(builderPrintTest),
  1384  			Deps:       []*work.Action{cleanAction},
  1385  			Package:    p,
  1386  			IgnoreFail: true, // print even if test failed
  1387  		}
  1388  	}
  1389  
  1390  	if len(ptest.GoFiles)+len(ptest.CgoFiles) > 0 {
  1391  		addTestVet(ld, b, ptest, vetRunAction, installAction)
  1392  	}
  1393  	if pxtest != nil {
  1394  		addTestVet(ld, b, pxtest, vetRunAction, installAction)
  1395  	}
  1396  
  1397  	if installAction != nil {
  1398  		if runAction != installAction {
  1399  			installAction.Deps = append(installAction.Deps, runAction)
  1400  		}
  1401  		if cleanAction != nil {
  1402  			cleanAction.Deps = append(cleanAction.Deps, installAction)
  1403  		}
  1404  	}
  1405  
  1406  	return buildAction, runAction, printAction, nil, nil
  1407  }
  1408  
  1409  func addTestVet(ld *modload.Loader, b *work.Builder, p *load.Package, runAction, installAction *work.Action) {
  1410  	if testVet.off {
  1411  		return
  1412  	}
  1413  	if cfg.Experiment.VetFiles && !analysisUsesCmdVet() {
  1414  		// Use the analysis driver instead of cmd/vet (see analysis.go).
  1415  		addTestAnalysis(ld, b, p, runAction, installAction)
  1416  		return
  1417  	}
  1418  
  1419  	vet := b.VetAction(p, false)
  1420  	runAction.Deps = append(runAction.Deps, vet)
  1421  	// Make sure vet succeeds before installing the test binary.
  1422  	if installAction != nil {
  1423  		installAction.Deps = append(installAction.Deps, vet)
  1424  	}
  1425  }
  1426  
  1427  var noTestsToRun = []byte("\ntesting: warning: no tests to run\n")
  1428  var noFuzzTestsToFuzz = []byte("\ntesting: warning: no fuzz tests to fuzz\n")
  1429  var tooManyFuzzTestsToFuzz = []byte("\ntesting: warning: -fuzz matches more than one fuzz test, won't fuzz\n")
  1430  
  1431  // runTestActor is the actor for running a test.
  1432  type runTestActor struct {
  1433  	c runCache
  1434  
  1435  	// writeCoverMetaAct points to the pseudo-action for collecting
  1436  	// coverage meta-data files for selected -cover test runs. See the
  1437  	// comment in runTest at the definition of writeCoverMetaAct for
  1438  	// more details.
  1439  	writeCoverMetaAct *work.Action
  1440  
  1441  	// sequencing of json start messages, to preserve test order
  1442  	prev <-chan struct{} // wait to start until prev is closed
  1443  	next chan<- struct{} // close next once the next test can start.
  1444  }
  1445  
  1446  // runCache is the cache for running a single test.
  1447  type runCache struct {
  1448  	disableCache bool // cache should be disabled for this run
  1449  
  1450  	buf     *bytes.Buffer
  1451  	id1     cache.ActionID
  1452  	id2     cache.ActionID
  1453  	covMeta cache.ActionID // Hash of writeCoverMetaAct dependencies, for invalidating coverage profiles
  1454  }
  1455  
  1456  func coverProfTempFile(a *work.Action) string {
  1457  	if a.Objdir == "" {
  1458  		panic("internal error: objdir not set in coverProfTempFile")
  1459  	}
  1460  	return a.Objdir + "_cover_.out"
  1461  }
  1462  
  1463  // stdoutMu and lockedStdout provide a locked standard output
  1464  // that guarantees never to interlace writes from multiple
  1465  // goroutines, so that we can have multiple JSON streams writing
  1466  // to a lockedStdout simultaneously and know that events will
  1467  // still be intelligible.
  1468  var stdoutMu sync.Mutex
  1469  
  1470  type lockedStdout struct{}
  1471  
  1472  func (lockedStdout) Write(b []byte) (int, error) {
  1473  	stdoutMu.Lock()
  1474  	defer stdoutMu.Unlock()
  1475  	return os.Stdout.Write(b)
  1476  }
  1477  
  1478  func (r *runTestActor) Act(b *work.Builder, ctx context.Context, a *work.Action) error {
  1479  	sh := b.Shell(a)
  1480  	barrierAction := a.Deps[0]
  1481  	buildAction := barrierAction.Deps[0]
  1482  
  1483  	// Wait for previous test to get started and print its first json line.
  1484  	select {
  1485  	case <-r.prev:
  1486  		// If should fail fast then release next test and exit.
  1487  		if testShouldFailFast.Load() {
  1488  			close(r.next)
  1489  			return nil
  1490  		}
  1491  	case <-base.Interrupted:
  1492  		// We can't wait for the previous test action to complete: we don't start
  1493  		// new actions after an interrupt, so if that action wasn't already running
  1494  		// it might never happen. Instead, just don't log anything for this action.
  1495  		base.SetExitStatus(1)
  1496  		return nil
  1497  	}
  1498  
  1499  	// Stream test output (no buffering) when no package has
  1500  	// been given on the command line (implicit current directory)
  1501  	// or when benchmarking or fuzzing.
  1502  	streamOutput := len(pkgArgs) == 0 || testBench != "" || testFuzz != ""
  1503  
  1504  	// If we're only running a single package under test or if parallelism is
  1505  	// set to 1, and if we're displaying all output (testShowPass), we can
  1506  	// hurry the output along, echoing it as soon as it comes in.
  1507  	// We still have to copy to &buf for caching the result. This special
  1508  	// case was introduced in Go 1.5 and is intentionally undocumented:
  1509  	// the exact details of output buffering are up to the go command and
  1510  	// subject to change. It would be nice to remove this special case
  1511  	// entirely, but it is surely very helpful to see progress being made
  1512  	// when tests are run on slow single-CPU ARM systems.
  1513  	//
  1514  	// If we're showing JSON output, then display output as soon as
  1515  	// possible even when multiple tests are being run: the JSON output
  1516  	// events are attributed to specific package tests, so interlacing them
  1517  	// is OK.
  1518  	streamAndCacheOutput := testShowPass() && (len(pkgs) == 1 || cfg.BuildP == 1) || testJSON
  1519  
  1520  	var stdout io.Writer = os.Stdout
  1521  	var err error
  1522  	var json *test2json.Converter
  1523  	if testJSON {
  1524  		json = test2json.NewConverter(lockedStdout{}, a.Package.ImportPath, test2json.Timestamp)
  1525  		defer func() {
  1526  			json.Exited(err)
  1527  			json.Close()
  1528  		}()
  1529  		stdout = json
  1530  	}
  1531  
  1532  	var buf bytes.Buffer
  1533  	if streamOutput {
  1534  		// No change to stdout.
  1535  	} else if streamAndCacheOutput {
  1536  		// Write both to stdout and buf, for possible saving
  1537  		// to cache, and for looking for the "no tests to run" message.
  1538  		stdout = io.MultiWriter(stdout, &buf)
  1539  	} else {
  1540  		stdout = &buf
  1541  	}
  1542  
  1543  	// Release next test to start (test2json.NewConverter writes the start event).
  1544  	close(r.next)
  1545  
  1546  	if a.Failed != nil {
  1547  		if buildAction.Failed == nil {
  1548  			for _, dep := range barrierAction.Deps {
  1549  				if dep.Mode == "vet" && dep.Failed != nil {
  1550  					b.ReportDeferredVetError(dep.Failed)
  1551  				}
  1552  			}
  1553  		} else {
  1554  			a.Failed = buildAction.Failed
  1555  		}
  1556  		// We were unable to build the binary.
  1557  		if json != nil && a.Failed.Package != nil {
  1558  			if gotestjsonbuildtext.Value() == "1" {
  1559  				gotestjsonbuildtext.IncNonDefault()
  1560  			} else {
  1561  				json.SetFailedBuild(a.Failed.Package.Desc())
  1562  			}
  1563  		}
  1564  		a.Failed = nil
  1565  		fmt.Fprintf(stdout, "FAIL\t%s [build failed]\n", a.Package.ImportPath)
  1566  		// Tell the JSON converter that this was a failure, not a passing run.
  1567  		err = errors.New("build failed")
  1568  		base.SetExitStatus(1)
  1569  		if stdout == &buf {
  1570  			a.TestOutput = &buf
  1571  		}
  1572  		return nil
  1573  	}
  1574  
  1575  	if p := a.Package; len(p.TestGoFiles)+len(p.XTestGoFiles) == 0 {
  1576  		reportNoTestFiles := true
  1577  		if cfg.BuildCover && p.Internal.Cover.GenMeta {
  1578  			if err := sh.Mkdir(a.Objdir); err != nil {
  1579  				return err
  1580  			}
  1581  			mf, err := work.BuildActionCoverMetaFile(a)
  1582  			if err != nil {
  1583  				return err
  1584  			} else if mf != "" {
  1585  				reportNoTestFiles = false
  1586  				// Write out "percent statements covered".
  1587  				if err := work.WriteCoveragePercent(b, a, mf, stdout); err != nil {
  1588  					return err
  1589  				}
  1590  				// If -coverprofile is in effect, then generate a
  1591  				// coverage profile fragment for this package and
  1592  				// merge it with the final -coverprofile output file.
  1593  				if coverMerge.f != nil {
  1594  					cp := coverProfTempFile(a)
  1595  					if err := work.WriteCoverageProfile(b, a, mf, cp, stdout); err != nil {
  1596  						return err
  1597  					}
  1598  					mergeCoverProfile(cp)
  1599  				}
  1600  			}
  1601  		}
  1602  		if reportNoTestFiles {
  1603  			fmt.Fprintf(stdout, "?   \t%s\t[no test files]\n", p.ImportPath)
  1604  		}
  1605  		if stdout == &buf {
  1606  			a.TestOutput = &buf
  1607  		}
  1608  		return nil
  1609  	}
  1610  
  1611  	if r.c.buf == nil {
  1612  		// We did not find a cached result using the link step action ID,
  1613  		// so we ran the link step. Try again now with the link output
  1614  		// content ID. The attempt using the action ID makes sure that
  1615  		// if the link inputs don't change, we reuse the cached test
  1616  		// result without even rerunning the linker. The attempt using
  1617  		// the link output (test binary) content ID makes sure that if
  1618  		// we have different link inputs but the same final binary,
  1619  		// we still reuse the cached test result.
  1620  		// c.saveOutput will store the result under both IDs.
  1621  		r.c.tryCacheWithID(b, a, buildAction.BuildContentID())
  1622  	}
  1623  	if r.c.buf != nil {
  1624  		if stdout != &buf {
  1625  			stdout.Write(r.c.buf.Bytes())
  1626  			r.c.buf.Reset()
  1627  		}
  1628  		a.TestOutput = r.c.buf
  1629  		return nil
  1630  	}
  1631  
  1632  	execCmd := work.FindExecCmd()
  1633  	testlogArg := []string{}
  1634  	if !r.c.disableCache && len(execCmd) == 0 {
  1635  		testlogArg = []string{"-test.testlogfile=" + a.Objdir + "testlog.txt"}
  1636  	}
  1637  	panicArg := "-test.paniconexit0"
  1638  	fuzzArg := []string{}
  1639  	if testFuzz != "" {
  1640  		fuzzCacheDir := filepath.Join(cache.Default().FuzzDir(), a.Package.ImportPath)
  1641  		fuzzArg = []string{"-test.fuzzcachedir=" + fuzzCacheDir}
  1642  	}
  1643  	coverdirArg := []string{}
  1644  	addToEnv := ""
  1645  	if cfg.BuildCover {
  1646  		gcd := filepath.Join(a.Objdir, "gocoverdir")
  1647  		if err := sh.Mkdir(gcd); err != nil {
  1648  			// If we can't create a temp dir, terminate immediately
  1649  			// with an error as opposed to returning an error to the
  1650  			// caller; failed MkDir most likely indicates that we're
  1651  			// out of disk space or there is some other systemic error
  1652  			// that will make forward progress unlikely.
  1653  			base.Fatalf("failed to create temporary dir: %v", err)
  1654  		}
  1655  		coverdirArg = append(coverdirArg, "-test.gocoverdir="+gcd)
  1656  		if r.writeCoverMetaAct != nil {
  1657  			// Copy the meta-files file over into the test's coverdir
  1658  			// directory so that the coverage runtime support will be
  1659  			// able to find it.
  1660  			src := r.writeCoverMetaAct.Objdir + coverage.MetaFilesFileName
  1661  			dst := filepath.Join(gcd, coverage.MetaFilesFileName)
  1662  			if err := sh.CopyFile(dst, src, 0666, false); err != nil {
  1663  				return err
  1664  			}
  1665  		}
  1666  		// Even though we are passing the -test.gocoverdir option to
  1667  		// the test binary, also set GOCOVERDIR as well. This is
  1668  		// intended to help with tests that run "go build" to build
  1669  		// fresh copies of tools to test as part of the testing.
  1670  		addToEnv = "GOCOVERDIR=" + gcd
  1671  	}
  1672  	args := str.StringList(execCmd, buildAction.BuiltTarget(), testlogArg, panicArg, fuzzArg, coverdirArg, testArgs)
  1673  
  1674  	if testCoverProfile != "" {
  1675  		// Write coverage to temporary profile, for merging later.
  1676  		for i, arg := range args {
  1677  			if strings.HasPrefix(arg, "-test.coverprofile=") {
  1678  				args[i] = "-test.coverprofile=" + coverProfTempFile(a)
  1679  			}
  1680  		}
  1681  	}
  1682  
  1683  	if cfg.BuildN || cfg.BuildX {
  1684  		sh.ShowCmd("", "%s", strings.Join(args, " "))
  1685  		if cfg.BuildN {
  1686  			return nil
  1687  		}
  1688  	}
  1689  
  1690  	// Normally, the test will terminate itself when the timeout expires,
  1691  	// but add a last-ditch deadline to detect and stop wedged binaries.
  1692  	ctx, cancel := context.WithTimeout(ctx, testKillTimeout)
  1693  	defer cancel()
  1694  
  1695  	// Now we're ready to actually run the command.
  1696  	//
  1697  	// If the -o flag is set, or if at some point we change cmd/go to start
  1698  	// copying test executables into the build cache, we may run into spurious
  1699  	// ETXTBSY errors on Unix platforms (see https://go.dev/issue/22315).
  1700  	//
  1701  	// Since we know what causes those, and we know that they should resolve
  1702  	// quickly (the ETXTBSY error will resolve as soon as the subprocess
  1703  	// holding the descriptor open reaches its 'exec' call), we retry them
  1704  	// in a loop.
  1705  
  1706  	var (
  1707  		cmd            *exec.Cmd
  1708  		t0             time.Time
  1709  		cancelKilled   = false
  1710  		cancelSignaled = false
  1711  	)
  1712  	for {
  1713  		cmd = exec.CommandContext(ctx, args[0], args[1:]...)
  1714  		cmd.Dir = a.Package.Dir
  1715  
  1716  		env := slices.Clip(cfg.OrigEnv)
  1717  		env = base.AppendPATH(env)
  1718  		env = base.AppendPWD(env, cmd.Dir)
  1719  		cmd.Env = env
  1720  		if addToEnv != "" {
  1721  			cmd.Env = append(cmd.Env, addToEnv)
  1722  		}
  1723  
  1724  		cmd.Stdout = stdout
  1725  		cmd.Stderr = stdout
  1726  
  1727  		cmd.Cancel = func() error {
  1728  			if base.SignalTrace == nil {
  1729  				err := cmd.Process.Kill()
  1730  				if err == nil {
  1731  					cancelKilled = true
  1732  				}
  1733  				return err
  1734  			}
  1735  
  1736  			// Send a quit signal in the hope that the program will print
  1737  			// a stack trace and exit.
  1738  			err := cmd.Process.Signal(base.SignalTrace)
  1739  			if err == nil {
  1740  				cancelSignaled = true
  1741  			}
  1742  			return err
  1743  		}
  1744  		cmd.WaitDelay = testWaitDelay
  1745  
  1746  		base.StartSigHandlers()
  1747  		t0 = time.Now()
  1748  		err = cmd.Run()
  1749  
  1750  		if !base.IsETXTBSY(err) {
  1751  			// We didn't hit the race in #22315, so there is no reason to retry the
  1752  			// command.
  1753  			break
  1754  		}
  1755  	}
  1756  
  1757  	out := buf.Bytes()
  1758  	a.TestOutput = &buf
  1759  	t := fmt.Sprintf("%.3fs", time.Since(t0).Seconds())
  1760  
  1761  	mergeCoverProfile(coverProfTempFile(a))
  1762  
  1763  	if err == nil {
  1764  		norun := ""
  1765  		if !testShowPass() && !testJSON {
  1766  			buf.Reset()
  1767  		}
  1768  		if bytes.HasPrefix(out, noTestsToRun[1:]) || bytes.Contains(out, noTestsToRun) {
  1769  			norun = " [no tests to run]"
  1770  		}
  1771  		if bytes.HasPrefix(out, noFuzzTestsToFuzz[1:]) || bytes.Contains(out, noFuzzTestsToFuzz) {
  1772  			norun = " [no fuzz tests to fuzz]"
  1773  		}
  1774  		if bytes.HasPrefix(out, tooManyFuzzTestsToFuzz[1:]) || bytes.Contains(out, tooManyFuzzTestsToFuzz) {
  1775  			norun = "[-fuzz matches more than one fuzz test, won't fuzz]"
  1776  		}
  1777  		// Ensure the output ends with a newline before the "ok" line
  1778  		// (https://golang.org/issue/49317). Check buf, which holds the
  1779  		// output still to be printed; out may include output that was
  1780  		// discarded above (https://go.dev/issue/79786).
  1781  		if buf.Len() > 0 && !bytes.HasSuffix(buf.Bytes(), []byte("\n")) {
  1782  			cmd.Stdout.Write([]byte("\n"))
  1783  		}
  1784  		fmt.Fprintf(cmd.Stdout, "ok  \t%s\t%s%s%s\n", a.Package.ImportPath, t, coveragePercentage(out), norun)
  1785  		r.c.saveOutput(a)
  1786  	} else {
  1787  		if testFailFast {
  1788  			testShouldFailFast.Store(true)
  1789  		}
  1790  
  1791  		base.SetExitStatus(1)
  1792  		if cancelSignaled {
  1793  			fmt.Fprintf(cmd.Stdout, "*** Test killed with %v: ran too long (%v).\n", base.SignalTrace, testKillTimeout)
  1794  		} else if cancelKilled {
  1795  			fmt.Fprintf(cmd.Stdout, "*** Test killed: ran too long (%v).\n", testKillTimeout)
  1796  		} else if errors.Is(err, exec.ErrWaitDelay) {
  1797  			fmt.Fprintf(cmd.Stdout, "*** Test I/O incomplete %v after exiting.\n", cmd.WaitDelay)
  1798  		}
  1799  		if ee, ok := errors.AsType[*exec.ExitError](err); !ok || !ee.Exited() || len(out) == 0 {
  1800  			// If there was no test output, print the exit status so that the reason
  1801  			// for failure is clear.
  1802  			fmt.Fprintf(cmd.Stdout, "%s\n", err)
  1803  		} else if !bytes.HasSuffix(out, []byte("\n")) {
  1804  			// Otherwise, ensure that the output ends with a newline before the FAIL
  1805  			// line we're about to print (https://golang.org/issue/49317).
  1806  			cmd.Stdout.Write([]byte("\n"))
  1807  		}
  1808  
  1809  		// NOTE(golang.org/issue/37555): test2json reports that a test passes
  1810  		// unless "FAIL" is printed at the beginning of a line. The test may not
  1811  		// actually print that if it panics, exits, or terminates abnormally,
  1812  		// so we print it here. We can't always check whether it was printed
  1813  		// because some tests need stdout to be a terminal (golang.org/issue/34791),
  1814  		// not a pipe.
  1815  		// TODO(golang.org/issue/29062): tests that exit with status 0 without
  1816  		// printing a final result should fail.
  1817  		prefix := ""
  1818  		if testJSON || testV.json {
  1819  			prefix = "\x16"
  1820  		}
  1821  		fmt.Fprintf(cmd.Stdout, "%sFAIL\t%s\t%s\n", prefix, a.Package.ImportPath, t)
  1822  	}
  1823  
  1824  	if cmd.Stdout != &buf {
  1825  		buf.Reset() // cmd.Stdout was going to os.Stdout already
  1826  	}
  1827  	return nil
  1828  }
  1829  
  1830  // tryCache is called just before the link attempt,
  1831  // to see if the test result is cached and therefore the link is unneeded.
  1832  // It reports whether the result can be satisfied from cache.
  1833  func (c *runCache) tryCache(b *work.Builder, a *work.Action, linkAction *work.Action) bool {
  1834  	return c.tryCacheWithID(b, a, linkAction.BuildActionID())
  1835  }
  1836  
  1837  func (c *runCache) tryCacheWithID(b *work.Builder, a *work.Action, id string) bool {
  1838  	if len(pkgArgs) == 0 {
  1839  		// Caching does not apply to "go test",
  1840  		// only to "go test foo" (including "go test .").
  1841  		if cache.DebugTest {
  1842  			fmt.Fprintf(os.Stderr, "testcache: caching disabled in local directory mode\n")
  1843  		}
  1844  		c.disableCache = true
  1845  		return false
  1846  	}
  1847  
  1848  	if a.Package.Root == "" {
  1849  		// Caching does not apply to tests outside of any module, GOPATH, or GOROOT.
  1850  		if cache.DebugTest {
  1851  			fmt.Fprintf(os.Stderr, "testcache: caching disabled for package outside of module root, GOPATH, or GOROOT: %s\n", a.Package.ImportPath)
  1852  		}
  1853  		c.disableCache = true
  1854  		return false
  1855  	}
  1856  
  1857  	// If we are collecting coverage for out-of-band packages (-coverpkg),
  1858  	// find the writeCoverMetaAct among the run action's dependencies and hash
  1859  	// its deps to ensure the cache invalidates when covered packages change.
  1860  	// Note: the run action's original deps may be wrapped inside a "test barrier"
  1861  	// action, so we search both a.Deps and any barrier's deps.
  1862  	// builderTest makes the link action depend on writeCoverMetaAct, so the
  1863  	// build IDs read here are final even when called from tryCache.
  1864  	if len(testCoverPkgs) != 0 {
  1865  		searchDeps := a.Deps
  1866  		for _, dep := range a.Deps {
  1867  			if dep.Mode == "test barrier" {
  1868  				searchDeps = dep.Deps
  1869  				break
  1870  			}
  1871  		}
  1872  		for _, dep := range searchDeps {
  1873  			if dep.Mode == "write coverage meta-data file" {
  1874  				h := cache.NewHash("covermeta")
  1875  				for _, metaDep := range dep.Deps {
  1876  					if aid := metaDep.BuildActionID(); aid != "" {
  1877  						fmt.Fprintf(h, "dep %s\n", aid)
  1878  					}
  1879  				}
  1880  				c.covMeta = h.Sum()
  1881  				break
  1882  			}
  1883  		}
  1884  	}
  1885  
  1886  	var cacheArgs []string
  1887  	for _, arg := range testArgs {
  1888  		i := strings.Index(arg, "=")
  1889  		if i < 0 || !strings.HasPrefix(arg, "-test.") {
  1890  			if cache.DebugTest {
  1891  				fmt.Fprintf(os.Stderr, "testcache: caching disabled for test argument: %s\n", arg)
  1892  			}
  1893  			c.disableCache = true
  1894  			return false
  1895  		}
  1896  		switch arg[:i] {
  1897  		case "-test.benchtime",
  1898  			"-test.cpu",
  1899  			"-test.list",
  1900  			"-test.parallel",
  1901  			"-test.run",
  1902  			"-test.short",
  1903  			"-test.skip",
  1904  			"-test.timeout",
  1905  			"-test.failfast",
  1906  			"-test.v",
  1907  			"-test.fullpath":
  1908  			// These are cacheable.
  1909  			// Note that this list is documented above,
  1910  			// so if you add to this list, update the docs too.
  1911  			cacheArgs = append(cacheArgs, arg)
  1912  		case "-test.coverprofile",
  1913  			"-test.outputdir":
  1914  			// These are cacheable and do not invalidate the cache when they change.
  1915  			// Note that this list is documented above,
  1916  			// so if you add to this list, update the docs too.
  1917  		default:
  1918  			// nothing else is cacheable
  1919  			if cache.DebugTest {
  1920  				fmt.Fprintf(os.Stderr, "testcache: caching disabled for test argument: %s\n", arg)
  1921  			}
  1922  			c.disableCache = true
  1923  			return false
  1924  		}
  1925  	}
  1926  
  1927  	// The test cache result fetch is a two-level lookup.
  1928  	//
  1929  	// First, we use the content hash of the test binary
  1930  	// and its command-line arguments to find the
  1931  	// list of environment variables and files consulted
  1932  	// the last time the test was run with those arguments.
  1933  	// (To avoid unnecessary links, we store this entry
  1934  	// under two hashes: id1 uses the linker inputs as a
  1935  	// proxy for the test binary, and id2 uses the actual
  1936  	// test binary. If the linker inputs are unchanged,
  1937  	// this way we avoid the link step, even though we
  1938  	// do not cache link outputs.)
  1939  	//
  1940  	// Second, we compute a hash of the values of the
  1941  	// environment variables and the content of the files
  1942  	// listed in the log from the previous run.
  1943  	// Then we look up test output using a combination of
  1944  	// the hash from the first part (testID) and the hash of the
  1945  	// test inputs (testInputsID).
  1946  	//
  1947  	// In order to store a new test result, we must redo the
  1948  	// testInputsID computation using the log from the run
  1949  	// we want to cache, and then we store that new log and
  1950  	// the new outputs.
  1951  
  1952  	h := cache.NewHash("testResult")
  1953  	fmt.Fprintf(h, "test binary %s args %q execcmd %q", id, cacheArgs, work.ExecCmd)
  1954  	testID := h.Sum()
  1955  	if c.id1 == (cache.ActionID{}) {
  1956  		c.id1 = testID
  1957  	} else {
  1958  		c.id2 = testID
  1959  	}
  1960  	if cache.DebugTest {
  1961  		fmt.Fprintf(os.Stderr, "testcache: %s: test ID %x => %x\n", a.Package.ImportPath, id, testID)
  1962  	}
  1963  
  1964  	// Load list of referenced environment variables and files
  1965  	// from last run of testID, and compute hash of that content.
  1966  	data, entry, err := cache.GetBytes(cache.Default(), testID)
  1967  	if !bytes.HasPrefix(data, testlogMagic) || data[len(data)-1] != '\n' {
  1968  		if cache.DebugTest {
  1969  			if err != nil {
  1970  				fmt.Fprintf(os.Stderr, "testcache: %s: input list not found: %v\n", a.Package.ImportPath, err)
  1971  			} else {
  1972  				fmt.Fprintf(os.Stderr, "testcache: %s: input list malformed\n", a.Package.ImportPath)
  1973  			}
  1974  		}
  1975  		return false
  1976  	}
  1977  	testInputsID, err := computeTestInputsID(a, data, nil)
  1978  	if err != nil {
  1979  		return false
  1980  	}
  1981  	if cache.DebugTest {
  1982  		fmt.Fprintf(os.Stderr, "testcache: %s: test ID %x => input ID %x => %x\n", a.Package.ImportPath, testID, testInputsID, testAndInputKey(testID, testInputsID))
  1983  	}
  1984  
  1985  	// Parse cached result in preparation for changing run time to "(cached)".
  1986  	// If we can't parse the cached result, don't use it.
  1987  	data, entry, err = cache.GetBytes(cache.Default(), testAndInputKey(testID, testInputsID))
  1988  
  1989  	// Merge cached cover profile data to cover profile.
  1990  	if testCoverProfile != "" {
  1991  		// Specifically ignore entry as it will be the same as above.
  1992  		cpData, _, err := cache.GetFile(cache.Default(), coverProfileAndInputKey(testID, testInputsID, c.covMeta))
  1993  		if err != nil {
  1994  			if cache.DebugTest {
  1995  				fmt.Fprintf(os.Stderr, "testcache: %s: cached cover profile missing: %v\n", a.Package.ImportPath, err)
  1996  			}
  1997  			return false
  1998  		}
  1999  		mergeCoverProfile(cpData)
  2000  	} else if c.covMeta != (cache.ActionID{}) {
  2001  		// If we have a coverage metadata hash but no testCoverProfile, we're collecting
  2002  		// coverage for out-of-band packages. Check if the coverage profile cache is still
  2003  		// valid. If c.covMeta changed (meaning a covered package changed), the coverage
  2004  		// profile cache will miss and we need to re-run the test.
  2005  		_, _, err := cache.GetFile(cache.Default(), coverProfileAndInputKey(testID, testInputsID, c.covMeta))
  2006  		if err != nil {
  2007  			if cache.DebugTest {
  2008  				fmt.Fprintf(os.Stderr, "testcache: %s: coverage metadata changed, re-running test: %v\n", a.Package.ImportPath, err)
  2009  			}
  2010  			return false
  2011  		}
  2012  	}
  2013  
  2014  	if len(data) == 0 || data[len(data)-1] != '\n' {
  2015  		if cache.DebugTest {
  2016  			if err != nil {
  2017  				fmt.Fprintf(os.Stderr, "testcache: %s: test output not found: %v\n", a.Package.ImportPath, err)
  2018  			} else {
  2019  				fmt.Fprintf(os.Stderr, "testcache: %s: test output malformed\n", a.Package.ImportPath)
  2020  			}
  2021  		}
  2022  		return false
  2023  	}
  2024  	if entry.Time.Before(testCacheExpire) {
  2025  		if cache.DebugTest {
  2026  			fmt.Fprintf(os.Stderr, "testcache: %s: test output expired due to go clean -testcache\n", a.Package.ImportPath)
  2027  		}
  2028  		return false
  2029  	}
  2030  	i := bytes.LastIndexByte(data[:len(data)-1], '\n') + 1
  2031  	if !bytes.HasPrefix(data[i:], []byte("ok  \t")) {
  2032  		if cache.DebugTest {
  2033  			fmt.Fprintf(os.Stderr, "testcache: %s: test output malformed\n", a.Package.ImportPath)
  2034  		}
  2035  		return false
  2036  	}
  2037  	j := bytes.IndexByte(data[i+len("ok  \t"):], '\t')
  2038  	if j < 0 {
  2039  		if cache.DebugTest {
  2040  			fmt.Fprintf(os.Stderr, "testcache: %s: test output malformed\n", a.Package.ImportPath)
  2041  		}
  2042  		return false
  2043  	}
  2044  	j += i + len("ok  \t") + 1
  2045  
  2046  	// Committed to printing.
  2047  	c.buf = new(bytes.Buffer)
  2048  	c.buf.Write(data[:j])
  2049  	c.buf.WriteString("(cached)")
  2050  	for j < len(data) && ('0' <= data[j] && data[j] <= '9' || data[j] == '.' || data[j] == 's') {
  2051  		j++
  2052  	}
  2053  	c.buf.Write(data[j:])
  2054  	return true
  2055  }
  2056  
  2057  var errBadTestInputs = errors.New("error parsing test inputs")
  2058  var errFileNotInRoot = errors.New("file used as input is not in package root")
  2059  var testlogMagic = []byte("# test log\n") // known to testing/internal/testdeps/deps.go
  2060  
  2061  // logOp is a test log operation like stat or getenv.
  2062  type logOp struct {
  2063  	op   string
  2064  	name string
  2065  }
  2066  
  2067  // testInputsQueue limits total concurrency for computeTestInputsID.
  2068  var testInputsQueue = par.NewQueue(runtime.GOMAXPROCS(0))
  2069  
  2070  // computeTestInputsID computes the "test inputs ID"
  2071  // (see comment in tryCacheWithID above) for the
  2072  // test log. If inputs is not nil, computeTestInputsID writes
  2073  // to it a test log of just the entries that the ID depends on.
  2074  //
  2075  // testing/internal/testdeps omits an entry it has already written
  2076  // since the last chdir, so what an entry contributes here must not
  2077  // depend on how many times the test used that input.
  2078  func computeTestInputsID(a *work.Action, testlog []byte, inputs *bytes.Buffer) (cache.ActionID, error) {
  2079  	testlog = bytes.TrimPrefix(testlog, testlogMagic)
  2080  	h := cache.NewHash("testInputs")
  2081  	// The runtime always looks at GODEBUG, without telling us in the testlog.
  2082  	fmt.Fprintf(h, "getenv GODEBUG %x\n", hashGetenv("GODEBUG"))
  2083  	pwd := a.Package.Dir
  2084  
  2085  	// We do two passes. First, we build up the list of test log ops and resolve those concurrently.
  2086  	// Second, we compute our final hash combining all our operations in the original test log order.
  2087  	// The error checking of the test log file is done on the first pass.
  2088  	// Returning errors for file operations is delayed until the second pass (to keep error reporting deterministic).
  2089  
  2090  	// Gather our test log ops.
  2091  	var logOps []logOp
  2092  	var logOpCache par.ErrCache[logOp, cache.ActionID]
  2093  	work := make(map[logOp]func())
  2094  	add := func(op, name string, f func() (cache.ActionID, error)) {
  2095  		logOp := logOp{op: op, name: name}
  2096  		logOps = append(logOps, logOp)
  2097  		work[logOp] = func() { logOpCache.Do(logOp, f) }
  2098  	}
  2099  	for _, line := range bytes.Split(testlog, []byte("\n")) {
  2100  		if len(line) == 0 {
  2101  			continue
  2102  		}
  2103  		s := string(line)
  2104  		op, name, found := strings.Cut(s, " ")
  2105  		if !found {
  2106  			if cache.DebugTest {
  2107  				fmt.Fprintf(os.Stderr, "testcache: %s: input list malformed (%q)\n", a.Package.ImportPath, line)
  2108  			}
  2109  			return cache.ActionID{}, errBadTestInputs
  2110  		}
  2111  		switch op {
  2112  		default:
  2113  			if cache.DebugTest {
  2114  				fmt.Fprintf(os.Stderr, "testcache: %s: input list malformed (%q)\n", a.Package.ImportPath, line)
  2115  			}
  2116  			return cache.ActionID{}, errBadTestInputs
  2117  		case "getenv":
  2118  			add(op, name, func() (cache.ActionID, error) {
  2119  				return hashGetenv(name), nil
  2120  			})
  2121  		case "chdir":
  2122  			pwd = name // always absolute
  2123  			add(op, name, func() (cache.ActionID, error) {
  2124  				return hashStat(name), nil
  2125  			})
  2126  		case "stat":
  2127  			if !filepath.IsAbs(name) {
  2128  				name = filepath.Join(pwd, name)
  2129  			}
  2130  			add(op, name, func() (cache.ActionID, error) {
  2131  				if a.Package.Root == "" || search.InDir(name, a.Package.Root) == "" {
  2132  					// Do not recheck files outside the module, GOPATH, or GOROOT root.
  2133  					return cache.ActionID{}, errFileNotInRoot
  2134  				}
  2135  				return hashStat(name), nil
  2136  			})
  2137  		case "open":
  2138  			if !filepath.IsAbs(name) {
  2139  				name = filepath.Join(pwd, name)
  2140  			}
  2141  			add(op, name, func() (cache.ActionID, error) {
  2142  				if a.Package.Root == "" || search.InDir(name, a.Package.Root) == "" {
  2143  					// Do not recheck files outside the module, GOPATH, or GOROOT root.
  2144  					return cache.ActionID{}, errFileNotInRoot
  2145  				}
  2146  				return hashOpen(name)
  2147  			})
  2148  		}
  2149  	}
  2150  
  2151  	// Create chunks of work and do the operations.
  2152  	// The chunks are randomized courtesy of the map.
  2153  	chunkCount := 10 * runtime.GOMAXPROCS(0)                 // above GOMAXPROCS to help stragglers
  2154  	chunkSize := max((len(work)+chunkCount-1)/chunkCount, 1) // round up, at least 1
  2155  	var wg sync.WaitGroup
  2156  	for chunk := range slices.Chunk(slices.Collect(maps.Values(work)), chunkSize) {
  2157  		wg.Add(1)
  2158  		testInputsQueue.Add(func() {
  2159  			defer wg.Done()
  2160  			for _, f := range chunk {
  2161  				f()
  2162  			}
  2163  		})
  2164  	}
  2165  	wg.Wait()
  2166  
  2167  	// We have all the test log op results now.
  2168  	// Next, combine them in the original order for the final hash.
  2169  	if inputs != nil {
  2170  		inputs.Write(testlogMagic)
  2171  	}
  2172  	for _, l := range logOps {
  2173  		op, name := l.op, l.name
  2174  		actionID, err := logOpCache.Get(logOp{op: op, name: name})
  2175  		switch {
  2176  		case errors.Is(err, par.ErrCacheEntryNotFound):
  2177  			panic("failed to find expected test log cache result")
  2178  		case errors.Is(err, errFileNotInRoot):
  2179  			continue
  2180  		case err != nil:
  2181  			if cache.DebugTest {
  2182  				fmt.Fprintf(os.Stderr, "testcache: %s: input file %s: %s\n", a.Package.ImportPath, name, err)
  2183  			}
  2184  			return cache.ActionID{}, err
  2185  		}
  2186  
  2187  		fmt.Fprintf(h, "%s %s %x\n", op, name, actionID)
  2188  		if inputs != nil {
  2189  			fmt.Fprintf(inputs, "%s %s\n", op, name)
  2190  		}
  2191  	}
  2192  
  2193  	sum := h.Sum()
  2194  	return sum, nil
  2195  }
  2196  
  2197  func hashGetenv(name string) cache.ActionID {
  2198  	h := cache.NewHash("getenv")
  2199  	v, ok := os.LookupEnv(name)
  2200  	if !ok {
  2201  		h.Write([]byte{0})
  2202  	} else {
  2203  		h.Write([]byte{1})
  2204  		h.Write([]byte(v))
  2205  	}
  2206  	return h.Sum()
  2207  }
  2208  
  2209  const modTimeCutoff = 2 * time.Second
  2210  
  2211  var errFileTooNew = errors.New("file used as input is too new")
  2212  
  2213  func hashOpen(name string) (cache.ActionID, error) {
  2214  	h := cache.NewHash("open")
  2215  	info, err := os.Stat(name)
  2216  	if err != nil {
  2217  		fmt.Fprintf(h, "err %v\n", err)
  2218  		return h.Sum(), nil
  2219  	}
  2220  	hashWriteStat(h, info)
  2221  	if info.IsDir() {
  2222  		files, err := os.ReadDir(name)
  2223  		if err != nil {
  2224  			fmt.Fprintf(h, "err %v\n", err)
  2225  		}
  2226  		for _, f := range files {
  2227  			fmt.Fprintf(h, "file %s ", f.Name())
  2228  			finfo, err := f.Info()
  2229  			if err != nil {
  2230  				fmt.Fprintf(h, "err %v\n", err)
  2231  			} else {
  2232  				hashWriteStat(h, finfo)
  2233  			}
  2234  		}
  2235  	} else if info.Mode().IsRegular() {
  2236  		// Because files might be very large, do not attempt
  2237  		// to hash the entirety of their content. Instead assume
  2238  		// the mtime and size recorded in hashWriteStat above
  2239  		// are good enough.
  2240  		//
  2241  		// To avoid problems for very recent files where a new
  2242  		// write might not change the mtime due to file system
  2243  		// mtime precision, reject caching if a file was read that
  2244  		// is less than modTimeCutoff old.
  2245  		if time.Since(info.ModTime()) < modTimeCutoff {
  2246  			return cache.ActionID{}, errFileTooNew
  2247  		}
  2248  	}
  2249  	return h.Sum(), nil
  2250  }
  2251  
  2252  func hashStat(name string) cache.ActionID {
  2253  	h := cache.NewHash("stat")
  2254  	if info, err := os.Stat(name); err != nil {
  2255  		fmt.Fprintf(h, "err %v\n", err)
  2256  	} else {
  2257  		hashWriteStat(h, info)
  2258  	}
  2259  	if info, err := os.Lstat(name); err != nil {
  2260  		fmt.Fprintf(h, "err %v\n", err)
  2261  	} else {
  2262  		hashWriteStat(h, info)
  2263  	}
  2264  	return h.Sum()
  2265  }
  2266  
  2267  func hashWriteStat(h io.Writer, info fs.FileInfo) {
  2268  	fmt.Fprintf(h, "stat %d %x %v %v\n", info.Size(), uint64(info.Mode()), info.ModTime(), info.IsDir())
  2269  }
  2270  
  2271  // testAndInputKey returns the actual cache key for the pair (testID, testInputsID).
  2272  func testAndInputKey(testID, testInputsID cache.ActionID) cache.ActionID {
  2273  	return cache.Subkey(testID, fmt.Sprintf("inputs:%x", testInputsID))
  2274  }
  2275  
  2276  // coverProfileAndInputKey returns the "coverprofile" cache key.
  2277  // If covMetaID is non-zero, it is included in the hash to ensure coverage profiles are invalidated
  2278  // when the coverage metadata changes (e.g., when source files in covered packages are modified).
  2279  func coverProfileAndInputKey(testID, testInputsID, covMetaID cache.ActionID) cache.ActionID {
  2280  	key := testAndInputKey(testID, testInputsID)
  2281  	if covMetaID != (cache.ActionID{}) {
  2282  		key = cache.Subkey(key, fmt.Sprintf("coverdeps:%x", covMetaID))
  2283  	}
  2284  	return cache.Subkey(key, "coverprofile")
  2285  }
  2286  
  2287  func (c *runCache) saveOutput(a *work.Action) {
  2288  	if c.id1 == (cache.ActionID{}) && c.id2 == (cache.ActionID{}) {
  2289  		return
  2290  	}
  2291  
  2292  	// See comment about two-level lookup in tryCacheWithID above.
  2293  	testlog, err := os.ReadFile(a.Objdir + "testlog.txt")
  2294  	if err != nil || !bytes.HasPrefix(testlog, testlogMagic) || testlog[len(testlog)-1] != '\n' {
  2295  		if cache.DebugTest {
  2296  			if err != nil {
  2297  				fmt.Fprintf(os.Stderr, "testcache: %s: reading testlog: %v\n", a.Package.ImportPath, err)
  2298  			} else {
  2299  				fmt.Fprintf(os.Stderr, "testcache: %s: reading testlog: malformed\n", a.Package.ImportPath)
  2300  			}
  2301  		}
  2302  		return
  2303  	}
  2304  	// Store only the entries that went into testInputsID: the rest are
  2305  	// outside the package root, and checking them again on every cache
  2306  	// lookup can take longer than running the test (go.dev/issue/26562).
  2307  	var inputs bytes.Buffer
  2308  	testInputsID, err := computeTestInputsID(a, testlog, &inputs)
  2309  	if err != nil {
  2310  		return
  2311  	}
  2312  	testlog = inputs.Bytes()
  2313  	var coverProfile []byte
  2314  	if testCoverProfile != "" {
  2315  		coverProfile, err = os.ReadFile(coverProfTempFile(a))
  2316  		if err != nil {
  2317  			if cache.DebugTest {
  2318  				fmt.Fprintf(os.Stderr, "testcache: %s: reading cover profile: %v\n", a.Package.ImportPath, err)
  2319  			}
  2320  			return
  2321  		}
  2322  	}
  2323  	if c.id1 != (cache.ActionID{}) {
  2324  		if cache.DebugTest {
  2325  			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))
  2326  		}
  2327  		cache.PutNoVerify(cache.Default(), c.id1, bytes.NewReader(testlog))
  2328  		cache.PutNoVerify(cache.Default(), testAndInputKey(c.id1, testInputsID), bytes.NewReader(a.TestOutput.Bytes()))
  2329  		if coverProfile != nil {
  2330  			cache.PutNoVerify(cache.Default(), coverProfileAndInputKey(c.id1, testInputsID, c.covMeta), bytes.NewReader(coverProfile))
  2331  		} else if c.covMeta != (cache.ActionID{}) {
  2332  			// Write a sentinel so the else-if branch in tryCacheWithID can verify
  2333  			// that the covMeta hash has not changed since the last run.
  2334  			cache.PutNoVerify(cache.Default(), coverProfileAndInputKey(c.id1, testInputsID, c.covMeta), bytes.NewReader(nil))
  2335  		}
  2336  	}
  2337  	if c.id2 != (cache.ActionID{}) {
  2338  		if cache.DebugTest {
  2339  			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))
  2340  		}
  2341  		cache.PutNoVerify(cache.Default(), c.id2, bytes.NewReader(testlog))
  2342  		cache.PutNoVerify(cache.Default(), testAndInputKey(c.id2, testInputsID), bytes.NewReader(a.TestOutput.Bytes()))
  2343  		if coverProfile != nil {
  2344  			cache.PutNoVerify(cache.Default(), coverProfileAndInputKey(c.id2, testInputsID, c.covMeta), bytes.NewReader(coverProfile))
  2345  		} else if c.covMeta != (cache.ActionID{}) {
  2346  			// Sentinel for covMeta validity; see comment in id1 block above.
  2347  			cache.PutNoVerify(cache.Default(), coverProfileAndInputKey(c.id2, testInputsID, c.covMeta), bytes.NewReader(nil))
  2348  		}
  2349  	}
  2350  }
  2351  
  2352  // coveragePercentage returns the coverage results (if enabled) for the
  2353  // test. It uncovers the data by scanning the output from the test run.
  2354  func coveragePercentage(out []byte) string {
  2355  	if !cfg.BuildCover {
  2356  		return ""
  2357  	}
  2358  	// The string looks like
  2359  	//	test coverage for encoding/binary: 79.9% of statements
  2360  	// Extract the piece from the percentage to the end of the line.
  2361  	re := regexp.MustCompile(`coverage: (.*)\n`)
  2362  	matches := re.FindSubmatch(out)
  2363  	if matches == nil {
  2364  		// Probably running "go test -cover" not "go test -cover fmt".
  2365  		// The coverage output will appear in the output directly.
  2366  		return ""
  2367  	}
  2368  	return fmt.Sprintf("\tcoverage: %s", matches[1])
  2369  }
  2370  
  2371  // builderCleanTest is the action for cleaning up after a test.
  2372  func builderCleanTest(b *work.Builder, ctx context.Context, a *work.Action) error {
  2373  	if cfg.BuildWork {
  2374  		return nil
  2375  	}
  2376  	b.Shell(a).RemoveAll(a.Objdir)
  2377  	return nil
  2378  }
  2379  
  2380  // builderPrintTest is the action for printing a test result.
  2381  func builderPrintTest(b *work.Builder, ctx context.Context, a *work.Action) error {
  2382  	run := a.Deps[0]
  2383  	if run.Mode == "test clean" {
  2384  		run = run.Deps[0]
  2385  	}
  2386  	if run.Mode != "test run" {
  2387  		base.Fatalf("internal error: cannot find test run to print")
  2388  	}
  2389  	if run.TestOutput != nil {
  2390  		os.Stdout.Write(run.TestOutput.Bytes())
  2391  		run.TestOutput = nil
  2392  	}
  2393  	return nil
  2394  }
  2395  
  2396  // printExitStatus is the action for printing the final exit status.
  2397  // If we are running multiple test targets, print a final "FAIL"
  2398  // in case a failure in an early package has already scrolled
  2399  // off of the user's terminal.
  2400  // (See https://golang.org/issue/30507#issuecomment-470593235.)
  2401  //
  2402  // In JSON mode, we need to maintain valid JSON output and
  2403  // we assume that the test output is being parsed by a tool
  2404  // anyway, so the failure will not be missed and would be
  2405  // awkward to try to wedge into the JSON stream.
  2406  //
  2407  // In fuzz mode, we only allow a single package for now
  2408  // (see CL 350156 and https://golang.org/issue/46312),
  2409  // so there is no possibility of scrolling off and no need
  2410  // to print the final status.
  2411  func printExitStatus(b *work.Builder, ctx context.Context, a *work.Action) error {
  2412  	if !testJSON && testFuzz == "" && len(pkgArgs) != 0 {
  2413  		if base.GetExitStatus() != 0 {
  2414  			fmt.Println("FAIL")
  2415  			return nil
  2416  		}
  2417  	}
  2418  	return nil
  2419  }
  2420  
  2421  // testBinaryName can be used to create name for test binary executable.
  2422  // Use last element of import path, not package name.
  2423  // They differ when package name is "main".
  2424  // But if the import path is "command-line-arguments",
  2425  // like it is during 'go run', use the package name.
  2426  func testBinaryName(p *load.Package) string {
  2427  	var elem string
  2428  	if p.ImportPath == "command-line-arguments" {
  2429  		elem = p.Name
  2430  	} else {
  2431  		elem = p.DefaultExecName()
  2432  	}
  2433  
  2434  	return elem + ".test"
  2435  }
  2436  

View as plain text