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

View as plain text