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