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