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