Debian Codegraph @

libgo/go/testing/testing.go

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