Source file src/testing/testing.go

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

View as plain text