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