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