Source file src/testing/testing.go

     1  // Copyright 2009 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 testing provides support for automated testing of Go packages.
     6  // It is intended to be used in concert with the "go test" command, which automates
     7  // execution of any function of the form
     8  //
     9  //	func TestXxx(*testing.T)
    10  //
    11  // where Xxx does not start with a lowercase letter. The function name
    12  // serves to identify the test routine.
    13  //
    14  // Within these functions, use the Error, Fail or related methods to signal failure.
    15  //
    16  // To write a new test suite, create a file that
    17  // contains the TestXxx functions as described here,
    18  // and give that file a name ending in "_test.go".
    19  // The file will be excluded from regular
    20  // package builds but will be included when the "go test" command is run.
    21  //
    22  // The test file can be in the same package as the one being tested,
    23  // or in a corresponding package with the suffix "_test".
    24  //
    25  // If the test file is in the same package, it may refer to unexported
    26  // identifiers within the package, as in this example:
    27  //
    28  //	package abs
    29  //
    30  //	import "testing"
    31  //
    32  //	func TestAbs(t *testing.T) {
    33  //	    got := Abs(-1)
    34  //	    if got != 1 {
    35  //	        t.Errorf("Abs(-1) = %d; want 1", got)
    36  //	    }
    37  //	}
    38  //
    39  // If the file is in a separate "_test" package, the package being tested
    40  // must be imported explicitly and only its exported identifiers may be used.
    41  // This is known as "black box" testing.
    42  //
    43  //	package abs_test
    44  //
    45  //	import (
    46  //		"testing"
    47  //
    48  //		"path_to_pkg/abs"
    49  //	)
    50  //
    51  //	func TestAbs(t *testing.T) {
    52  //	    got := abs.Abs(-1)
    53  //	    if got != 1 {
    54  //	        t.Errorf("Abs(-1) = %d; want 1", got)
    55  //	    }
    56  //	}
    57  //
    58  // For more detail, run "go help test" and "go help testflag".
    59  //
    60  // # Benchmarks
    61  //
    62  // Functions of the form
    63  //
    64  //	func BenchmarkXxx(*testing.B)
    65  //
    66  // are considered benchmarks, and are executed by the "go test" command when
    67  // its -bench flag is provided. Benchmarks are run sequentially.
    68  //
    69  // For a description of the testing flags, see
    70  // https://golang.org/cmd/go/#hdr-Testing_flags.
    71  //
    72  // A sample benchmark function looks like this:
    73  //
    74  //	func BenchmarkRandInt(b *testing.B) {
    75  //	    for b.Loop() {
    76  //	        rand.Int()
    77  //	    }
    78  //	}
    79  //
    80  // The output
    81  //
    82  //	BenchmarkRandInt-8   	68453040	        17.8 ns/op
    83  //
    84  // means that the body of the loop ran 68453040 times at a speed of 17.8 ns per loop.
    85  //
    86  // Only the body of the loop is timed, so benchmarks may do expensive
    87  // setup before calling b.Loop, which will not be counted toward the
    88  // benchmark measurement:
    89  //
    90  //	func BenchmarkBigLen(b *testing.B) {
    91  //	    big := NewBig()
    92  //	    for b.Loop() {
    93  //	        big.Len()
    94  //	    }
    95  //	}
    96  //
    97  // If a benchmark needs to test performance in a parallel setting, it may use
    98  // the RunParallel helper function; such benchmarks are intended to be used with
    99  // the go test -cpu flag:
   100  //
   101  //	func BenchmarkTemplateParallel(b *testing.B) {
   102  //	    templ := template.Must(template.New("test").Parse("Hello, {{.}}!"))
   103  //	    b.RunParallel(func(pb *testing.PB) {
   104  //	        var buf bytes.Buffer
   105  //	        for pb.Next() {
   106  //	            buf.Reset()
   107  //	            templ.Execute(&buf, "World")
   108  //	        }
   109  //	    })
   110  //	}
   111  //
   112  // A detailed specification of the benchmark results format is given
   113  // in https://golang.org/design/14313-benchmark-format.
   114  //
   115  // There are standard tools for working with benchmark results at
   116  // https://golang.org/x/perf/cmd.
   117  // In particular, https://golang.org/x/perf/cmd/benchstat performs
   118  // statistically robust A/B comparisons.
   119  //
   120  // # b.N-style benchmarks
   121  //
   122  // Prior to the introduction of [B.Loop], benchmarks were written in a
   123  // different style using B.N. For example:
   124  //
   125  //	func BenchmarkRandInt(b *testing.B) {
   126  //	    for range b.N {
   127  //	        rand.Int()
   128  //	    }
   129  //	}
   130  //
   131  // In this style of benchmark, the benchmark function must run
   132  // the target code b.N times. The benchmark function is called
   133  // multiple times with b.N adjusted until the benchmark function
   134  // lasts long enough to be timed reliably. This also means any setup
   135  // done before the loop may be run several times.
   136  //
   137  // If a benchmark needs some expensive setup before running, the timer
   138  // should be explicitly reset:
   139  //
   140  //	func BenchmarkBigLen(b *testing.B) {
   141  //	    big := NewBig()
   142  //	    b.ResetTimer()
   143  //	    for range b.N {
   144  //	        big.Len()
   145  //	    }
   146  //	}
   147  //
   148  // New benchmarks should prefer using [B.Loop], which is more robust
   149  // and more efficient.
   150  //
   151  // # Examples
   152  //
   153  // The package also runs and verifies example code. Example functions may
   154  // include a concluding line comment that begins with "Output:" and is compared with
   155  // the standard output of the function when the tests are run. (The comparison
   156  // ignores leading and trailing space.) These are examples of an example:
   157  //
   158  //	func ExampleHello() {
   159  //	    fmt.Println("hello")
   160  //	    // Output: hello
   161  //	}
   162  //
   163  //	func ExampleSalutations() {
   164  //	    fmt.Println("hello, and")
   165  //	    fmt.Println("goodbye")
   166  //	    // Output:
   167  //	    // hello, and
   168  //	    // goodbye
   169  //	}
   170  //
   171  // The comment prefix "Unordered output:" is like "Output:", but matches any
   172  // line order:
   173  //
   174  //	func ExamplePerm() {
   175  //	    for _, value := range Perm(5) {
   176  //	        fmt.Println(value)
   177  //	    }
   178  //	    // Unordered output: 4
   179  //	    // 2
   180  //	    // 1
   181  //	    // 3
   182  //	    // 0
   183  //	}
   184  //
   185  // Example functions without output comments are compiled but not executed.
   186  //
   187  // The naming convention to declare examples for the package, a function F, a type T and
   188  // method M on type T are:
   189  //
   190  //	func Example() { ... }
   191  //	func ExampleF() { ... }
   192  //	func ExampleT() { ... }
   193  //	func ExampleT_M() { ... }
   194  //
   195  // Multiple example functions for a package/type/function/method may be provided by
   196  // appending a distinct suffix to the name. The suffix must start with a
   197  // lower-case letter.
   198  //
   199  //	func Example_suffix() { ... }
   200  //	func ExampleF_suffix() { ... }
   201  //	func ExampleT_suffix() { ... }
   202  //	func ExampleT_M_suffix() { ... }
   203  //
   204  // The entire test file is presented as the example when it contains a single
   205  // example function, at least one other function, type, variable, or constant
   206  // declaration, and no test or benchmark functions.
   207  //
   208  // # Fuzzing
   209  //
   210  // 'go test' and the testing package support fuzzing, a testing technique where
   211  // a function is called with randomly generated inputs to find bugs not
   212  // anticipated by unit tests.
   213  //
   214  // Functions of the form
   215  //
   216  //	func FuzzXxx(*testing.F)
   217  //
   218  // are considered fuzz tests.
   219  //
   220  // For example:
   221  //
   222  //	func FuzzHex(f *testing.F) {
   223  //	  for _, seed := range [][]byte{{}, {0}, {9}, {0xa}, {0xf}, {1, 2, 3, 4}} {
   224  //	    f.Add(seed)
   225  //	  }
   226  //	  f.Fuzz(func(t *testing.T, in []byte) {
   227  //	    enc := hex.EncodeToString(in)
   228  //	    out, err := hex.DecodeString(enc)
   229  //	    if err != nil {
   230  //	      t.Fatalf("%v: decode: %v", in, err)
   231  //	    }
   232  //	    if !bytes.Equal(in, out) {
   233  //	      t.Fatalf("%v: not equal after round trip: %v", in, out)
   234  //	    }
   235  //	  })
   236  //	}
   237  //
   238  // A fuzz test maintains a seed corpus, or a set of inputs which are run by
   239  // default, and can seed input generation. Seed inputs may be registered by
   240  // calling (*F).Add or by storing files in the directory testdata/fuzz/<Name>
   241  // (where <Name> is the name of the fuzz test) within the package containing
   242  // the fuzz test. Seed inputs are optional, but the fuzzing engine may find
   243  // bugs more efficiently when provided with a set of small seed inputs with good
   244  // code coverage. These seed inputs can also serve as regression tests for bugs
   245  // identified through fuzzing.
   246  //
   247  // The function passed to (*F).Fuzz within the fuzz test is considered the fuzz
   248  // target. A fuzz target must accept a *T parameter, followed by one or more
   249  // parameters for random inputs. The types of arguments passed to (*F).Add must
   250  // be identical to the types of these parameters. The fuzz target may signal
   251  // that it's found a problem the same way tests do: by calling T.Fail (or any
   252  // method that calls it like T.Error or T.Fatal) or by panicking.
   253  //
   254  // When fuzzing is enabled (by setting the -fuzz flag to a regular expression
   255  // that matches a specific fuzz test), the fuzz target is called with arguments
   256  // generated by repeatedly making random changes to the seed inputs. On
   257  // supported platforms, 'go test' compiles the test executable with fuzzing
   258  // coverage instrumentation. The fuzzing engine uses that instrumentation to
   259  // find and cache inputs that expand coverage, increasing the likelihood of
   260  // finding bugs. If the fuzz target fails for a given input, the fuzzing engine
   261  // writes the inputs that caused the failure to a file in the directory
   262  // testdata/fuzz/<Name> within the package directory. This file later serves as
   263  // a seed input. If the file can't be written at that location (for example,
   264  // because the directory is read-only), the fuzzing engine writes the file to
   265  // the fuzz cache directory within the build cache instead.
   266  //
   267  // When fuzzing is disabled, the fuzz target is called with the seed inputs
   268  // registered with F.Add and seed inputs from testdata/fuzz/<Name>. In this
   269  // mode, the fuzz test acts much like a regular test, with subtests started
   270  // with F.Fuzz instead of T.Run.
   271  //
   272  // See https://go.dev/doc/fuzz for documentation about fuzzing.
   273  //
   274  // # Skipping
   275  //
   276  // Tests or benchmarks may be skipped at run time with a call to
   277  // the Skip method of *T or *B:
   278  //
   279  //	func TestTimeConsuming(t *testing.T) {
   280  //	    if testing.Short() {
   281  //	        t.Skip("skipping test in short mode.")
   282  //	    }
   283  //	    ...
   284  //	}
   285  //
   286  // The Skip method of *T can be used in a fuzz target if the input is invalid,
   287  // but should not be considered a failing input. For example:
   288  //
   289  //	func FuzzJSONMarshaling(f *testing.F) {
   290  //	    f.Fuzz(func(t *testing.T, b []byte) {
   291  //	        var v interface{}
   292  //	        if err := json.Unmarshal(b, &v); err != nil {
   293  //	            t.Skip()
   294  //	        }
   295  //	        if _, err := json.Marshal(v); err != nil {
   296  //	            t.Errorf("Marshal: %v", err)
   297  //	        }
   298  //	    })
   299  //	}
   300  //
   301  // # Subtests and Sub-benchmarks
   302  //
   303  // The Run methods of T and B allow defining subtests and sub-benchmarks,
   304  // without having to define separate functions for each. This enables uses
   305  // like table-driven benchmarks and creating hierarchical tests.
   306  // It also provides a way to share common setup and tear-down code:
   307  //
   308  //	func TestFoo(t *testing.T) {
   309  //	    // <setup code>
   310  //	    t.Run("A=1", func(t *testing.T) { ... })
   311  //	    t.Run("A=2", func(t *testing.T) { ... })
   312  //	    t.Run("B=1", func(t *testing.T) { ... })
   313  //	    // <tear-down code>
   314  //	}
   315  //
   316  // Each subtest and sub-benchmark has a unique name: the combination of the name
   317  // of the top-level test and the sequence of names passed to Run, separated by
   318  // slashes, with an optional trailing sequence number for disambiguation.
   319  //
   320  // The argument to the -run, -bench, and -fuzz command-line flags is an unanchored regular
   321  // expression that matches the test's name. For tests with multiple slash-separated
   322  // elements, such as subtests, the argument is itself slash-separated, with
   323  // expressions matching each name element in turn. Because it is unanchored, an
   324  // empty expression matches any string.
   325  // For example, using "matching" to mean "whose name contains":
   326  //
   327  //	go test -run ''        # Run all tests.
   328  //	go test -run Foo       # Run top-level tests matching "Foo", such as "TestFooBar".
   329  //	go test -run Foo/A=    # For top-level tests matching "Foo", run subtests matching "A=".
   330  //	go test -run /A=1      # For all top-level tests, run subtests matching "A=1".
   331  //	go test -fuzz FuzzFoo  # Fuzz the target matching "FuzzFoo"
   332  //
   333  // The -run argument can also be used to run a specific value in the seed
   334  // corpus, for debugging. For example:
   335  //
   336  //	go test -run=FuzzFoo/9ddb952d9814
   337  //
   338  // The -fuzz and -run flags can both be set, in order to fuzz a target but
   339  // skip the execution of all other tests.
   340  //
   341  // Subtests can also be used to control parallelism. A parent test will only
   342  // complete once all of its subtests complete. In this example, all tests are
   343  // run in parallel with each other, and only with each other, regardless of
   344  // other top-level tests that may be defined:
   345  //
   346  //	func TestGroupedParallel(t *testing.T) {
   347  //	    for _, tc := range tests {
   348  //	        tc := tc // capture range variable
   349  //	        t.Run(tc.Name, func(t *testing.T) {
   350  //	            t.Parallel()
   351  //	            ...
   352  //	        })
   353  //	    }
   354  //	}
   355  //
   356  // Run does not return until parallel subtests have completed, providing a way
   357  // to clean up after a group of parallel tests:
   358  //
   359  //	func TestTeardownParallel(t *testing.T) {
   360  //	    // This Run will not return until the parallel tests finish.
   361  //	    t.Run("group", func(t *testing.T) {
   362  //	        t.Run("Test1", parallelTest1)
   363  //	        t.Run("Test2", parallelTest2)
   364  //	        t.Run("Test3", parallelTest3)
   365  //	    })
   366  //	    // <tear-down code>
   367  //	}
   368  //
   369  // # Main
   370  //
   371  // It is sometimes necessary for a test or benchmark program to do extra setup or teardown
   372  // before or after it executes. It is also sometimes necessary to control
   373  // which code runs on the main thread. To support these and other cases,
   374  // if a test file contains a function:
   375  //
   376  //	func TestMain(m *testing.M)
   377  //
   378  // then the generated test will call TestMain(m) instead of running the tests or benchmarks
   379  // directly. TestMain runs in the main goroutine and can do whatever setup
   380  // and teardown is necessary around a call to m.Run. m.Run will return an exit
   381  // code that may be passed to os.Exit. If TestMain returns, the test wrapper
   382  // will pass the result of m.Run to os.Exit itself.
   383  //
   384  // When TestMain is called, flag.Parse has not been run. If TestMain depends on
   385  // command-line flags, including those of the testing package, it should call
   386  // flag.Parse explicitly. Command line flags are always parsed by the time test
   387  // or benchmark functions run.
   388  //
   389  // A simple implementation of TestMain is:
   390  //
   391  //	func TestMain(m *testing.M) {
   392  //		// call flag.Parse() here if TestMain uses flags
   393  //		m.Run()
   394  //	}
   395  //
   396  // TestMain is a low-level primitive and should not be necessary for casual
   397  // testing needs, where ordinary test functions suffice.
   398  package testing
   399  
   400  import (
   401  	"bytes"
   402  	"context"
   403  	"errors"
   404  	"flag"
   405  	"fmt"
   406  	"internal/goexperiment"
   407  	"internal/race"
   408  	"io"
   409  	"math/rand"
   410  	"os"
   411  	"path/filepath"
   412  	"reflect"
   413  	"runtime"
   414  	"runtime/debug"
   415  	"runtime/trace"
   416  	"slices"
   417  	"strconv"
   418  	"strings"
   419  	"sync"
   420  	"sync/atomic"
   421  	"time"
   422  	"unicode"
   423  	"unicode/utf8"
   424  )
   425  
   426  var initRan bool
   427  
   428  // Init registers testing flags. These flags are automatically registered by
   429  // the "go test" command before running test functions, so Init is only needed
   430  // when calling functions such as Benchmark without using "go test".
   431  //
   432  // Init is not safe to call concurrently. It has no effect if it was already called.
   433  func Init() {
   434  	if initRan {
   435  		return
   436  	}
   437  	initRan = true
   438  	// The short flag requests that tests run more quickly, but its functionality
   439  	// is provided by test writers themselves. The testing package is just its
   440  	// home. The all.bash installation script sets it to make installation more
   441  	// efficient, but by default the flag is off so a plain "go test" will do a
   442  	// full test of the package.
   443  	short = flag.Bool("test.short", false, "run smaller test suite to save time")
   444  
   445  	// The failfast flag requests that test execution stop after the first test failure.
   446  	failFast = flag.Bool("test.failfast", false, "do not start new tests after the first test failure")
   447  
   448  	// The directory in which to create profile files and the like. When run from
   449  	// "go test", the binary always runs in the source directory for the package;
   450  	// this flag lets "go test" tell the binary to write the files in the directory where
   451  	// the "go test" command is run.
   452  	outputDir = flag.String("test.outputdir", "", "write profiles to `dir`")
   453  	// Report as tests are run; default is silent for success.
   454  	flag.Var(&chatty, "test.v", "verbose: print additional output")
   455  	count = flag.Uint("test.count", 1, "run tests and benchmarks `n` times")
   456  	coverProfile = flag.String("test.coverprofile", "", "write a coverage profile to `file`")
   457  	gocoverdir = flag.String("test.gocoverdir", "", "write coverage intermediate files to this directory")
   458  	matchList = flag.String("test.list", "", "list tests, examples, and benchmarks matching `regexp` then exit")
   459  	match = flag.String("test.run", "", "run only tests and examples matching `regexp`")
   460  	skip = flag.String("test.skip", "", "do not list or run tests matching `regexp`")
   461  	memProfile = flag.String("test.memprofile", "", "write an allocation profile to `file`")
   462  	memProfileRate = flag.Int("test.memprofilerate", 0, "set memory allocation profiling `rate` (see runtime.MemProfileRate)")
   463  	cpuProfile = flag.String("test.cpuprofile", "", "write a cpu profile to `file`")
   464  	blockProfile = flag.String("test.blockprofile", "", "write a goroutine blocking profile to `file`")
   465  	blockProfileRate = flag.Int("test.blockprofilerate", 1, "set blocking profile `rate` (see runtime.SetBlockProfileRate)")
   466  	mutexProfile = flag.String("test.mutexprofile", "", "write a mutex contention profile to the named file after execution")
   467  	mutexProfileFraction = flag.Int("test.mutexprofilefraction", 1, "if >= 0, calls runtime.SetMutexProfileFraction()")
   468  	panicOnExit0 = flag.Bool("test.paniconexit0", false, "panic on call to os.Exit(0)")
   469  	traceFile = flag.String("test.trace", "", "write an execution trace to `file`")
   470  	timeout = flag.Duration("test.timeout", 0, "panic test binary after duration `d` (default 0, timeout disabled)")
   471  	cpuListStr = flag.String("test.cpu", "", "comma-separated `list` of cpu counts to run each test with")
   472  	parallel = flag.Int("test.parallel", runtime.GOMAXPROCS(0), "run at most `n` tests in parallel")
   473  	testlog = flag.String("test.testlogfile", "", "write test action log to `file` (for use only by cmd/go)")
   474  	shuffle = flag.String("test.shuffle", "off", "randomize the execution order of tests and benchmarks")
   475  	fullPath = flag.Bool("test.fullpath", false, "show full file names in error messages")
   476  
   477  	initBenchmarkFlags()
   478  	initFuzzFlags()
   479  }
   480  
   481  var (
   482  	// Flags, registered during Init.
   483  	short                *bool
   484  	failFast             *bool
   485  	outputDir            *string
   486  	chatty               chattyFlag
   487  	count                *uint
   488  	coverProfile         *string
   489  	gocoverdir           *string
   490  	matchList            *string
   491  	match                *string
   492  	skip                 *string
   493  	memProfile           *string
   494  	memProfileRate       *int
   495  	cpuProfile           *string
   496  	blockProfile         *string
   497  	blockProfileRate     *int
   498  	mutexProfile         *string
   499  	mutexProfileFraction *int
   500  	panicOnExit0         *bool
   501  	traceFile            *string
   502  	timeout              *time.Duration
   503  	cpuListStr           *string
   504  	parallel             *int
   505  	shuffle              *string
   506  	testlog              *string
   507  	fullPath             *bool
   508  
   509  	haveExamples bool // are there examples?
   510  
   511  	cpuList     []int
   512  	testlogFile *os.File
   513  
   514  	numFailed atomic.Uint32 // number of test failures
   515  
   516  	running sync.Map // map[string]time.Time of running, unpaused tests
   517  )
   518  
   519  type chattyFlag struct {
   520  	on   bool // -v is set in some form
   521  	json bool // -v=test2json is set, to make output better for test2json
   522  }
   523  
   524  func (*chattyFlag) IsBoolFlag() bool { return true }
   525  
   526  func (f *chattyFlag) Set(arg string) error {
   527  	switch arg {
   528  	default:
   529  		return fmt.Errorf("invalid flag -test.v=%s", arg)
   530  	case "true", "test2json":
   531  		f.on = true
   532  		f.json = arg == "test2json"
   533  	case "false":
   534  		f.on = false
   535  		f.json = false
   536  	}
   537  	return nil
   538  }
   539  
   540  func (f *chattyFlag) String() string {
   541  	if f.json {
   542  		return "test2json"
   543  	}
   544  	if f.on {
   545  		return "true"
   546  	}
   547  	return "false"
   548  }
   549  
   550  func (f *chattyFlag) Get() any {
   551  	if f.json {
   552  		return "test2json"
   553  	}
   554  	return f.on
   555  }
   556  
   557  const marker = byte(0x16) // ^V for framing
   558  
   559  func (f *chattyFlag) prefix() string {
   560  	if f.json {
   561  		return string(marker)
   562  	}
   563  	return ""
   564  }
   565  
   566  type chattyPrinter struct {
   567  	w          io.Writer
   568  	lastNameMu sync.Mutex // guards lastName
   569  	lastName   string     // last printed test name in chatty mode
   570  	json       bool       // -v=json output mode
   571  }
   572  
   573  func newChattyPrinter(w io.Writer) *chattyPrinter {
   574  	return &chattyPrinter{w: w, json: chatty.json}
   575  }
   576  
   577  // prefix is like chatty.prefix but using p.json instead of chatty.json.
   578  // Using p.json allows tests to check the json behavior without modifying
   579  // the global variable. For convenience, we allow p == nil and treat
   580  // that as not in json mode (because it's not chatty at all).
   581  func (p *chattyPrinter) prefix() string {
   582  	if p != nil && p.json {
   583  		return string(marker)
   584  	}
   585  	return ""
   586  }
   587  
   588  // Updatef prints a message about the status of the named test to w.
   589  //
   590  // The formatted message must include the test name itself.
   591  func (p *chattyPrinter) Updatef(testName, format string, args ...any) {
   592  	p.lastNameMu.Lock()
   593  	defer p.lastNameMu.Unlock()
   594  
   595  	// Since the message already implies an association with a specific new test,
   596  	// we don't need to check what the old test name was or log an extra NAME line
   597  	// for it. (We're updating it anyway, and the current message already includes
   598  	// the test name.)
   599  	p.lastName = testName
   600  	fmt.Fprintf(p.w, p.prefix()+format, args...)
   601  }
   602  
   603  // Printf prints a message, generated by the named test, that does not
   604  // necessarily mention that tests's name itself.
   605  func (p *chattyPrinter) Printf(testName, format string, args ...any) {
   606  	p.lastNameMu.Lock()
   607  	defer p.lastNameMu.Unlock()
   608  
   609  	if p.lastName == "" {
   610  		p.lastName = testName
   611  	} else if p.lastName != testName {
   612  		fmt.Fprintf(p.w, "%s=== NAME  %s\n", p.prefix(), testName)
   613  		p.lastName = testName
   614  	}
   615  
   616  	fmt.Fprintf(p.w, format, args...)
   617  }
   618  
   619  // The maximum number of stack frames to go through when skipping helper functions for
   620  // the purpose of decorating log messages.
   621  const maxStackLen = 50
   622  
   623  // common holds the elements common between T and B and
   624  // captures common methods such as Errorf.
   625  type common struct {
   626  	mu          sync.RWMutex         // guards this group of fields
   627  	output      []byte               // Output generated by test or benchmark.
   628  	w           io.Writer            // For flushToParent.
   629  	ran         bool                 // Test or benchmark (or one of its subtests) was executed.
   630  	failed      bool                 // Test or benchmark has failed.
   631  	skipped     bool                 // Test or benchmark has been skipped.
   632  	done        bool                 // Test is finished and all subtests have completed.
   633  	helperPCs   map[uintptr]struct{} // functions to be skipped when writing file/line info
   634  	helperNames map[string]struct{}  // helperPCs converted to function names
   635  	cleanups    []func()             // optional functions to be called at the end of the test
   636  	cleanupName string               // Name of the cleanup function.
   637  	cleanupPc   []uintptr            // The stack trace at the point where Cleanup was called.
   638  	finished    bool                 // Test function has completed.
   639  	inFuzzFn    bool                 // Whether the fuzz target, if this is one, is running.
   640  
   641  	chatty         *chattyPrinter // A copy of chattyPrinter, if the chatty flag is set.
   642  	bench          bool           // Whether the current test is a benchmark.
   643  	hasSub         atomic.Bool    // whether there are sub-benchmarks.
   644  	cleanupStarted atomic.Bool    // Registered cleanup callbacks have started to execute
   645  	runner         string         // Function name of tRunner running the test.
   646  	isParallel     bool           // Whether the test is parallel.
   647  
   648  	parent   *common
   649  	level    int               // Nesting depth of test or benchmark.
   650  	creator  []uintptr         // If level > 0, the stack trace at the point where the parent called t.Run.
   651  	name     string            // Name of test or benchmark.
   652  	start    highPrecisionTime // Time test or benchmark started
   653  	duration time.Duration
   654  	barrier  chan bool // To signal parallel subtests they may start. Nil when T.Parallel is not present (B) or not usable (when fuzzing).
   655  	signal   chan bool // To signal a test is done.
   656  	sub      []*T      // Queue of subtests to be run in parallel.
   657  
   658  	lastRaceErrors  atomic.Int64 // Max value of race.Errors seen during the test or its subtests.
   659  	raceErrorLogged atomic.Bool
   660  
   661  	tempDirMu  sync.Mutex
   662  	tempDir    string
   663  	tempDirErr error
   664  	tempDirSeq int32
   665  
   666  	ctx       context.Context
   667  	cancelCtx context.CancelFunc
   668  }
   669  
   670  // Short reports whether the -test.short flag is set.
   671  func Short() bool {
   672  	if short == nil {
   673  		panic("testing: Short called before Init")
   674  	}
   675  	// Catch code that calls this from TestMain without first calling flag.Parse.
   676  	if !flag.Parsed() {
   677  		panic("testing: Short called before Parse")
   678  	}
   679  
   680  	return *short
   681  }
   682  
   683  // testBinary is set by cmd/go to "1" if this is a binary built by "go test".
   684  // The value is set to "1" by a -X option to cmd/link. We assume that
   685  // because this is possible, the compiler will not optimize testBinary
   686  // into a constant on the basis that it is an unexported package-scope
   687  // variable that is never changed. If the compiler ever starts implementing
   688  // such an optimization, we will need some technique to mark this variable
   689  // as "changed by a cmd/link -X option".
   690  var testBinary = "0"
   691  
   692  // Testing reports whether the current code is being run in a test.
   693  // This will report true in programs created by "go test",
   694  // false in programs created by "go build".
   695  func Testing() bool {
   696  	return testBinary == "1"
   697  }
   698  
   699  // CoverMode reports what the test coverage mode is set to. The
   700  // values are "set", "count", or "atomic". The return value will be
   701  // empty if test coverage is not enabled.
   702  func CoverMode() string {
   703  	if goexperiment.CoverageRedesign {
   704  		return cover2.mode
   705  	}
   706  	return cover.Mode
   707  }
   708  
   709  // Verbose reports whether the -test.v flag is set.
   710  func Verbose() bool {
   711  	// Same as in Short.
   712  	if !flag.Parsed() {
   713  		panic("testing: Verbose called before Parse")
   714  	}
   715  	return chatty.on
   716  }
   717  
   718  func (c *common) checkFuzzFn(name string) {
   719  	if c.inFuzzFn {
   720  		panic(fmt.Sprintf("testing: f.%s was called inside the fuzz target, use t.%s instead", name, name))
   721  	}
   722  }
   723  
   724  // frameSkip searches, starting after skip frames, for the first caller frame
   725  // in a function not marked as a helper and returns that frame.
   726  // The search stops if it finds a tRunner function that
   727  // was the entry point into the test and the test is not a subtest.
   728  // This function must be called with c.mu held.
   729  func (c *common) frameSkip(skip int) runtime.Frame {
   730  	// If the search continues into the parent test, we'll have to hold
   731  	// its mu temporarily. If we then return, we need to unlock it.
   732  	shouldUnlock := false
   733  	defer func() {
   734  		if shouldUnlock {
   735  			c.mu.Unlock()
   736  		}
   737  	}()
   738  	var pc [maxStackLen]uintptr
   739  	// Skip two extra frames to account for this function
   740  	// and runtime.Callers itself.
   741  	n := runtime.Callers(skip+2, pc[:])
   742  	if n == 0 {
   743  		panic("testing: zero callers found")
   744  	}
   745  	frames := runtime.CallersFrames(pc[:n])
   746  	var firstFrame, prevFrame, frame runtime.Frame
   747  	for more := true; more; prevFrame = frame {
   748  		frame, more = frames.Next()
   749  		if frame.Function == "runtime.gopanic" {
   750  			continue
   751  		}
   752  		if frame.Function == c.cleanupName {
   753  			frames = runtime.CallersFrames(c.cleanupPc)
   754  			continue
   755  		}
   756  		if firstFrame.PC == 0 {
   757  			firstFrame = frame
   758  		}
   759  		if frame.Function == c.runner {
   760  			// We've gone up all the way to the tRunner calling
   761  			// the test function (so the user must have
   762  			// called tb.Helper from inside that test function).
   763  			// If this is a top-level test, only skip up to the test function itself.
   764  			// If we're in a subtest, continue searching in the parent test,
   765  			// starting from the point of the call to Run which created this subtest.
   766  			if c.level > 1 {
   767  				frames = runtime.CallersFrames(c.creator)
   768  				parent := c.parent
   769  				// We're no longer looking at the current c after this point,
   770  				// so we should unlock its mu, unless it's the original receiver,
   771  				// in which case our caller doesn't expect us to do that.
   772  				if shouldUnlock {
   773  					c.mu.Unlock()
   774  				}
   775  				c = parent
   776  				// Remember to unlock c.mu when we no longer need it, either
   777  				// because we went up another nesting level, or because we
   778  				// returned.
   779  				shouldUnlock = true
   780  				c.mu.Lock()
   781  				continue
   782  			}
   783  			return prevFrame
   784  		}
   785  		// If more helper PCs have been added since we last did the conversion
   786  		if c.helperNames == nil {
   787  			c.helperNames = make(map[string]struct{})
   788  			for pc := range c.helperPCs {
   789  				c.helperNames[pcToName(pc)] = struct{}{}
   790  			}
   791  		}
   792  		if _, ok := c.helperNames[frame.Function]; !ok {
   793  			// Found a frame that wasn't inside a helper function.
   794  			return frame
   795  		}
   796  	}
   797  	return firstFrame
   798  }
   799  
   800  // decorate prefixes the string with the file and line of the call site
   801  // and inserts the final newline if needed and indentation spaces for formatting.
   802  // This function must be called with c.mu held.
   803  func (c *common) decorate(s string, skip int) string {
   804  	frame := c.frameSkip(skip)
   805  	file := frame.File
   806  	line := frame.Line
   807  	if file != "" {
   808  		if *fullPath {
   809  			// If relative path, truncate file name at last file name separator.
   810  		} else if index := strings.LastIndexAny(file, `/\`); index >= 0 {
   811  			file = file[index+1:]
   812  		}
   813  	} else {
   814  		file = "???"
   815  	}
   816  	if line == 0 {
   817  		line = 1
   818  	}
   819  	buf := new(strings.Builder)
   820  	// Every line is indented at least 4 spaces.
   821  	buf.WriteString("    ")
   822  	fmt.Fprintf(buf, "%s:%d: ", file, line)
   823  	lines := strings.Split(s, "\n")
   824  	if l := len(lines); l > 1 && lines[l-1] == "" {
   825  		lines = lines[:l-1]
   826  	}
   827  	for i, line := range lines {
   828  		if i > 0 {
   829  			// Second and subsequent lines are indented an additional 4 spaces.
   830  			buf.WriteString("\n        ")
   831  		}
   832  		buf.WriteString(line)
   833  	}
   834  	buf.WriteByte('\n')
   835  	return buf.String()
   836  }
   837  
   838  // flushToParent writes c.output to the parent after first writing the header
   839  // with the given format and arguments.
   840  func (c *common) flushToParent(testName, format string, args ...any) {
   841  	p := c.parent
   842  	p.mu.Lock()
   843  	defer p.mu.Unlock()
   844  
   845  	c.mu.Lock()
   846  	defer c.mu.Unlock()
   847  
   848  	if len(c.output) > 0 {
   849  		// Add the current c.output to the print,
   850  		// and then arrange for the print to replace c.output.
   851  		// (This displays the logged output after the --- FAIL line.)
   852  		format += "%s"
   853  		args = append(args[:len(args):len(args)], c.output)
   854  		c.output = c.output[:0]
   855  	}
   856  
   857  	if c.chatty != nil && (p.w == c.chatty.w || c.chatty.json) {
   858  		// We're flushing to the actual output, so track that this output is
   859  		// associated with a specific test (and, specifically, that the next output
   860  		// is *not* associated with that test).
   861  		//
   862  		// Moreover, if c.output is non-empty it is important that this write be
   863  		// atomic with respect to the output of other tests, so that we don't end up
   864  		// with confusing '=== NAME' lines in the middle of our '--- PASS' block.
   865  		// Neither humans nor cmd/test2json can parse those easily.
   866  		// (See https://go.dev/issue/40771.)
   867  		//
   868  		// If test2json is used, we never flush to parent tests,
   869  		// so that the json stream shows subtests as they finish.
   870  		// (See https://go.dev/issue/29811.)
   871  		c.chatty.Updatef(testName, format, args...)
   872  	} else {
   873  		// We're flushing to the output buffer of the parent test, which will
   874  		// itself follow a test-name header when it is finally flushed to stdout.
   875  		fmt.Fprintf(p.w, c.chatty.prefix()+format, args...)
   876  	}
   877  }
   878  
   879  type indenter struct {
   880  	c *common
   881  }
   882  
   883  func (w indenter) Write(b []byte) (n int, err error) {
   884  	n = len(b)
   885  	for len(b) > 0 {
   886  		end := bytes.IndexByte(b, '\n')
   887  		if end == -1 {
   888  			end = len(b)
   889  		} else {
   890  			end++
   891  		}
   892  		// An indent of 4 spaces will neatly align the dashes with the status
   893  		// indicator of the parent.
   894  		line := b[:end]
   895  		if line[0] == marker {
   896  			w.c.output = append(w.c.output, marker)
   897  			line = line[1:]
   898  		}
   899  		const indent = "    "
   900  		w.c.output = append(w.c.output, indent...)
   901  		w.c.output = append(w.c.output, line...)
   902  		b = b[end:]
   903  	}
   904  	return
   905  }
   906  
   907  // fmtDuration returns a string representing d in the form "87.00s".
   908  func fmtDuration(d time.Duration) string {
   909  	return fmt.Sprintf("%.2fs", d.Seconds())
   910  }
   911  
   912  // TB is the interface common to T, B, and F.
   913  type TB interface {
   914  	Cleanup(func())
   915  	Error(args ...any)
   916  	Errorf(format string, args ...any)
   917  	Fail()
   918  	FailNow()
   919  	Failed() bool
   920  	Fatal(args ...any)
   921  	Fatalf(format string, args ...any)
   922  	Helper()
   923  	Log(args ...any)
   924  	Logf(format string, args ...any)
   925  	Name() string
   926  	Setenv(key, value string)
   927  	Chdir(dir string)
   928  	Skip(args ...any)
   929  	SkipNow()
   930  	Skipf(format string, args ...any)
   931  	Skipped() bool
   932  	TempDir() string
   933  	Context() context.Context
   934  
   935  	// A private method to prevent users implementing the
   936  	// interface and so future additions to it will not
   937  	// violate Go 1 compatibility.
   938  	private()
   939  }
   940  
   941  var _ TB = (*T)(nil)
   942  var _ TB = (*B)(nil)
   943  
   944  // T is a type passed to Test functions to manage test state and support formatted test logs.
   945  //
   946  // A test ends when its Test function returns or calls any of the methods
   947  // FailNow, Fatal, Fatalf, SkipNow, Skip, or Skipf. Those methods, as well as
   948  // the Parallel method, must be called only from the goroutine running the
   949  // Test function.
   950  //
   951  // The other reporting methods, such as the variations of Log and Error,
   952  // may be called simultaneously from multiple goroutines.
   953  type T struct {
   954  	common
   955  	denyParallel bool
   956  	tstate       *testState // For running tests and subtests.
   957  }
   958  
   959  func (c *common) private() {}
   960  
   961  // Name returns the name of the running (sub-) test or benchmark.
   962  //
   963  // The name will include the name of the test along with the names of
   964  // any nested sub-tests. If two sibling sub-tests have the same name,
   965  // Name will append a suffix to guarantee the returned name is unique.
   966  func (c *common) Name() string {
   967  	return c.name
   968  }
   969  
   970  func (c *common) setRan() {
   971  	if c.parent != nil {
   972  		c.parent.setRan()
   973  	}
   974  	c.mu.Lock()
   975  	defer c.mu.Unlock()
   976  	c.ran = true
   977  }
   978  
   979  // Fail marks the function as having failed but continues execution.
   980  func (c *common) Fail() {
   981  	if c.parent != nil {
   982  		c.parent.Fail()
   983  	}
   984  	c.mu.Lock()
   985  	defer c.mu.Unlock()
   986  	// c.done needs to be locked to synchronize checks to c.done in parent tests.
   987  	if c.done {
   988  		panic("Fail in goroutine after " + c.name + " has completed")
   989  	}
   990  	c.failed = true
   991  }
   992  
   993  // Failed reports whether the function has failed.
   994  func (c *common) Failed() bool {
   995  	c.mu.RLock()
   996  	defer c.mu.RUnlock()
   997  
   998  	if !c.done && int64(race.Errors()) > c.lastRaceErrors.Load() {
   999  		c.mu.RUnlock()
  1000  		c.checkRaces()
  1001  		c.mu.RLock()
  1002  	}
  1003  
  1004  	return c.failed
  1005  }
  1006  
  1007  // FailNow marks the function as having failed and stops its execution
  1008  // by calling runtime.Goexit (which then runs all deferred calls in the
  1009  // current goroutine).
  1010  // Execution will continue at the next test or benchmark.
  1011  // FailNow must be called from the goroutine running the
  1012  // test or benchmark function, not from other goroutines
  1013  // created during the test. Calling FailNow does not stop
  1014  // those other goroutines.
  1015  func (c *common) FailNow() {
  1016  	c.checkFuzzFn("FailNow")
  1017  	c.Fail()
  1018  
  1019  	// Calling runtime.Goexit will exit the goroutine, which
  1020  	// will run the deferred functions in this goroutine,
  1021  	// which will eventually run the deferred lines in tRunner,
  1022  	// which will signal to the test loop that this test is done.
  1023  	//
  1024  	// A previous version of this code said:
  1025  	//
  1026  	//	c.duration = ...
  1027  	//	c.signal <- c.self
  1028  	//	runtime.Goexit()
  1029  	//
  1030  	// This previous version duplicated code (those lines are in
  1031  	// tRunner no matter what), but worse the goroutine teardown
  1032  	// implicit in runtime.Goexit was not guaranteed to complete
  1033  	// before the test exited. If a test deferred an important cleanup
  1034  	// function (like removing temporary files), there was no guarantee
  1035  	// it would run on a test failure. Because we send on c.signal during
  1036  	// a top-of-stack deferred function now, we know that the send
  1037  	// only happens after any other stacked defers have completed.
  1038  	c.mu.Lock()
  1039  	c.finished = true
  1040  	c.mu.Unlock()
  1041  	runtime.Goexit()
  1042  }
  1043  
  1044  // log generates the output. It's always at the same stack depth.
  1045  func (c *common) log(s string) {
  1046  	c.logDepth(s, 3) // logDepth + log + public function
  1047  }
  1048  
  1049  // logDepth generates the output at an arbitrary stack depth.
  1050  func (c *common) logDepth(s string, depth int) {
  1051  	c.mu.Lock()
  1052  	defer c.mu.Unlock()
  1053  	if c.done {
  1054  		// This test has already finished. Try and log this message
  1055  		// with our parent. If we don't have a parent, panic.
  1056  		for parent := c.parent; parent != nil; parent = parent.parent {
  1057  			parent.mu.Lock()
  1058  			defer parent.mu.Unlock()
  1059  			if !parent.done {
  1060  				parent.output = append(parent.output, parent.decorate(s, depth+1)...)
  1061  				return
  1062  			}
  1063  		}
  1064  		panic("Log in goroutine after " + c.name + " has completed: " + s)
  1065  	} else {
  1066  		if c.chatty != nil {
  1067  			if c.bench {
  1068  				// Benchmarks don't print === CONT, so we should skip the test
  1069  				// printer and just print straight to stdout.
  1070  				fmt.Print(c.decorate(s, depth+1))
  1071  			} else {
  1072  				c.chatty.Printf(c.name, "%s", c.decorate(s, depth+1))
  1073  			}
  1074  
  1075  			return
  1076  		}
  1077  		c.output = append(c.output, c.decorate(s, depth+1)...)
  1078  	}
  1079  }
  1080  
  1081  // Log formats its arguments using default formatting, analogous to Println,
  1082  // and records the text in the error log. For tests, the text will be printed only if
  1083  // the test fails or the -test.v flag is set. For benchmarks, the text is always
  1084  // printed to avoid having performance depend on the value of the -test.v flag.
  1085  func (c *common) Log(args ...any) {
  1086  	c.checkFuzzFn("Log")
  1087  	c.log(fmt.Sprintln(args...))
  1088  }
  1089  
  1090  // Logf formats its arguments according to the format, analogous to Printf, and
  1091  // records the text in the error log. A final newline is added if not provided. For
  1092  // tests, the text will be printed only if the test fails or the -test.v flag is
  1093  // set. For benchmarks, the text is always printed to avoid having performance
  1094  // depend on the value of the -test.v flag.
  1095  func (c *common) Logf(format string, args ...any) {
  1096  	c.checkFuzzFn("Logf")
  1097  	c.log(fmt.Sprintf(format, args...))
  1098  }
  1099  
  1100  // Error is equivalent to Log followed by Fail.
  1101  func (c *common) Error(args ...any) {
  1102  	c.checkFuzzFn("Error")
  1103  	c.log(fmt.Sprintln(args...))
  1104  	c.Fail()
  1105  }
  1106  
  1107  // Errorf is equivalent to Logf followed by Fail.
  1108  func (c *common) Errorf(format string, args ...any) {
  1109  	c.checkFuzzFn("Errorf")
  1110  	c.log(fmt.Sprintf(format, args...))
  1111  	c.Fail()
  1112  }
  1113  
  1114  // Fatal is equivalent to Log followed by FailNow.
  1115  func (c *common) Fatal(args ...any) {
  1116  	c.checkFuzzFn("Fatal")
  1117  	c.log(fmt.Sprintln(args...))
  1118  	c.FailNow()
  1119  }
  1120  
  1121  // Fatalf is equivalent to Logf followed by FailNow.
  1122  func (c *common) Fatalf(format string, args ...any) {
  1123  	c.checkFuzzFn("Fatalf")
  1124  	c.log(fmt.Sprintf(format, args...))
  1125  	c.FailNow()
  1126  }
  1127  
  1128  // Skip is equivalent to Log followed by SkipNow.
  1129  func (c *common) Skip(args ...any) {
  1130  	c.checkFuzzFn("Skip")
  1131  	c.log(fmt.Sprintln(args...))
  1132  	c.SkipNow()
  1133  }
  1134  
  1135  // Skipf is equivalent to Logf followed by SkipNow.
  1136  func (c *common) Skipf(format string, args ...any) {
  1137  	c.checkFuzzFn("Skipf")
  1138  	c.log(fmt.Sprintf(format, args...))
  1139  	c.SkipNow()
  1140  }
  1141  
  1142  // SkipNow marks the test as having been skipped and stops its execution
  1143  // by calling [runtime.Goexit].
  1144  // If a test fails (see Error, Errorf, Fail) and is then skipped,
  1145  // it is still considered to have failed.
  1146  // Execution will continue at the next test or benchmark. See also FailNow.
  1147  // SkipNow must be called from the goroutine running the test, not from
  1148  // other goroutines created during the test. Calling SkipNow does not stop
  1149  // those other goroutines.
  1150  func (c *common) SkipNow() {
  1151  	c.checkFuzzFn("SkipNow")
  1152  	c.mu.Lock()
  1153  	c.skipped = true
  1154  	c.finished = true
  1155  	c.mu.Unlock()
  1156  	runtime.Goexit()
  1157  }
  1158  
  1159  // Skipped reports whether the test was skipped.
  1160  func (c *common) Skipped() bool {
  1161  	c.mu.RLock()
  1162  	defer c.mu.RUnlock()
  1163  	return c.skipped
  1164  }
  1165  
  1166  // Helper marks the calling function as a test helper function.
  1167  // When printing file and line information, that function will be skipped.
  1168  // Helper may be called simultaneously from multiple goroutines.
  1169  func (c *common) Helper() {
  1170  	c.mu.Lock()
  1171  	defer c.mu.Unlock()
  1172  	if c.helperPCs == nil {
  1173  		c.helperPCs = make(map[uintptr]struct{})
  1174  	}
  1175  	// repeating code from callerName here to save walking a stack frame
  1176  	var pc [1]uintptr
  1177  	n := runtime.Callers(2, pc[:]) // skip runtime.Callers + Helper
  1178  	if n == 0 {
  1179  		panic("testing: zero callers found")
  1180  	}
  1181  	if _, found := c.helperPCs[pc[0]]; !found {
  1182  		c.helperPCs[pc[0]] = struct{}{}
  1183  		c.helperNames = nil // map will be recreated next time it is needed
  1184  	}
  1185  }
  1186  
  1187  // Cleanup registers a function to be called when the test (or subtest) and all its
  1188  // subtests complete. Cleanup functions will be called in last added,
  1189  // first called order.
  1190  func (c *common) Cleanup(f func()) {
  1191  	c.checkFuzzFn("Cleanup")
  1192  	var pc [maxStackLen]uintptr
  1193  	// Skip two extra frames to account for this function and runtime.Callers itself.
  1194  	n := runtime.Callers(2, pc[:])
  1195  	cleanupPc := pc[:n]
  1196  
  1197  	fn := func() {
  1198  		defer func() {
  1199  			c.mu.Lock()
  1200  			defer c.mu.Unlock()
  1201  			c.cleanupName = ""
  1202  			c.cleanupPc = nil
  1203  		}()
  1204  
  1205  		name := callerName(0)
  1206  		c.mu.Lock()
  1207  		c.cleanupName = name
  1208  		c.cleanupPc = cleanupPc
  1209  		c.mu.Unlock()
  1210  
  1211  		f()
  1212  	}
  1213  
  1214  	c.mu.Lock()
  1215  	defer c.mu.Unlock()
  1216  	c.cleanups = append(c.cleanups, fn)
  1217  }
  1218  
  1219  // TempDir returns a temporary directory for the test to use.
  1220  // The directory is automatically removed when the test and
  1221  // all its subtests complete.
  1222  // Each subsequent call to t.TempDir returns a unique directory;
  1223  // if the directory creation fails, TempDir terminates the test by calling Fatal.
  1224  func (c *common) TempDir() string {
  1225  	c.checkFuzzFn("TempDir")
  1226  	// Use a single parent directory for all the temporary directories
  1227  	// created by a test, each numbered sequentially.
  1228  	c.tempDirMu.Lock()
  1229  	var nonExistent bool
  1230  	if c.tempDir == "" { // Usually the case with js/wasm
  1231  		nonExistent = true
  1232  	} else {
  1233  		_, err := os.Stat(c.tempDir)
  1234  		nonExistent = os.IsNotExist(err)
  1235  		if err != nil && !nonExistent {
  1236  			c.Fatalf("TempDir: %v", err)
  1237  		}
  1238  	}
  1239  
  1240  	if nonExistent {
  1241  		c.Helper()
  1242  
  1243  		// Drop unusual characters (such as path separators or
  1244  		// characters interacting with globs) from the directory name to
  1245  		// avoid surprising os.MkdirTemp behavior.
  1246  		mapper := func(r rune) rune {
  1247  			if r < utf8.RuneSelf {
  1248  				const allowed = "!#$%&()+,-.=@^_{}~ "
  1249  				if '0' <= r && r <= '9' ||
  1250  					'a' <= r && r <= 'z' ||
  1251  					'A' <= r && r <= 'Z' {
  1252  					return r
  1253  				}
  1254  				if strings.ContainsRune(allowed, r) {
  1255  					return r
  1256  				}
  1257  			} else if unicode.IsLetter(r) || unicode.IsNumber(r) {
  1258  				return r
  1259  			}
  1260  			return -1
  1261  		}
  1262  		pattern := strings.Map(mapper, c.Name())
  1263  		c.tempDir, c.tempDirErr = os.MkdirTemp("", pattern)
  1264  		if c.tempDirErr == nil {
  1265  			c.Cleanup(func() {
  1266  				if err := removeAll(c.tempDir); err != nil {
  1267  					c.Errorf("TempDir RemoveAll cleanup: %v", err)
  1268  				}
  1269  			})
  1270  		}
  1271  	}
  1272  
  1273  	if c.tempDirErr == nil {
  1274  		c.tempDirSeq++
  1275  	}
  1276  	seq := c.tempDirSeq
  1277  	c.tempDirMu.Unlock()
  1278  
  1279  	if c.tempDirErr != nil {
  1280  		c.Fatalf("TempDir: %v", c.tempDirErr)
  1281  	}
  1282  
  1283  	dir := fmt.Sprintf("%s%c%03d", c.tempDir, os.PathSeparator, seq)
  1284  	if err := os.Mkdir(dir, 0777); err != nil {
  1285  		c.Fatalf("TempDir: %v", err)
  1286  	}
  1287  	return dir
  1288  }
  1289  
  1290  // removeAll is like os.RemoveAll, but retries Windows "Access is denied."
  1291  // errors up to an arbitrary timeout.
  1292  //
  1293  // Those errors have been known to occur spuriously on at least the
  1294  // windows-amd64-2012 builder (https://go.dev/issue/50051), and can only occur
  1295  // legitimately if the test leaves behind a temp file that either is still open
  1296  // or the test otherwise lacks permission to delete. In the case of legitimate
  1297  // failures, a failing test may take a bit longer to fail, but once the test is
  1298  // fixed the extra latency will go away.
  1299  func removeAll(path string) error {
  1300  	const arbitraryTimeout = 2 * time.Second
  1301  	var (
  1302  		start     time.Time
  1303  		nextSleep = 1 * time.Millisecond
  1304  	)
  1305  	for {
  1306  		err := os.RemoveAll(path)
  1307  		if !isWindowsRetryable(err) {
  1308  			return err
  1309  		}
  1310  		if start.IsZero() {
  1311  			start = time.Now()
  1312  		} else if d := time.Since(start) + nextSleep; d >= arbitraryTimeout {
  1313  			return err
  1314  		}
  1315  		time.Sleep(nextSleep)
  1316  		nextSleep += time.Duration(rand.Int63n(int64(nextSleep)))
  1317  	}
  1318  }
  1319  
  1320  // Setenv calls os.Setenv(key, value) and uses Cleanup to
  1321  // restore the environment variable to its original value
  1322  // after the test.
  1323  //
  1324  // Because Setenv affects the whole process, it cannot be used
  1325  // in parallel tests or tests with parallel ancestors.
  1326  func (c *common) Setenv(key, value string) {
  1327  	c.checkFuzzFn("Setenv")
  1328  	prevValue, ok := os.LookupEnv(key)
  1329  
  1330  	if err := os.Setenv(key, value); err != nil {
  1331  		c.Fatalf("cannot set environment variable: %v", err)
  1332  	}
  1333  
  1334  	if ok {
  1335  		c.Cleanup(func() {
  1336  			os.Setenv(key, prevValue)
  1337  		})
  1338  	} else {
  1339  		c.Cleanup(func() {
  1340  			os.Unsetenv(key)
  1341  		})
  1342  	}
  1343  }
  1344  
  1345  // Chdir calls os.Chdir(dir) and uses Cleanup to restore the current
  1346  // working directory to its original value after the test. On Unix, it
  1347  // also sets PWD environment variable for the duration of the test.
  1348  //
  1349  // Because Chdir affects the whole process, it cannot be used
  1350  // in parallel tests or tests with parallel ancestors.
  1351  func (c *common) Chdir(dir string) {
  1352  	c.checkFuzzFn("Chdir")
  1353  	oldwd, err := os.Open(".")
  1354  	if err != nil {
  1355  		c.Fatal(err)
  1356  	}
  1357  	if err := os.Chdir(dir); err != nil {
  1358  		c.Fatal(err)
  1359  	}
  1360  	// On POSIX platforms, PWD represents “an absolute pathname of the
  1361  	// current working directory.” Since we are changing the working
  1362  	// directory, we should also set or update PWD to reflect that.
  1363  	switch runtime.GOOS {
  1364  	case "windows", "plan9":
  1365  		// Windows and Plan 9 do not use the PWD variable.
  1366  	default:
  1367  		if !filepath.IsAbs(dir) {
  1368  			dir, err = os.Getwd()
  1369  			if err != nil {
  1370  				c.Fatal(err)
  1371  			}
  1372  		}
  1373  		c.Setenv("PWD", dir)
  1374  	}
  1375  	c.Cleanup(func() {
  1376  		err := oldwd.Chdir()
  1377  		oldwd.Close()
  1378  		if err != nil {
  1379  			// It's not safe to continue with tests if we can't
  1380  			// get back to the original working directory. Since
  1381  			// we are holding a dirfd, this is highly unlikely.
  1382  			panic("testing.Chdir: " + err.Error())
  1383  		}
  1384  	})
  1385  }
  1386  
  1387  // Context returns a context that is canceled just before
  1388  // Cleanup-registered functions are called.
  1389  //
  1390  // Cleanup functions can wait for any resources
  1391  // that shut down on Context.Done before the test or benchmark completes.
  1392  func (c *common) Context() context.Context {
  1393  	c.checkFuzzFn("Context")
  1394  	return c.ctx
  1395  }
  1396  
  1397  // panicHandling controls the panic handling used by runCleanup.
  1398  type panicHandling int
  1399  
  1400  const (
  1401  	normalPanic panicHandling = iota
  1402  	recoverAndReturnPanic
  1403  )
  1404  
  1405  // runCleanup is called at the end of the test.
  1406  // If ph is recoverAndReturnPanic, it will catch panics, and return the
  1407  // recovered value if any.
  1408  func (c *common) runCleanup(ph panicHandling) (panicVal any) {
  1409  	c.cleanupStarted.Store(true)
  1410  	defer c.cleanupStarted.Store(false)
  1411  
  1412  	if ph == recoverAndReturnPanic {
  1413  		defer func() {
  1414  			panicVal = recover()
  1415  		}()
  1416  	}
  1417  
  1418  	// Make sure that if a cleanup function panics,
  1419  	// we still run the remaining cleanup functions.
  1420  	defer func() {
  1421  		c.mu.Lock()
  1422  		recur := len(c.cleanups) > 0
  1423  		c.mu.Unlock()
  1424  		if recur {
  1425  			c.runCleanup(normalPanic)
  1426  		}
  1427  	}()
  1428  
  1429  	if c.cancelCtx != nil {
  1430  		c.cancelCtx()
  1431  	}
  1432  
  1433  	for {
  1434  		var cleanup func()
  1435  		c.mu.Lock()
  1436  		if len(c.cleanups) > 0 {
  1437  			last := len(c.cleanups) - 1
  1438  			cleanup = c.cleanups[last]
  1439  			c.cleanups = c.cleanups[:last]
  1440  		}
  1441  		c.mu.Unlock()
  1442  		if cleanup == nil {
  1443  			return nil
  1444  		}
  1445  		cleanup()
  1446  	}
  1447  }
  1448  
  1449  // resetRaces updates c.parent's count of data race errors (or the global count,
  1450  // if c has no parent), and updates c.lastRaceErrors to match.
  1451  //
  1452  // Any races that occurred prior to this call to resetRaces will
  1453  // not be attributed to c.
  1454  func (c *common) resetRaces() {
  1455  	if c.parent == nil {
  1456  		c.lastRaceErrors.Store(int64(race.Errors()))
  1457  	} else {
  1458  		c.lastRaceErrors.Store(c.parent.checkRaces())
  1459  	}
  1460  }
  1461  
  1462  // checkRaces checks whether the global count of data race errors has increased
  1463  // since c's count was last reset.
  1464  //
  1465  // If so, it marks c as having failed due to those races (logging an error for
  1466  // the first such race), and updates the race counts for the parents of c so
  1467  // that if they are currently suspended (such as in a call to T.Run) they will
  1468  // not log separate errors for the race(s).
  1469  //
  1470  // Note that multiple tests may be marked as failed due to the same race if they
  1471  // are executing in parallel.
  1472  func (c *common) checkRaces() (raceErrors int64) {
  1473  	raceErrors = int64(race.Errors())
  1474  	for {
  1475  		last := c.lastRaceErrors.Load()
  1476  		if raceErrors <= last {
  1477  			// All races have already been reported.
  1478  			return raceErrors
  1479  		}
  1480  		if c.lastRaceErrors.CompareAndSwap(last, raceErrors) {
  1481  			break
  1482  		}
  1483  	}
  1484  
  1485  	if c.raceErrorLogged.CompareAndSwap(false, true) {
  1486  		// This is the first race we've encountered for this test.
  1487  		// Mark the test as failed, and log the reason why only once.
  1488  		// (Note that the race detector itself will still write a goroutine
  1489  		// dump for any further races it detects.)
  1490  		c.Errorf("race detected during execution of test")
  1491  	}
  1492  
  1493  	// Update the parent(s) of this test so that they don't re-report the race.
  1494  	parent := c.parent
  1495  	for parent != nil {
  1496  		for {
  1497  			last := parent.lastRaceErrors.Load()
  1498  			if raceErrors <= last {
  1499  				// This race was already reported by another (likely parallel) subtest.
  1500  				return raceErrors
  1501  			}
  1502  			if parent.lastRaceErrors.CompareAndSwap(last, raceErrors) {
  1503  				break
  1504  			}
  1505  		}
  1506  		parent = parent.parent
  1507  	}
  1508  
  1509  	return raceErrors
  1510  }
  1511  
  1512  // callerName gives the function name (qualified with a package path)
  1513  // for the caller after skip frames (where 0 means the current function).
  1514  func callerName(skip int) string {
  1515  	var pc [1]uintptr
  1516  	n := runtime.Callers(skip+2, pc[:]) // skip + runtime.Callers + callerName
  1517  	if n == 0 {
  1518  		panic("testing: zero callers found")
  1519  	}
  1520  	return pcToName(pc[0])
  1521  }
  1522  
  1523  func pcToName(pc uintptr) string {
  1524  	pcs := []uintptr{pc}
  1525  	frames := runtime.CallersFrames(pcs)
  1526  	frame, _ := frames.Next()
  1527  	return frame.Function
  1528  }
  1529  
  1530  const parallelConflict = `testing: test using t.Setenv or t.Chdir can not use t.Parallel`
  1531  
  1532  // Parallel signals that this test is to be run in parallel with (and only with)
  1533  // other parallel tests. When a test is run multiple times due to use of
  1534  // -test.count or -test.cpu, multiple instances of a single test never run in
  1535  // parallel with each other.
  1536  func (t *T) Parallel() {
  1537  	if t.isParallel {
  1538  		panic("testing: t.Parallel called multiple times")
  1539  	}
  1540  	if t.denyParallel {
  1541  		panic(parallelConflict)
  1542  	}
  1543  	t.isParallel = true
  1544  	if t.parent.barrier == nil {
  1545  		// T.Parallel has no effect when fuzzing.
  1546  		// Multiple processes may run in parallel, but only one input can run at a
  1547  		// time per process so we can attribute crashes to specific inputs.
  1548  		return
  1549  	}
  1550  
  1551  	// We don't want to include the time we spend waiting for serial tests
  1552  	// in the test duration. Record the elapsed time thus far and reset the
  1553  	// timer afterwards.
  1554  	t.duration += highPrecisionTimeSince(t.start)
  1555  
  1556  	// Add to the list of tests to be released by the parent.
  1557  	t.parent.sub = append(t.parent.sub, t)
  1558  
  1559  	// Report any races during execution of this test up to this point.
  1560  	//
  1561  	// We will assume that any races that occur between here and the point where
  1562  	// we unblock are not caused by this subtest. That assumption usually holds,
  1563  	// although it can be wrong if the test spawns a goroutine that races in the
  1564  	// background while the rest of the test is blocked on the call to Parallel.
  1565  	// If that happens, we will misattribute the background race to some other
  1566  	// test, or to no test at all — but that false-negative is so unlikely that it
  1567  	// is not worth adding race-report noise for the common case where the test is
  1568  	// completely suspended during the call to Parallel.
  1569  	t.checkRaces()
  1570  
  1571  	if t.chatty != nil {
  1572  		t.chatty.Updatef(t.name, "=== PAUSE %s\n", t.name)
  1573  	}
  1574  	running.Delete(t.name)
  1575  
  1576  	t.signal <- true   // Release calling test.
  1577  	<-t.parent.barrier // Wait for the parent test to complete.
  1578  	t.tstate.waitParallel()
  1579  
  1580  	if t.chatty != nil {
  1581  		t.chatty.Updatef(t.name, "=== CONT  %s\n", t.name)
  1582  	}
  1583  	running.Store(t.name, highPrecisionTimeNow())
  1584  	t.start = highPrecisionTimeNow()
  1585  
  1586  	// Reset the local race counter to ignore any races that happened while this
  1587  	// goroutine was blocked, such as in the parent test or in other parallel
  1588  	// subtests.
  1589  	//
  1590  	// (Note that we don't call parent.checkRaces here:
  1591  	// if other parallel subtests have already introduced races, we want to
  1592  	// let them report those races instead of attributing them to the parent.)
  1593  	t.lastRaceErrors.Store(int64(race.Errors()))
  1594  }
  1595  
  1596  func (t *T) checkParallel() {
  1597  	// Non-parallel subtests that have parallel ancestors may still
  1598  	// run in parallel with other tests: they are only non-parallel
  1599  	// with respect to the other subtests of the same parent.
  1600  	// Since calls like SetEnv or Chdir affects the whole process, we need
  1601  	// to deny those if the current test or any parent is parallel.
  1602  	for c := &t.common; c != nil; c = c.parent {
  1603  		if c.isParallel {
  1604  			panic(parallelConflict)
  1605  		}
  1606  	}
  1607  
  1608  	t.denyParallel = true
  1609  }
  1610  
  1611  // Setenv calls os.Setenv(key, value) and uses Cleanup to
  1612  // restore the environment variable to its original value
  1613  // after the test.
  1614  //
  1615  // Because Setenv affects the whole process, it cannot be used
  1616  // in parallel tests or tests with parallel ancestors.
  1617  func (t *T) Setenv(key, value string) {
  1618  	t.checkParallel()
  1619  	t.common.Setenv(key, value)
  1620  }
  1621  
  1622  // Chdir calls os.Chdir(dir) and uses Cleanup to restore the current
  1623  // working directory to its original value after the test. On Unix, it
  1624  // also sets PWD environment variable for the duration of the test.
  1625  //
  1626  // Because Chdir affects the whole process, it cannot be used
  1627  // in parallel tests or tests with parallel ancestors.
  1628  func (t *T) Chdir(dir string) {
  1629  	t.checkParallel()
  1630  	t.common.Chdir(dir)
  1631  }
  1632  
  1633  // InternalTest is an internal type but exported because it is cross-package;
  1634  // it is part of the implementation of the "go test" command.
  1635  type InternalTest struct {
  1636  	Name string
  1637  	F    func(*T)
  1638  }
  1639  
  1640  var errNilPanicOrGoexit = errors.New("test executed panic(nil) or runtime.Goexit")
  1641  
  1642  func tRunner(t *T, fn func(t *T)) {
  1643  	t.runner = callerName(0)
  1644  
  1645  	// When this goroutine is done, either because fn(t)
  1646  	// returned normally or because a test failure triggered
  1647  	// a call to runtime.Goexit, record the duration and send
  1648  	// a signal saying that the test is done.
  1649  	defer func() {
  1650  		t.checkRaces()
  1651  
  1652  		// TODO(#61034): This is the wrong place for this check.
  1653  		if t.Failed() {
  1654  			numFailed.Add(1)
  1655  		}
  1656  
  1657  		// Check if the test panicked or Goexited inappropriately.
  1658  		//
  1659  		// If this happens in a normal test, print output but continue panicking.
  1660  		// tRunner is called in its own goroutine, so this terminates the process.
  1661  		//
  1662  		// If this happens while fuzzing, recover from the panic and treat it like a
  1663  		// normal failure. It's important that the process keeps running in order to
  1664  		// find short inputs that cause panics.
  1665  		err := recover()
  1666  		signal := true
  1667  
  1668  		t.mu.RLock()
  1669  		finished := t.finished
  1670  		t.mu.RUnlock()
  1671  		if !finished && err == nil {
  1672  			err = errNilPanicOrGoexit
  1673  			for p := t.parent; p != nil; p = p.parent {
  1674  				p.mu.RLock()
  1675  				finished = p.finished
  1676  				p.mu.RUnlock()
  1677  				if finished {
  1678  					if !t.isParallel {
  1679  						t.Errorf("%v: subtest may have called FailNow on a parent test", err)
  1680  						err = nil
  1681  					}
  1682  					signal = false
  1683  					break
  1684  				}
  1685  			}
  1686  		}
  1687  
  1688  		if err != nil && t.tstate.isFuzzing {
  1689  			prefix := "panic: "
  1690  			if err == errNilPanicOrGoexit {
  1691  				prefix = ""
  1692  			}
  1693  			t.Errorf("%s%s\n%s\n", prefix, err, string(debug.Stack()))
  1694  			t.mu.Lock()
  1695  			t.finished = true
  1696  			t.mu.Unlock()
  1697  			err = nil
  1698  		}
  1699  
  1700  		// Use a deferred call to ensure that we report that the test is
  1701  		// complete even if a cleanup function calls t.FailNow. See issue 41355.
  1702  		didPanic := false
  1703  		defer func() {
  1704  			// Only report that the test is complete if it doesn't panic,
  1705  			// as otherwise the test binary can exit before the panic is
  1706  			// reported to the user. See issue 41479.
  1707  			if didPanic {
  1708  				return
  1709  			}
  1710  			if err != nil {
  1711  				panic(err)
  1712  			}
  1713  			running.Delete(t.name)
  1714  			t.signal <- signal
  1715  		}()
  1716  
  1717  		doPanic := func(err any) {
  1718  			t.Fail()
  1719  			if r := t.runCleanup(recoverAndReturnPanic); r != nil {
  1720  				t.Logf("cleanup panicked with %v", r)
  1721  			}
  1722  			// Flush the output log up to the root before dying.
  1723  			for root := &t.common; root.parent != nil; root = root.parent {
  1724  				root.mu.Lock()
  1725  				root.duration += highPrecisionTimeSince(root.start)
  1726  				d := root.duration
  1727  				root.mu.Unlock()
  1728  				root.flushToParent(root.name, "--- FAIL: %s (%s)\n", root.name, fmtDuration(d))
  1729  				if r := root.parent.runCleanup(recoverAndReturnPanic); r != nil {
  1730  					fmt.Fprintf(root.parent.w, "cleanup panicked with %v", r)
  1731  				}
  1732  			}
  1733  			didPanic = true
  1734  			panic(err)
  1735  		}
  1736  		if err != nil {
  1737  			doPanic(err)
  1738  		}
  1739  
  1740  		t.duration += highPrecisionTimeSince(t.start)
  1741  
  1742  		if len(t.sub) > 0 {
  1743  			// Run parallel subtests.
  1744  
  1745  			// Decrease the running count for this test and mark it as no longer running.
  1746  			t.tstate.release()
  1747  			running.Delete(t.name)
  1748  
  1749  			// Release the parallel subtests.
  1750  			close(t.barrier)
  1751  			// Wait for subtests to complete.
  1752  			for _, sub := range t.sub {
  1753  				<-sub.signal
  1754  			}
  1755  
  1756  			// Run any cleanup callbacks, marking the test as running
  1757  			// in case the cleanup hangs.
  1758  			cleanupStart := highPrecisionTimeNow()
  1759  			running.Store(t.name, cleanupStart)
  1760  			err := t.runCleanup(recoverAndReturnPanic)
  1761  			t.duration += highPrecisionTimeSince(cleanupStart)
  1762  			if err != nil {
  1763  				doPanic(err)
  1764  			}
  1765  			t.checkRaces()
  1766  			if !t.isParallel {
  1767  				// Reacquire the count for sequential tests. See comment in Run.
  1768  				t.tstate.waitParallel()
  1769  			}
  1770  		} else if t.isParallel {
  1771  			// Only release the count for this test if it was run as a parallel
  1772  			// test. See comment in Run method.
  1773  			t.tstate.release()
  1774  		}
  1775  		t.report() // Report after all subtests have finished.
  1776  
  1777  		// Do not lock t.done to allow race detector to detect race in case
  1778  		// the user does not appropriately synchronize a goroutine.
  1779  		t.done = true
  1780  		if t.parent != nil && !t.hasSub.Load() {
  1781  			t.setRan()
  1782  		}
  1783  	}()
  1784  	defer func() {
  1785  		if len(t.sub) == 0 {
  1786  			t.runCleanup(normalPanic)
  1787  		}
  1788  	}()
  1789  
  1790  	t.start = highPrecisionTimeNow()
  1791  	t.resetRaces()
  1792  	fn(t)
  1793  
  1794  	// code beyond here will not be executed when FailNow is invoked
  1795  	t.mu.Lock()
  1796  	t.finished = true
  1797  	t.mu.Unlock()
  1798  }
  1799  
  1800  // Run runs f as a subtest of t called name. It runs f in a separate goroutine
  1801  // and blocks until f returns or calls t.Parallel to become a parallel test.
  1802  // Run reports whether f succeeded (or at least did not fail before calling t.Parallel).
  1803  //
  1804  // Run may be called simultaneously from multiple goroutines, but all such calls
  1805  // must return before the outer test function for t returns.
  1806  func (t *T) Run(name string, f func(t *T)) bool {
  1807  	if t.cleanupStarted.Load() {
  1808  		panic("testing: t.Run called during t.Cleanup")
  1809  	}
  1810  
  1811  	t.hasSub.Store(true)
  1812  	testName, ok, _ := t.tstate.match.fullName(&t.common, name)
  1813  	if !ok || shouldFailFast() {
  1814  		return true
  1815  	}
  1816  	// Record the stack trace at the point of this call so that if the subtest
  1817  	// function - which runs in a separate stack - is marked as a helper, we can
  1818  	// continue walking the stack into the parent test.
  1819  	var pc [maxStackLen]uintptr
  1820  	n := runtime.Callers(2, pc[:])
  1821  
  1822  	// There's no reason to inherit this context from parent. The user's code can't observe
  1823  	// the difference between the background context and the one from the parent test.
  1824  	ctx, cancelCtx := context.WithCancel(context.Background())
  1825  	t = &T{
  1826  		common: common{
  1827  			barrier:   make(chan bool),
  1828  			signal:    make(chan bool, 1),
  1829  			name:      testName,
  1830  			parent:    &t.common,
  1831  			level:     t.level + 1,
  1832  			creator:   pc[:n],
  1833  			chatty:    t.chatty,
  1834  			ctx:       ctx,
  1835  			cancelCtx: cancelCtx,
  1836  		},
  1837  		tstate: t.tstate,
  1838  	}
  1839  	t.w = indenter{&t.common}
  1840  
  1841  	if t.chatty != nil {
  1842  		t.chatty.Updatef(t.name, "=== RUN   %s\n", t.name)
  1843  	}
  1844  	running.Store(t.name, highPrecisionTimeNow())
  1845  
  1846  	// Instead of reducing the running count of this test before calling the
  1847  	// tRunner and increasing it afterwards, we rely on tRunner keeping the
  1848  	// count correct. This ensures that a sequence of sequential tests runs
  1849  	// without being preempted, even when their parent is a parallel test. This
  1850  	// may especially reduce surprises if *parallel == 1.
  1851  	go tRunner(t, f)
  1852  
  1853  	// The parent goroutine will block until the subtest either finishes or calls
  1854  	// Parallel, but in general we don't know whether the parent goroutine is the
  1855  	// top-level test function or some other goroutine it has spawned.
  1856  	// To avoid confusing false-negatives, we leave the parent in the running map
  1857  	// even though in the typical case it is blocked.
  1858  
  1859  	if !<-t.signal {
  1860  		// At this point, it is likely that FailNow was called on one of the
  1861  		// parent tests by one of the subtests. Continue aborting up the chain.
  1862  		runtime.Goexit()
  1863  	}
  1864  
  1865  	if t.chatty != nil && t.chatty.json {
  1866  		t.chatty.Updatef(t.parent.name, "=== NAME  %s\n", t.parent.name)
  1867  	}
  1868  	return !t.failed
  1869  }
  1870  
  1871  // Deadline reports the time at which the test binary will have
  1872  // exceeded the timeout specified by the -timeout flag.
  1873  //
  1874  // The ok result is false if the -timeout flag indicates “no timeout” (0).
  1875  func (t *T) Deadline() (deadline time.Time, ok bool) {
  1876  	deadline = t.tstate.deadline
  1877  	return deadline, !deadline.IsZero()
  1878  }
  1879  
  1880  // testState holds all fields that are common to all tests. This includes
  1881  // synchronization primitives to run at most *parallel tests.
  1882  type testState struct {
  1883  	match    *matcher
  1884  	deadline time.Time
  1885  
  1886  	// isFuzzing is true in the state used when generating random inputs
  1887  	// for fuzz targets. isFuzzing is false when running normal tests and
  1888  	// when running fuzz tests as unit tests (without -fuzz or when -fuzz
  1889  	// does not match).
  1890  	isFuzzing bool
  1891  
  1892  	mu sync.Mutex
  1893  
  1894  	// Channel used to signal tests that are ready to be run in parallel.
  1895  	startParallel chan bool
  1896  
  1897  	// running is the number of tests currently running in parallel.
  1898  	// This does not include tests that are waiting for subtests to complete.
  1899  	running int
  1900  
  1901  	// numWaiting is the number tests waiting to be run in parallel.
  1902  	numWaiting int
  1903  
  1904  	// maxParallel is a copy of the parallel flag.
  1905  	maxParallel int
  1906  }
  1907  
  1908  func newTestState(maxParallel int, m *matcher) *testState {
  1909  	return &testState{
  1910  		match:         m,
  1911  		startParallel: make(chan bool),
  1912  		maxParallel:   maxParallel,
  1913  		running:       1, // Set the count to 1 for the main (sequential) test.
  1914  	}
  1915  }
  1916  
  1917  func (s *testState) waitParallel() {
  1918  	s.mu.Lock()
  1919  	if s.running < s.maxParallel {
  1920  		s.running++
  1921  		s.mu.Unlock()
  1922  		return
  1923  	}
  1924  	s.numWaiting++
  1925  	s.mu.Unlock()
  1926  	<-s.startParallel
  1927  }
  1928  
  1929  func (s *testState) release() {
  1930  	s.mu.Lock()
  1931  	if s.numWaiting == 0 {
  1932  		s.running--
  1933  		s.mu.Unlock()
  1934  		return
  1935  	}
  1936  	s.numWaiting--
  1937  	s.mu.Unlock()
  1938  	s.startParallel <- true // Pick a waiting test to be run.
  1939  }
  1940  
  1941  // No one should be using func Main anymore.
  1942  // See the doc comment on func Main and use MainStart instead.
  1943  var errMain = errors.New("testing: unexpected use of func Main")
  1944  
  1945  type matchStringOnly func(pat, str string) (bool, error)
  1946  
  1947  func (f matchStringOnly) MatchString(pat, str string) (bool, error)   { return f(pat, str) }
  1948  func (f matchStringOnly) StartCPUProfile(w io.Writer) error           { return errMain }
  1949  func (f matchStringOnly) StopCPUProfile()                             {}
  1950  func (f matchStringOnly) WriteProfileTo(string, io.Writer, int) error { return errMain }
  1951  func (f matchStringOnly) ImportPath() string                          { return "" }
  1952  func (f matchStringOnly) StartTestLog(io.Writer)                      {}
  1953  func (f matchStringOnly) StopTestLog() error                          { return errMain }
  1954  func (f matchStringOnly) SetPanicOnExit0(bool)                        {}
  1955  func (f matchStringOnly) CoordinateFuzzing(time.Duration, int64, time.Duration, int64, int, []corpusEntry, []reflect.Type, string, string) error {
  1956  	return errMain
  1957  }
  1958  func (f matchStringOnly) RunFuzzWorker(func(corpusEntry) error) error { return errMain }
  1959  func (f matchStringOnly) ReadCorpus(string, []reflect.Type) ([]corpusEntry, error) {
  1960  	return nil, errMain
  1961  }
  1962  func (f matchStringOnly) CheckCorpus([]any, []reflect.Type) error { return nil }
  1963  func (f matchStringOnly) ResetCoverage()                          {}
  1964  func (f matchStringOnly) SnapshotCoverage()                       {}
  1965  
  1966  func (f matchStringOnly) InitRuntimeCoverage() (mode string, tearDown func(string, string) (string, error), snapcov func() float64) {
  1967  	return
  1968  }
  1969  
  1970  // Main is an internal function, part of the implementation of the "go test" command.
  1971  // It was exported because it is cross-package and predates "internal" packages.
  1972  // It is no longer used by "go test" but preserved, as much as possible, for other
  1973  // systems that simulate "go test" using Main, but Main sometimes cannot be updated as
  1974  // new functionality is added to the testing package.
  1975  // Systems simulating "go test" should be updated to use MainStart.
  1976  func Main(matchString func(pat, str string) (bool, error), tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample) {
  1977  	os.Exit(MainStart(matchStringOnly(matchString), tests, benchmarks, nil, examples).Run())
  1978  }
  1979  
  1980  // M is a type passed to a TestMain function to run the actual tests.
  1981  type M struct {
  1982  	deps        testDeps
  1983  	tests       []InternalTest
  1984  	benchmarks  []InternalBenchmark
  1985  	fuzzTargets []InternalFuzzTarget
  1986  	examples    []InternalExample
  1987  
  1988  	timer     *time.Timer
  1989  	afterOnce sync.Once
  1990  
  1991  	numRun int
  1992  
  1993  	// value to pass to os.Exit, the outer test func main
  1994  	// harness calls os.Exit with this code. See #34129.
  1995  	exitCode int
  1996  }
  1997  
  1998  // testDeps is an internal interface of functionality that is
  1999  // passed into this package by a test's generated main package.
  2000  // The canonical implementation of this interface is
  2001  // testing/internal/testdeps's TestDeps.
  2002  type testDeps interface {
  2003  	ImportPath() string
  2004  	MatchString(pat, str string) (bool, error)
  2005  	SetPanicOnExit0(bool)
  2006  	StartCPUProfile(io.Writer) error
  2007  	StopCPUProfile()
  2008  	StartTestLog(io.Writer)
  2009  	StopTestLog() error
  2010  	WriteProfileTo(string, io.Writer, int) error
  2011  	CoordinateFuzzing(time.Duration, int64, time.Duration, int64, int, []corpusEntry, []reflect.Type, string, string) error
  2012  	RunFuzzWorker(func(corpusEntry) error) error
  2013  	ReadCorpus(string, []reflect.Type) ([]corpusEntry, error)
  2014  	CheckCorpus([]any, []reflect.Type) error
  2015  	ResetCoverage()
  2016  	SnapshotCoverage()
  2017  	InitRuntimeCoverage() (mode string, tearDown func(coverprofile string, gocoverdir string) (string, error), snapcov func() float64)
  2018  }
  2019  
  2020  // MainStart is meant for use by tests generated by 'go test'.
  2021  // It is not meant to be called directly and is not subject to the Go 1 compatibility document.
  2022  // It may change signature from release to release.
  2023  func MainStart(deps testDeps, tests []InternalTest, benchmarks []InternalBenchmark, fuzzTargets []InternalFuzzTarget, examples []InternalExample) *M {
  2024  	registerCover2(deps.InitRuntimeCoverage())
  2025  	Init()
  2026  	return &M{
  2027  		deps:        deps,
  2028  		tests:       tests,
  2029  		benchmarks:  benchmarks,
  2030  		fuzzTargets: fuzzTargets,
  2031  		examples:    examples,
  2032  	}
  2033  }
  2034  
  2035  var testingTesting bool
  2036  var realStderr *os.File
  2037  
  2038  // Run runs the tests. It returns an exit code to pass to os.Exit.
  2039  func (m *M) Run() (code int) {
  2040  	defer func() {
  2041  		code = m.exitCode
  2042  	}()
  2043  
  2044  	// Count the number of calls to m.Run.
  2045  	// We only ever expected 1, but we didn't enforce that,
  2046  	// and now there are tests in the wild that call m.Run multiple times.
  2047  	// Sigh. go.dev/issue/23129.
  2048  	m.numRun++
  2049  
  2050  	// TestMain may have already called flag.Parse.
  2051  	if !flag.Parsed() {
  2052  		flag.Parse()
  2053  	}
  2054  
  2055  	if chatty.json {
  2056  		// With -v=json, stdout and stderr are pointing to the same pipe,
  2057  		// which is leading into test2json. In general, operating systems
  2058  		// do a good job of ensuring that writes to the same pipe through
  2059  		// different file descriptors are delivered whole, so that writing
  2060  		// AAA to stdout and BBB to stderr simultaneously produces
  2061  		// AAABBB or BBBAAA on the pipe, not something like AABBBA.
  2062  		// However, the exception to this is when the pipe fills: in that
  2063  		// case, Go's use of non-blocking I/O means that writing AAA
  2064  		// or BBB might be split across multiple system calls, making it
  2065  		// entirely possible to get output like AABBBA. The same problem
  2066  		// happens inside the operating system kernel if we switch to
  2067  		// blocking I/O on the pipe. This interleaved output can do things
  2068  		// like print unrelated messages in the middle of a TestFoo line,
  2069  		// which confuses test2json. Setting os.Stderr = os.Stdout will make
  2070  		// them share a single pfd, which will hold a lock for each program
  2071  		// write, preventing any interleaving.
  2072  		//
  2073  		// It might be nice to set Stderr = Stdout always, or perhaps if
  2074  		// we can tell they are the same file, but for now -v=json is
  2075  		// a very clear signal. Making the two files the same may cause
  2076  		// surprises if programs close os.Stdout but expect to be able
  2077  		// to continue to write to os.Stderr, but it's hard to see why a
  2078  		// test would think it could take over global state that way.
  2079  		//
  2080  		// This fix only helps programs where the output is coming directly
  2081  		// from Go code. It does not help programs in which a subprocess is
  2082  		// writing to stderr or stdout at the same time that a Go test is writing output.
  2083  		// It also does not help when the output is coming from the runtime,
  2084  		// such as when using the print/println functions, since that code writes
  2085  		// directly to fd 2 without any locking.
  2086  		// We keep realStderr around to prevent fd 2 from being closed.
  2087  		//
  2088  		// See go.dev/issue/33419.
  2089  		realStderr = os.Stderr
  2090  		os.Stderr = os.Stdout
  2091  	}
  2092  
  2093  	if *parallel < 1 {
  2094  		fmt.Fprintln(os.Stderr, "testing: -parallel can only be given a positive integer")
  2095  		flag.Usage()
  2096  		m.exitCode = 2
  2097  		return
  2098  	}
  2099  	if *matchFuzz != "" && *fuzzCacheDir == "" {
  2100  		fmt.Fprintln(os.Stderr, "testing: -test.fuzzcachedir must be set if -test.fuzz is set")
  2101  		flag.Usage()
  2102  		m.exitCode = 2
  2103  		return
  2104  	}
  2105  
  2106  	if *matchList != "" {
  2107  		listTests(m.deps.MatchString, m.tests, m.benchmarks, m.fuzzTargets, m.examples)
  2108  		m.exitCode = 0
  2109  		return
  2110  	}
  2111  
  2112  	if *shuffle != "off" {
  2113  		var n int64
  2114  		var err error
  2115  		if *shuffle == "on" {
  2116  			n = time.Now().UnixNano()
  2117  		} else {
  2118  			n, err = strconv.ParseInt(*shuffle, 10, 64)
  2119  			if err != nil {
  2120  				fmt.Fprintln(os.Stderr, `testing: -shuffle should be "off", "on", or a valid integer:`, err)
  2121  				m.exitCode = 2
  2122  				return
  2123  			}
  2124  		}
  2125  		fmt.Println("-test.shuffle", n)
  2126  		rng := rand.New(rand.NewSource(n))
  2127  		rng.Shuffle(len(m.tests), func(i, j int) { m.tests[i], m.tests[j] = m.tests[j], m.tests[i] })
  2128  		rng.Shuffle(len(m.benchmarks), func(i, j int) { m.benchmarks[i], m.benchmarks[j] = m.benchmarks[j], m.benchmarks[i] })
  2129  	}
  2130  
  2131  	parseCpuList()
  2132  
  2133  	m.before()
  2134  	defer m.after()
  2135  
  2136  	// Run tests, examples, and benchmarks unless this is a fuzz worker process.
  2137  	// Workers start after this is done by their parent process, and they should
  2138  	// not repeat this work.
  2139  	if !*isFuzzWorker {
  2140  		deadline := m.startAlarm()
  2141  		haveExamples = len(m.examples) > 0
  2142  		testRan, testOk := runTests(m.deps.MatchString, m.tests, deadline)
  2143  		fuzzTargetsRan, fuzzTargetsOk := runFuzzTests(m.deps, m.fuzzTargets, deadline)
  2144  		exampleRan, exampleOk := runExamples(m.deps.MatchString, m.examples)
  2145  		m.stopAlarm()
  2146  		if !testRan && !exampleRan && !fuzzTargetsRan && *matchBenchmarks == "" && *matchFuzz == "" {
  2147  			fmt.Fprintln(os.Stderr, "testing: warning: no tests to run")
  2148  			if testingTesting && *match != "^$" {
  2149  				// If this happens during testing of package testing it could be that
  2150  				// package testing's own logic for when to run a test is broken,
  2151  				// in which case every test will run nothing and succeed,
  2152  				// with no obvious way to detect this problem (since no tests are running).
  2153  				// So make 'no tests to run' a hard failure when testing package testing itself.
  2154  				fmt.Print(chatty.prefix(), "FAIL: package testing must run tests\n")
  2155  				testOk = false
  2156  			}
  2157  		}
  2158  		anyFailed := !testOk || !exampleOk || !fuzzTargetsOk || !runBenchmarks(m.deps.ImportPath(), m.deps.MatchString, m.benchmarks)
  2159  		if !anyFailed && race.Errors() > 0 {
  2160  			fmt.Print(chatty.prefix(), "testing: race detected outside of test execution\n")
  2161  			anyFailed = true
  2162  		}
  2163  		if anyFailed {
  2164  			fmt.Print(chatty.prefix(), "FAIL\n")
  2165  			m.exitCode = 1
  2166  			return
  2167  		}
  2168  	}
  2169  
  2170  	fuzzingOk := runFuzzing(m.deps, m.fuzzTargets)
  2171  	if !fuzzingOk {
  2172  		fmt.Print(chatty.prefix(), "FAIL\n")
  2173  		if *isFuzzWorker {
  2174  			m.exitCode = fuzzWorkerExitCode
  2175  		} else {
  2176  			m.exitCode = 1
  2177  		}
  2178  		return
  2179  	}
  2180  
  2181  	m.exitCode = 0
  2182  	if !*isFuzzWorker {
  2183  		fmt.Print(chatty.prefix(), "PASS\n")
  2184  	}
  2185  	return
  2186  }
  2187  
  2188  func (t *T) report() {
  2189  	if t.parent == nil {
  2190  		return
  2191  	}
  2192  	dstr := fmtDuration(t.duration)
  2193  	format := "--- %s: %s (%s)\n"
  2194  	if t.Failed() {
  2195  		t.flushToParent(t.name, format, "FAIL", t.name, dstr)
  2196  	} else if t.chatty != nil {
  2197  		if t.Skipped() {
  2198  			t.flushToParent(t.name, format, "SKIP", t.name, dstr)
  2199  		} else {
  2200  			t.flushToParent(t.name, format, "PASS", t.name, dstr)
  2201  		}
  2202  	}
  2203  }
  2204  
  2205  func listTests(matchString func(pat, str string) (bool, error), tests []InternalTest, benchmarks []InternalBenchmark, fuzzTargets []InternalFuzzTarget, examples []InternalExample) {
  2206  	if _, err := matchString(*matchList, "non-empty"); err != nil {
  2207  		fmt.Fprintf(os.Stderr, "testing: invalid regexp in -test.list (%q): %s\n", *matchList, err)
  2208  		os.Exit(1)
  2209  	}
  2210  
  2211  	for _, test := range tests {
  2212  		if ok, _ := matchString(*matchList, test.Name); ok {
  2213  			fmt.Println(test.Name)
  2214  		}
  2215  	}
  2216  	for _, bench := range benchmarks {
  2217  		if ok, _ := matchString(*matchList, bench.Name); ok {
  2218  			fmt.Println(bench.Name)
  2219  		}
  2220  	}
  2221  	for _, fuzzTarget := range fuzzTargets {
  2222  		if ok, _ := matchString(*matchList, fuzzTarget.Name); ok {
  2223  			fmt.Println(fuzzTarget.Name)
  2224  		}
  2225  	}
  2226  	for _, example := range examples {
  2227  		if ok, _ := matchString(*matchList, example.Name); ok {
  2228  			fmt.Println(example.Name)
  2229  		}
  2230  	}
  2231  }
  2232  
  2233  // RunTests is an internal function but exported because it is cross-package;
  2234  // it is part of the implementation of the "go test" command.
  2235  func RunTests(matchString func(pat, str string) (bool, error), tests []InternalTest) (ok bool) {
  2236  	var deadline time.Time
  2237  	if *timeout > 0 {
  2238  		deadline = time.Now().Add(*timeout)
  2239  	}
  2240  	ran, ok := runTests(matchString, tests, deadline)
  2241  	if !ran && !haveExamples {
  2242  		fmt.Fprintln(os.Stderr, "testing: warning: no tests to run")
  2243  	}
  2244  	return ok
  2245  }
  2246  
  2247  func runTests(matchString func(pat, str string) (bool, error), tests []InternalTest, deadline time.Time) (ran, ok bool) {
  2248  	ok = true
  2249  	for _, procs := range cpuList {
  2250  		runtime.GOMAXPROCS(procs)
  2251  		for i := uint(0); i < *count; i++ {
  2252  			if shouldFailFast() {
  2253  				break
  2254  			}
  2255  			if i > 0 && !ran {
  2256  				// There were no tests to run on the first
  2257  				// iteration. This won't change, so no reason
  2258  				// to keep trying.
  2259  				break
  2260  			}
  2261  			ctx, cancelCtx := context.WithCancel(context.Background())
  2262  			tstate := newTestState(*parallel, newMatcher(matchString, *match, "-test.run", *skip))
  2263  			tstate.deadline = deadline
  2264  			t := &T{
  2265  				common: common{
  2266  					signal:    make(chan bool, 1),
  2267  					barrier:   make(chan bool),
  2268  					w:         os.Stdout,
  2269  					ctx:       ctx,
  2270  					cancelCtx: cancelCtx,
  2271  				},
  2272  				tstate: tstate,
  2273  			}
  2274  			if Verbose() {
  2275  				t.chatty = newChattyPrinter(t.w)
  2276  			}
  2277  			tRunner(t, func(t *T) {
  2278  				for _, test := range tests {
  2279  					t.Run(test.Name, test.F)
  2280  				}
  2281  			})
  2282  			select {
  2283  			case <-t.signal:
  2284  			default:
  2285  				panic("internal error: tRunner exited without sending on t.signal")
  2286  			}
  2287  			ok = ok && !t.Failed()
  2288  			ran = ran || t.ran
  2289  		}
  2290  	}
  2291  	return ran, ok
  2292  }
  2293  
  2294  // before runs before all testing.
  2295  func (m *M) before() {
  2296  	if *memProfileRate > 0 {
  2297  		runtime.MemProfileRate = *memProfileRate
  2298  	}
  2299  	if *cpuProfile != "" {
  2300  		f, err := os.Create(toOutputDir(*cpuProfile))
  2301  		if err != nil {
  2302  			fmt.Fprintf(os.Stderr, "testing: %s\n", err)
  2303  			return
  2304  		}
  2305  		if err := m.deps.StartCPUProfile(f); err != nil {
  2306  			fmt.Fprintf(os.Stderr, "testing: can't start cpu profile: %s\n", err)
  2307  			f.Close()
  2308  			return
  2309  		}
  2310  		// Could save f so after can call f.Close; not worth the effort.
  2311  	}
  2312  	if *traceFile != "" {
  2313  		f, err := os.Create(toOutputDir(*traceFile))
  2314  		if err != nil {
  2315  			fmt.Fprintf(os.Stderr, "testing: %s\n", err)
  2316  			return
  2317  		}
  2318  		if err := trace.Start(f); err != nil {
  2319  			fmt.Fprintf(os.Stderr, "testing: can't start tracing: %s\n", err)
  2320  			f.Close()
  2321  			return
  2322  		}
  2323  		// Could save f so after can call f.Close; not worth the effort.
  2324  	}
  2325  	if *blockProfile != "" && *blockProfileRate >= 0 {
  2326  		runtime.SetBlockProfileRate(*blockProfileRate)
  2327  	}
  2328  	if *mutexProfile != "" && *mutexProfileFraction >= 0 {
  2329  		runtime.SetMutexProfileFraction(*mutexProfileFraction)
  2330  	}
  2331  	if *coverProfile != "" && CoverMode() == "" {
  2332  		fmt.Fprintf(os.Stderr, "testing: cannot use -test.coverprofile because test binary was not built with coverage enabled\n")
  2333  		os.Exit(2)
  2334  	}
  2335  	if *gocoverdir != "" && CoverMode() == "" {
  2336  		fmt.Fprintf(os.Stderr, "testing: cannot use -test.gocoverdir because test binary was not built with coverage enabled\n")
  2337  		os.Exit(2)
  2338  	}
  2339  	if *testlog != "" {
  2340  		// Note: Not using toOutputDir.
  2341  		// This file is for use by cmd/go, not users.
  2342  		var f *os.File
  2343  		var err error
  2344  		if m.numRun == 1 {
  2345  			f, err = os.Create(*testlog)
  2346  		} else {
  2347  			f, err = os.OpenFile(*testlog, os.O_WRONLY, 0)
  2348  			if err == nil {
  2349  				f.Seek(0, io.SeekEnd)
  2350  			}
  2351  		}
  2352  		if err != nil {
  2353  			fmt.Fprintf(os.Stderr, "testing: %s\n", err)
  2354  			os.Exit(2)
  2355  		}
  2356  		m.deps.StartTestLog(f)
  2357  		testlogFile = f
  2358  	}
  2359  	if *panicOnExit0 {
  2360  		m.deps.SetPanicOnExit0(true)
  2361  	}
  2362  }
  2363  
  2364  // after runs after all testing.
  2365  func (m *M) after() {
  2366  	m.afterOnce.Do(func() {
  2367  		m.writeProfiles()
  2368  	})
  2369  
  2370  	// Restore PanicOnExit0 after every run, because we set it to true before
  2371  	// every run. Otherwise, if m.Run is called multiple times the behavior of
  2372  	// os.Exit(0) will not be restored after the second run.
  2373  	if *panicOnExit0 {
  2374  		m.deps.SetPanicOnExit0(false)
  2375  	}
  2376  }
  2377  
  2378  func (m *M) writeProfiles() {
  2379  	if *testlog != "" {
  2380  		if err := m.deps.StopTestLog(); err != nil {
  2381  			fmt.Fprintf(os.Stderr, "testing: can't write %s: %s\n", *testlog, err)
  2382  			os.Exit(2)
  2383  		}
  2384  		if err := testlogFile.Close(); err != nil {
  2385  			fmt.Fprintf(os.Stderr, "testing: can't write %s: %s\n", *testlog, err)
  2386  			os.Exit(2)
  2387  		}
  2388  	}
  2389  	if *cpuProfile != "" {
  2390  		m.deps.StopCPUProfile() // flushes profile to disk
  2391  	}
  2392  	if *traceFile != "" {
  2393  		trace.Stop() // flushes trace to disk
  2394  	}
  2395  	if *memProfile != "" {
  2396  		f, err := os.Create(toOutputDir(*memProfile))
  2397  		if err != nil {
  2398  			fmt.Fprintf(os.Stderr, "testing: %s\n", err)
  2399  			os.Exit(2)
  2400  		}
  2401  		runtime.GC() // materialize all statistics
  2402  		if err = m.deps.WriteProfileTo("allocs", f, 0); err != nil {
  2403  			fmt.Fprintf(os.Stderr, "testing: can't write %s: %s\n", *memProfile, err)
  2404  			os.Exit(2)
  2405  		}
  2406  		f.Close()
  2407  	}
  2408  	if *blockProfile != "" && *blockProfileRate >= 0 {
  2409  		f, err := os.Create(toOutputDir(*blockProfile))
  2410  		if err != nil {
  2411  			fmt.Fprintf(os.Stderr, "testing: %s\n", err)
  2412  			os.Exit(2)
  2413  		}
  2414  		if err = m.deps.WriteProfileTo("block", f, 0); err != nil {
  2415  			fmt.Fprintf(os.Stderr, "testing: can't write %s: %s\n", *blockProfile, err)
  2416  			os.Exit(2)
  2417  		}
  2418  		f.Close()
  2419  	}
  2420  	if *mutexProfile != "" && *mutexProfileFraction >= 0 {
  2421  		f, err := os.Create(toOutputDir(*mutexProfile))
  2422  		if err != nil {
  2423  			fmt.Fprintf(os.Stderr, "testing: %s\n", err)
  2424  			os.Exit(2)
  2425  		}
  2426  		if err = m.deps.WriteProfileTo("mutex", f, 0); err != nil {
  2427  			fmt.Fprintf(os.Stderr, "testing: can't write %s: %s\n", *mutexProfile, err)
  2428  			os.Exit(2)
  2429  		}
  2430  		f.Close()
  2431  	}
  2432  	if CoverMode() != "" {
  2433  		coverReport()
  2434  	}
  2435  }
  2436  
  2437  // toOutputDir returns the file name relocated, if required, to outputDir.
  2438  // Simple implementation to avoid pulling in path/filepath.
  2439  func toOutputDir(path string) string {
  2440  	if *outputDir == "" || path == "" {
  2441  		return path
  2442  	}
  2443  	// On Windows, it's clumsy, but we can be almost always correct
  2444  	// by just looking for a drive letter and a colon.
  2445  	// Absolute paths always have a drive letter (ignoring UNC).
  2446  	// Problem: if path == "C:A" and outputdir == "C:\Go" it's unclear
  2447  	// what to do, but even then path/filepath doesn't help.
  2448  	// TODO: Worth doing better? Probably not, because we're here only
  2449  	// under the management of go test.
  2450  	if runtime.GOOS == "windows" && len(path) >= 2 {
  2451  		letter, colon := path[0], path[1]
  2452  		if ('a' <= letter && letter <= 'z' || 'A' <= letter && letter <= 'Z') && colon == ':' {
  2453  			// If path starts with a drive letter we're stuck with it regardless.
  2454  			return path
  2455  		}
  2456  	}
  2457  	if os.IsPathSeparator(path[0]) {
  2458  		return path
  2459  	}
  2460  	return fmt.Sprintf("%s%c%s", *outputDir, os.PathSeparator, path)
  2461  }
  2462  
  2463  // startAlarm starts an alarm if requested.
  2464  func (m *M) startAlarm() time.Time {
  2465  	if *timeout <= 0 {
  2466  		return time.Time{}
  2467  	}
  2468  
  2469  	deadline := time.Now().Add(*timeout)
  2470  	m.timer = time.AfterFunc(*timeout, func() {
  2471  		m.after()
  2472  		debug.SetTraceback("all")
  2473  		extra := ""
  2474  
  2475  		if list := runningList(); len(list) > 0 {
  2476  			var b strings.Builder
  2477  			b.WriteString("\nrunning tests:")
  2478  			for _, name := range list {
  2479  				b.WriteString("\n\t")
  2480  				b.WriteString(name)
  2481  			}
  2482  			extra = b.String()
  2483  		}
  2484  		panic(fmt.Sprintf("test timed out after %v%s", *timeout, extra))
  2485  	})
  2486  	return deadline
  2487  }
  2488  
  2489  // runningList returns the list of running tests.
  2490  func runningList() []string {
  2491  	var list []string
  2492  	running.Range(func(k, v any) bool {
  2493  		list = append(list, fmt.Sprintf("%s (%v)", k.(string), highPrecisionTimeSince(v.(highPrecisionTime)).Round(time.Second)))
  2494  		return true
  2495  	})
  2496  	slices.Sort(list)
  2497  	return list
  2498  }
  2499  
  2500  // stopAlarm turns off the alarm.
  2501  func (m *M) stopAlarm() {
  2502  	if *timeout > 0 {
  2503  		m.timer.Stop()
  2504  	}
  2505  }
  2506  
  2507  func parseCpuList() {
  2508  	for _, val := range strings.Split(*cpuListStr, ",") {
  2509  		val = strings.TrimSpace(val)
  2510  		if val == "" {
  2511  			continue
  2512  		}
  2513  		cpu, err := strconv.Atoi(val)
  2514  		if err != nil || cpu <= 0 {
  2515  			fmt.Fprintf(os.Stderr, "testing: invalid value %q for -test.cpu\n", val)
  2516  			os.Exit(1)
  2517  		}
  2518  		cpuList = append(cpuList, cpu)
  2519  	}
  2520  	if cpuList == nil {
  2521  		cpuList = append(cpuList, runtime.GOMAXPROCS(-1))
  2522  	}
  2523  }
  2524  
  2525  func shouldFailFast() bool {
  2526  	return *failFast && numFailed.Load() > 0
  2527  }
  2528  

View as plain text