github.com/hikaru7719/go@v0.0.0-20181025140707-c8b2ac68906a/src/testing/testing.go (about) 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 // Tests and benchmarks may be skipped if not applicable with a call to 21 // the Skip method of *T and *B: 22 // func TestTimeConsuming(t *testing.T) { 23 // if testing.Short() { 24 // t.Skip("skipping test in short mode.") 25 // } 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 BenchmarkHello(b *testing.B) { 41 // for i := 0; i < b.N; i++ { 42 // fmt.Sprintf("hello") 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 // BenchmarkHello 10000000 282 ns/op 50 // means that the loop ran 10000000 times at a speed of 282 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(4) { 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 // Subtests and Sub-benchmarks 136 // 137 // The Run methods of T and B allow defining subtests and sub-benchmarks, 138 // without having to define separate functions for each. This enables uses 139 // like table-driven benchmarks and creating hierarchical tests. 140 // It also provides a way to share common setup and tear-down code: 141 // 142 // func TestFoo(t *testing.T) { 143 // // <setup code> 144 // t.Run("A=1", func(t *testing.T) { ... }) 145 // t.Run("A=2", func(t *testing.T) { ... }) 146 // t.Run("B=1", func(t *testing.T) { ... }) 147 // // <tear-down code> 148 // } 149 // 150 // Each subtest and sub-benchmark has a unique name: the combination of the name 151 // of the top-level test and the sequence of names passed to Run, separated by 152 // slashes, with an optional trailing sequence number for disambiguation. 153 // 154 // The argument to the -run and -bench command-line flags is an unanchored regular 155 // expression that matches the test's name. For tests with multiple slash-separated 156 // elements, such as subtests, the argument is itself slash-separated, with 157 // expressions matching each name element in turn. Because it is unanchored, an 158 // empty expression matches any string. 159 // For example, using "matching" to mean "whose name contains": 160 // 161 // go test -run '' # Run all tests. 162 // go test -run Foo # Run top-level tests matching "Foo", such as "TestFooBar". 163 // go test -run Foo/A= # For top-level tests matching "Foo", run subtests matching "A=". 164 // go test -run /A=1 # For all top-level tests, run subtests matching "A=1". 165 // 166 // Subtests can also be used to control parallelism. A parent test will only 167 // complete once all of its subtests complete. In this example, all tests are 168 // run in parallel with each other, and only with each other, regardless of 169 // other top-level tests that may be defined: 170 // 171 // func TestGroupedParallel(t *testing.T) { 172 // for _, tc := range tests { 173 // tc := tc // capture range variable 174 // t.Run(tc.Name, func(t *testing.T) { 175 // t.Parallel() 176 // ... 177 // }) 178 // } 179 // } 180 // 181 // The race detector kills the program if it exceeds 8192 concurrent goroutines, 182 // so use care when running parallel tests with the -race flag set. 183 // 184 // Run does not return until parallel subtests have completed, providing a way 185 // to clean up after a group of parallel tests: 186 // 187 // func TestTeardownParallel(t *testing.T) { 188 // // This Run will not return until the parallel tests finish. 189 // t.Run("group", func(t *testing.T) { 190 // t.Run("Test1", parallelTest1) 191 // t.Run("Test2", parallelTest2) 192 // t.Run("Test3", parallelTest3) 193 // }) 194 // // <tear-down code> 195 // } 196 // 197 // Main 198 // 199 // It is sometimes necessary for a test program to do extra setup or teardown 200 // before or after testing. It is also sometimes necessary for a test to control 201 // which code runs on the main thread. To support these and other cases, 202 // if a test file contains a function: 203 // 204 // func TestMain(m *testing.M) 205 // 206 // then the generated test will call TestMain(m) instead of running the tests 207 // directly. TestMain runs in the main goroutine and can do whatever setup 208 // and teardown is necessary around a call to m.Run. It should then call 209 // os.Exit with the result of m.Run. When TestMain is called, flag.Parse has 210 // not been run. If TestMain depends on command-line flags, including those 211 // of the testing package, it should call flag.Parse explicitly. 212 // 213 // A simple implementation of TestMain is: 214 // 215 // func TestMain(m *testing.M) { 216 // // call flag.Parse() here if TestMain uses flags 217 // os.Exit(m.Run()) 218 // } 219 // 220 package testing 221 222 import ( 223 "bytes" 224 "errors" 225 "flag" 226 "fmt" 227 "internal/race" 228 "io" 229 "os" 230 "runtime" 231 "runtime/debug" 232 "runtime/trace" 233 "strconv" 234 "strings" 235 "sync" 236 "sync/atomic" 237 "time" 238 ) 239 240 var ( 241 // The short flag requests that tests run more quickly, but its functionality 242 // is provided by test writers themselves. The testing package is just its 243 // home. The all.bash installation script sets it to make installation more 244 // efficient, but by default the flag is off so a plain "go test" will do a 245 // full test of the package. 246 short = flag.Bool("test.short", false, "run smaller test suite to save time") 247 248 // The failfast flag requests that test execution stop after the first test failure. 249 failFast = flag.Bool("test.failfast", false, "do not start new tests after the first test failure") 250 251 // The directory in which to create profile files and the like. When run from 252 // "go test", the binary always runs in the source directory for the package; 253 // this flag lets "go test" tell the binary to write the files in the directory where 254 // the "go test" command is run. 255 outputDir = flag.String("test.outputdir", "", "write profiles to `dir`") 256 257 // Report as tests are run; default is silent for success. 258 chatty = flag.Bool("test.v", false, "verbose: print additional output") 259 count = flag.Uint("test.count", 1, "run tests and benchmarks `n` times") 260 coverProfile = flag.String("test.coverprofile", "", "write a coverage profile to `file`") 261 matchList = flag.String("test.list", "", "list tests, examples, and benchmarks matching `regexp` then exit") 262 match = flag.String("test.run", "", "run only tests and examples matching `regexp`") 263 memProfile = flag.String("test.memprofile", "", "write an allocation profile to `file`") 264 memProfileRate = flag.Int("test.memprofilerate", 0, "set memory allocation profiling `rate` (see runtime.MemProfileRate)") 265 cpuProfile = flag.String("test.cpuprofile", "", "write a cpu profile to `file`") 266 blockProfile = flag.String("test.blockprofile", "", "write a goroutine blocking profile to `file`") 267 blockProfileRate = flag.Int("test.blockprofilerate", 1, "set blocking profile `rate` (see runtime.SetBlockProfileRate)") 268 mutexProfile = flag.String("test.mutexprofile", "", "write a mutex contention profile to the named file after execution") 269 mutexProfileFraction = flag.Int("test.mutexprofilefraction", 1, "if >= 0, calls runtime.SetMutexProfileFraction()") 270 traceFile = flag.String("test.trace", "", "write an execution trace to `file`") 271 timeout = flag.Duration("test.timeout", 0, "panic test binary after duration `d` (default 0, timeout disabled)") 272 cpuListStr = flag.String("test.cpu", "", "comma-separated `list` of cpu counts to run each test with") 273 parallel = flag.Int("test.parallel", runtime.GOMAXPROCS(0), "run at most `n` tests in parallel") 274 testlog = flag.String("test.testlogfile", "", "write test action log to `file` (for use only by cmd/go)") 275 276 haveExamples bool // are there examples? 277 278 cpuList []int 279 testlogFile *os.File 280 281 numFailed uint32 // number of test failures 282 ) 283 284 // The maximum number of stack frames to go through when skipping helper functions for 285 // the purpose of decorating log messages. 286 const maxStackLen = 50 287 288 // common holds the elements common between T and B and 289 // captures common methods such as Errorf. 290 type common struct { 291 mu sync.RWMutex // guards this group of fields 292 output []byte // Output generated by test or benchmark. 293 w io.Writer // For flushToParent. 294 ran bool // Test or benchmark (or one of its subtests) was executed. 295 failed bool // Test or benchmark has failed. 296 skipped bool // Test of benchmark has been skipped. 297 done bool // Test is finished and all subtests have completed. 298 helpers map[string]struct{} // functions to be skipped when writing file/line info 299 300 chatty bool // A copy of the chatty flag. 301 finished bool // Test function has completed. 302 hasSub int32 // written atomically 303 raceErrors int // number of races detected during test 304 runner string // function name of tRunner running the test 305 306 parent *common 307 level int // Nesting depth of test or benchmark. 308 creator []uintptr // If level > 0, the stack trace at the point where the parent called t.Run. 309 name string // Name of test or benchmark. 310 start time.Time // Time test or benchmark started 311 duration time.Duration 312 barrier chan bool // To signal parallel subtests they may start. 313 signal chan bool // To signal a test is done. 314 sub []*T // Queue of subtests to be run in parallel. 315 } 316 317 // Short reports whether the -test.short flag is set. 318 func Short() bool { 319 // Catch code that calls this from TestMain without first 320 // calling flag.Parse. This shouldn't really be a panic 321 if !flag.Parsed() { 322 fmt.Fprintf(os.Stderr, "testing: testing.Short called before flag.Parse\n") 323 os.Exit(2) 324 } 325 326 return *short 327 } 328 329 // CoverMode reports what the test coverage mode is set to. The 330 // values are "set", "count", or "atomic". The return value will be 331 // empty if test coverage is not enabled. 332 func CoverMode() string { 333 return cover.Mode 334 } 335 336 // Verbose reports whether the -test.v flag is set. 337 func Verbose() bool { 338 return *chatty 339 } 340 341 // frameSkip searches, starting after skip frames, for the first caller frame 342 // in a function not marked as a helper and returns that frame. 343 // The search stops if it finds a tRunner function that 344 // was the entry point into the test and the test is not a subtest. 345 // This function must be called with c.mu held. 346 func (c *common) frameSkip(skip int) runtime.Frame { 347 // If the search continues into the parent test, we'll have to hold 348 // its mu temporarily. If we then return, we need to unlock it. 349 shouldUnlock := false 350 defer func() { 351 if shouldUnlock { 352 c.mu.Unlock() 353 } 354 }() 355 var pc [maxStackLen]uintptr 356 // Skip two extra frames to account for this function 357 // and runtime.Callers itself. 358 n := runtime.Callers(skip+2, pc[:]) 359 if n == 0 { 360 panic("testing: zero callers found") 361 } 362 frames := runtime.CallersFrames(pc[:n]) 363 var firstFrame, prevFrame, frame runtime.Frame 364 for more := true; more; prevFrame = frame { 365 frame, more = frames.Next() 366 if firstFrame.PC == 0 { 367 firstFrame = frame 368 } 369 if frame.Function == c.runner { 370 // We've gone up all the way to the tRunner calling 371 // the test function (so the user must have 372 // called tb.Helper from inside that test function). 373 // If this is a top-level test, only skip up to the test function itself. 374 // If we're in a subtest, continue searching in the parent test, 375 // starting from the point of the call to Run which created this subtest. 376 if c.level > 1 { 377 frames = runtime.CallersFrames(c.creator) 378 parent := c.parent 379 // We're no longer looking at the current c after this point, 380 // so we should unlock its mu, unless it's the original receiver, 381 // in which case our caller doesn't expect us to do that. 382 if shouldUnlock { 383 c.mu.Unlock() 384 } 385 c = parent 386 // Remember to unlock c.mu when we no longer need it, either 387 // because we went up another nesting level, or because we 388 // returned. 389 shouldUnlock = true 390 c.mu.Lock() 391 continue 392 } 393 return prevFrame 394 } 395 if _, ok := c.helpers[frame.Function]; !ok { 396 // Found a frame that wasn't inside a helper function. 397 return frame 398 } 399 } 400 return firstFrame 401 } 402 403 // decorate prefixes the string with the file and line of the call site 404 // and inserts the final newline if needed and indentation spaces for formatting. 405 // This function must be called with c.mu held. 406 func (c *common) decorate(s string, skip int) string { 407 frame := c.frameSkip(skip) 408 file := frame.File 409 line := frame.Line 410 if file != "" { 411 // Truncate file name at last file name separator. 412 if index := strings.LastIndex(file, "/"); index >= 0 { 413 file = file[index+1:] 414 } else if index = strings.LastIndex(file, "\\"); index >= 0 { 415 file = file[index+1:] 416 } 417 } else { 418 file = "???" 419 } 420 if line == 0 { 421 line = 1 422 } 423 buf := new(strings.Builder) 424 // Every line is indented at least 4 spaces. 425 buf.WriteString(" ") 426 fmt.Fprintf(buf, "%s:%d: ", file, line) 427 lines := strings.Split(s, "\n") 428 if l := len(lines); l > 1 && lines[l-1] == "" { 429 lines = lines[:l-1] 430 } 431 for i, line := range lines { 432 if i > 0 { 433 // Second and subsequent lines are indented an additional 4 spaces. 434 buf.WriteString("\n ") 435 } 436 buf.WriteString(line) 437 } 438 buf.WriteByte('\n') 439 return buf.String() 440 } 441 442 // flushToParent writes c.output to the parent after first writing the header 443 // with the given format and arguments. 444 func (c *common) flushToParent(format string, args ...interface{}) { 445 p := c.parent 446 p.mu.Lock() 447 defer p.mu.Unlock() 448 449 fmt.Fprintf(p.w, format, args...) 450 451 c.mu.Lock() 452 defer c.mu.Unlock() 453 io.Copy(p.w, bytes.NewReader(c.output)) 454 c.output = c.output[:0] 455 } 456 457 type indenter struct { 458 c *common 459 } 460 461 func (w indenter) Write(b []byte) (n int, err error) { 462 n = len(b) 463 for len(b) > 0 { 464 end := bytes.IndexByte(b, '\n') 465 if end == -1 { 466 end = len(b) 467 } else { 468 end++ 469 } 470 // An indent of 4 spaces will neatly align the dashes with the status 471 // indicator of the parent. 472 const indent = " " 473 w.c.output = append(w.c.output, indent...) 474 w.c.output = append(w.c.output, b[:end]...) 475 b = b[end:] 476 } 477 return 478 } 479 480 // fmtDuration returns a string representing d in the form "87.00s". 481 func fmtDuration(d time.Duration) string { 482 return fmt.Sprintf("%.2fs", d.Seconds()) 483 } 484 485 // TB is the interface common to T and B. 486 type TB interface { 487 Error(args ...interface{}) 488 Errorf(format string, args ...interface{}) 489 Fail() 490 FailNow() 491 Failed() bool 492 Fatal(args ...interface{}) 493 Fatalf(format string, args ...interface{}) 494 Log(args ...interface{}) 495 Logf(format string, args ...interface{}) 496 Name() string 497 Skip(args ...interface{}) 498 SkipNow() 499 Skipf(format string, args ...interface{}) 500 Skipped() bool 501 Helper() 502 503 // A private method to prevent users implementing the 504 // interface and so future additions to it will not 505 // violate Go 1 compatibility. 506 private() 507 } 508 509 var _ TB = (*T)(nil) 510 var _ TB = (*B)(nil) 511 512 // T is a type passed to Test functions to manage test state and support formatted test logs. 513 // Logs are accumulated during execution and dumped to standard output when done. 514 // 515 // A test ends when its Test function returns or calls any of the methods 516 // FailNow, Fatal, Fatalf, SkipNow, Skip, or Skipf. Those methods, as well as 517 // the Parallel method, must be called only from the goroutine running the 518 // Test function. 519 // 520 // The other reporting methods, such as the variations of Log and Error, 521 // may be called simultaneously from multiple goroutines. 522 type T struct { 523 common 524 isParallel bool 525 context *testContext // For running tests and subtests. 526 } 527 528 func (c *common) private() {} 529 530 // Name returns the name of the running test or benchmark. 531 func (c *common) Name() string { 532 return c.name 533 } 534 535 func (c *common) setRan() { 536 if c.parent != nil { 537 c.parent.setRan() 538 } 539 c.mu.Lock() 540 defer c.mu.Unlock() 541 c.ran = true 542 } 543 544 // Fail marks the function as having failed but continues execution. 545 func (c *common) Fail() { 546 if c.parent != nil { 547 c.parent.Fail() 548 } 549 c.mu.Lock() 550 defer c.mu.Unlock() 551 // c.done needs to be locked to synchronize checks to c.done in parent tests. 552 if c.done { 553 panic("Fail in goroutine after " + c.name + " has completed") 554 } 555 c.failed = true 556 } 557 558 // Failed reports whether the function has failed. 559 func (c *common) Failed() bool { 560 c.mu.RLock() 561 failed := c.failed 562 c.mu.RUnlock() 563 return failed || c.raceErrors+race.Errors() > 0 564 } 565 566 // FailNow marks the function as having failed and stops its execution 567 // by calling runtime.Goexit (which then runs all deferred calls in the 568 // current goroutine). 569 // Execution will continue at the next test or benchmark. 570 // FailNow must be called from the goroutine running the 571 // test or benchmark function, not from other goroutines 572 // created during the test. Calling FailNow does not stop 573 // those other goroutines. 574 func (c *common) FailNow() { 575 c.Fail() 576 577 // Calling runtime.Goexit will exit the goroutine, which 578 // will run the deferred functions in this goroutine, 579 // which will eventually run the deferred lines in tRunner, 580 // which will signal to the test loop that this test is done. 581 // 582 // A previous version of this code said: 583 // 584 // c.duration = ... 585 // c.signal <- c.self 586 // runtime.Goexit() 587 // 588 // This previous version duplicated code (those lines are in 589 // tRunner no matter what), but worse the goroutine teardown 590 // implicit in runtime.Goexit was not guaranteed to complete 591 // before the test exited. If a test deferred an important cleanup 592 // function (like removing temporary files), there was no guarantee 593 // it would run on a test failure. Because we send on c.signal during 594 // a top-of-stack deferred function now, we know that the send 595 // only happens after any other stacked defers have completed. 596 c.finished = true 597 runtime.Goexit() 598 } 599 600 // log generates the output. It's always at the same stack depth. 601 func (c *common) log(s string) { 602 c.logDepth(s, 3) // logDepth + log + public function 603 } 604 605 // logDepth generates the output. At an arbitary stack depth 606 func (c *common) logDepth(s string, depth int) { 607 c.mu.Lock() 608 defer c.mu.Unlock() 609 // If this test has already finished try and log this message with our parent 610 // with this test name tagged so we know where it came from. 611 // If we don't have a parent panic. 612 if c.done { 613 if c.parent != nil { 614 c.parent.logDepth(s, depth+1) 615 } else { 616 panic("Log in goroutine after " + c.name + " has completed") 617 } 618 } else { 619 c.output = append(c.output, c.decorate(s, depth+1)...) 620 } 621 } 622 623 // Log formats its arguments using default formatting, analogous to Println, 624 // and records the text in the error log. For tests, the text will be printed only if 625 // the test fails or the -test.v flag is set. For benchmarks, the text is always 626 // printed to avoid having performance depend on the value of the -test.v flag. 627 func (c *common) Log(args ...interface{}) { c.log(fmt.Sprintln(args...)) } 628 629 // Logf formats its arguments according to the format, analogous to Printf, and 630 // records the text in the error log. A final newline is added if not provided. For 631 // tests, the text will be printed only if the test fails or the -test.v flag is 632 // set. For benchmarks, the text is always printed to avoid having performance 633 // depend on the value of the -test.v flag. 634 func (c *common) Logf(format string, args ...interface{}) { c.log(fmt.Sprintf(format, args...)) } 635 636 // Error is equivalent to Log followed by Fail. 637 func (c *common) Error(args ...interface{}) { 638 c.log(fmt.Sprintln(args...)) 639 c.Fail() 640 } 641 642 // Errorf is equivalent to Logf followed by Fail. 643 func (c *common) Errorf(format string, args ...interface{}) { 644 c.log(fmt.Sprintf(format, args...)) 645 c.Fail() 646 } 647 648 // Fatal is equivalent to Log followed by FailNow. 649 func (c *common) Fatal(args ...interface{}) { 650 c.log(fmt.Sprintln(args...)) 651 c.FailNow() 652 } 653 654 // Fatalf is equivalent to Logf followed by FailNow. 655 func (c *common) Fatalf(format string, args ...interface{}) { 656 c.log(fmt.Sprintf(format, args...)) 657 c.FailNow() 658 } 659 660 // Skip is equivalent to Log followed by SkipNow. 661 func (c *common) Skip(args ...interface{}) { 662 c.log(fmt.Sprintln(args...)) 663 c.SkipNow() 664 } 665 666 // Skipf is equivalent to Logf followed by SkipNow. 667 func (c *common) Skipf(format string, args ...interface{}) { 668 c.log(fmt.Sprintf(format, args...)) 669 c.SkipNow() 670 } 671 672 // SkipNow marks the test as having been skipped and stops its execution 673 // by calling runtime.Goexit. 674 // If a test fails (see Error, Errorf, Fail) and is then skipped, 675 // it is still considered to have failed. 676 // Execution will continue at the next test or benchmark. See also FailNow. 677 // SkipNow must be called from the goroutine running the test, not from 678 // other goroutines created during the test. Calling SkipNow does not stop 679 // those other goroutines. 680 func (c *common) SkipNow() { 681 c.skip() 682 c.finished = true 683 runtime.Goexit() 684 } 685 686 func (c *common) skip() { 687 c.mu.Lock() 688 defer c.mu.Unlock() 689 c.skipped = true 690 } 691 692 // Skipped reports whether the test was skipped. 693 func (c *common) Skipped() bool { 694 c.mu.RLock() 695 defer c.mu.RUnlock() 696 return c.skipped 697 } 698 699 // Helper marks the calling function as a test helper function. 700 // When printing file and line information, that function will be skipped. 701 // Helper may be called simultaneously from multiple goroutines. 702 func (c *common) Helper() { 703 c.mu.Lock() 704 defer c.mu.Unlock() 705 if c.helpers == nil { 706 c.helpers = make(map[string]struct{}) 707 } 708 c.helpers[callerName(1)] = struct{}{} 709 } 710 711 // callerName gives the function name (qualified with a package path) 712 // for the caller after skip frames (where 0 means the current function). 713 func callerName(skip int) string { 714 // Make room for the skip PC. 715 var pc [2]uintptr 716 n := runtime.Callers(skip+2, pc[:]) // skip + runtime.Callers + callerName 717 if n == 0 { 718 panic("testing: zero callers found") 719 } 720 frames := runtime.CallersFrames(pc[:n]) 721 frame, _ := frames.Next() 722 return frame.Function 723 } 724 725 // Parallel signals that this test is to be run in parallel with (and only with) 726 // other parallel tests. When a test is run multiple times due to use of 727 // -test.count or -test.cpu, multiple instances of a single test never run in 728 // parallel with each other. 729 func (t *T) Parallel() { 730 if t.isParallel { 731 panic("testing: t.Parallel called multiple times") 732 } 733 t.isParallel = true 734 735 // We don't want to include the time we spend waiting for serial tests 736 // in the test duration. Record the elapsed time thus far and reset the 737 // timer afterwards. 738 t.duration += time.Since(t.start) 739 740 // Add to the list of tests to be released by the parent. 741 t.parent.sub = append(t.parent.sub, t) 742 t.raceErrors += race.Errors() 743 744 if t.chatty { 745 // Print directly to root's io.Writer so there is no delay. 746 root := t.parent 747 for ; root.parent != nil; root = root.parent { 748 } 749 root.mu.Lock() 750 fmt.Fprintf(root.w, "=== PAUSE %s\n", t.name) 751 root.mu.Unlock() 752 } 753 754 t.signal <- true // Release calling test. 755 <-t.parent.barrier // Wait for the parent test to complete. 756 t.context.waitParallel() 757 758 if t.chatty { 759 // Print directly to root's io.Writer so there is no delay. 760 root := t.parent 761 for ; root.parent != nil; root = root.parent { 762 } 763 root.mu.Lock() 764 fmt.Fprintf(root.w, "=== CONT %s\n", t.name) 765 root.mu.Unlock() 766 } 767 768 t.start = time.Now() 769 t.raceErrors += -race.Errors() 770 } 771 772 // An internal type but exported because it is cross-package; part of the implementation 773 // of the "go test" command. 774 type InternalTest struct { 775 Name string 776 F func(*T) 777 } 778 779 var errNilPanicOrGoexit = errors.New("test executed panic(nil) or runtime.Goexit") 780 781 func tRunner(t *T, fn func(t *T)) { 782 t.runner = callerName(0) 783 784 // When this goroutine is done, either because fn(t) 785 // returned normally or because a test failure triggered 786 // a call to runtime.Goexit, record the duration and send 787 // a signal saying that the test is done. 788 defer func() { 789 if t.Failed() { 790 atomic.AddUint32(&numFailed, 1) 791 } 792 793 if t.raceErrors+race.Errors() > 0 { 794 t.Errorf("race detected during execution of test") 795 } 796 797 t.duration += time.Since(t.start) 798 // If the test panicked, print any test output before dying. 799 err := recover() 800 signal := true 801 if !t.finished && err == nil { 802 err = errNilPanicOrGoexit 803 for p := t.parent; p != nil; p = p.parent { 804 if p.finished { 805 t.Errorf("%v: subtest may have called FailNow on a parent test", err) 806 err = nil 807 signal = false 808 break 809 } 810 } 811 } 812 if err != nil { 813 t.Fail() 814 t.report() 815 panic(err) 816 } 817 818 if len(t.sub) > 0 { 819 // Run parallel subtests. 820 // Decrease the running count for this test. 821 t.context.release() 822 // Release the parallel subtests. 823 close(t.barrier) 824 // Wait for subtests to complete. 825 for _, sub := range t.sub { 826 <-sub.signal 827 } 828 if !t.isParallel { 829 // Reacquire the count for sequential tests. See comment in Run. 830 t.context.waitParallel() 831 } 832 } else if t.isParallel { 833 // Only release the count for this test if it was run as a parallel 834 // test. See comment in Run method. 835 t.context.release() 836 } 837 t.report() // Report after all subtests have finished. 838 839 // Do not lock t.done to allow race detector to detect race in case 840 // the user does not appropriately synchronizes a goroutine. 841 t.done = true 842 if t.parent != nil && atomic.LoadInt32(&t.hasSub) == 0 { 843 t.setRan() 844 } 845 t.signal <- signal 846 }() 847 848 t.start = time.Now() 849 t.raceErrors = -race.Errors() 850 fn(t) 851 852 // code beyond here will not be executed when FailNow is invoked 853 t.finished = true 854 } 855 856 // Run runs f as a subtest of t called name. It runs f in a separate goroutine 857 // and blocks until f returns or calls t.Parallel to become a parallel test. 858 // Run reports whether f succeeded (or at least did not fail before calling t.Parallel). 859 // 860 // Run may be called simultaneously from multiple goroutines, but all such calls 861 // must return before the outer test function for t returns. 862 func (t *T) Run(name string, f func(t *T)) bool { 863 atomic.StoreInt32(&t.hasSub, 1) 864 testName, ok, _ := t.context.match.fullName(&t.common, name) 865 if !ok || shouldFailFast() { 866 return true 867 } 868 // Record the stack trace at the point of this call so that if the subtest 869 // function - which runs in a separate stack - is marked as a helper, we can 870 // continue walking the stack into the parent test. 871 var pc [maxStackLen]uintptr 872 n := runtime.Callers(2, pc[:]) 873 t = &T{ 874 common: common{ 875 barrier: make(chan bool), 876 signal: make(chan bool), 877 name: testName, 878 parent: &t.common, 879 level: t.level + 1, 880 creator: pc[:n], 881 chatty: t.chatty, 882 }, 883 context: t.context, 884 } 885 t.w = indenter{&t.common} 886 887 if t.chatty { 888 // Print directly to root's io.Writer so there is no delay. 889 root := t.parent 890 for ; root.parent != nil; root = root.parent { 891 } 892 root.mu.Lock() 893 fmt.Fprintf(root.w, "=== RUN %s\n", t.name) 894 root.mu.Unlock() 895 } 896 // Instead of reducing the running count of this test before calling the 897 // tRunner and increasing it afterwards, we rely on tRunner keeping the 898 // count correct. This ensures that a sequence of sequential tests runs 899 // without being preempted, even when their parent is a parallel test. This 900 // may especially reduce surprises if *parallel == 1. 901 go tRunner(t, f) 902 if !<-t.signal { 903 // At this point, it is likely that FailNow was called on one of the 904 // parent tests by one of the subtests. Continue aborting up the chain. 905 runtime.Goexit() 906 } 907 return !t.failed 908 } 909 910 // testContext holds all fields that are common to all tests. This includes 911 // synchronization primitives to run at most *parallel tests. 912 type testContext struct { 913 match *matcher 914 915 mu sync.Mutex 916 917 // Channel used to signal tests that are ready to be run in parallel. 918 startParallel chan bool 919 920 // running is the number of tests currently running in parallel. 921 // This does not include tests that are waiting for subtests to complete. 922 running int 923 924 // numWaiting is the number tests waiting to be run in parallel. 925 numWaiting int 926 927 // maxParallel is a copy of the parallel flag. 928 maxParallel int 929 } 930 931 func newTestContext(maxParallel int, m *matcher) *testContext { 932 return &testContext{ 933 match: m, 934 startParallel: make(chan bool), 935 maxParallel: maxParallel, 936 running: 1, // Set the count to 1 for the main (sequential) test. 937 } 938 } 939 940 func (c *testContext) waitParallel() { 941 c.mu.Lock() 942 if c.running < c.maxParallel { 943 c.running++ 944 c.mu.Unlock() 945 return 946 } 947 c.numWaiting++ 948 c.mu.Unlock() 949 <-c.startParallel 950 } 951 952 func (c *testContext) release() { 953 c.mu.Lock() 954 if c.numWaiting == 0 { 955 c.running-- 956 c.mu.Unlock() 957 return 958 } 959 c.numWaiting-- 960 c.mu.Unlock() 961 c.startParallel <- true // Pick a waiting test to be run. 962 } 963 964 // No one should be using func Main anymore. 965 // See the doc comment on func Main and use MainStart instead. 966 var errMain = errors.New("testing: unexpected use of func Main") 967 968 type matchStringOnly func(pat, str string) (bool, error) 969 970 func (f matchStringOnly) MatchString(pat, str string) (bool, error) { return f(pat, str) } 971 func (f matchStringOnly) StartCPUProfile(w io.Writer) error { return errMain } 972 func (f matchStringOnly) StopCPUProfile() {} 973 func (f matchStringOnly) WriteProfileTo(string, io.Writer, int) error { return errMain } 974 func (f matchStringOnly) ImportPath() string { return "" } 975 func (f matchStringOnly) StartTestLog(io.Writer) {} 976 func (f matchStringOnly) StopTestLog() error { return errMain } 977 978 // Main is an internal function, part of the implementation of the "go test" command. 979 // It was exported because it is cross-package and predates "internal" packages. 980 // It is no longer used by "go test" but preserved, as much as possible, for other 981 // systems that simulate "go test" using Main, but Main sometimes cannot be updated as 982 // new functionality is added to the testing package. 983 // Systems simulating "go test" should be updated to use MainStart. 984 func Main(matchString func(pat, str string) (bool, error), tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample) { 985 os.Exit(MainStart(matchStringOnly(matchString), tests, benchmarks, examples).Run()) 986 } 987 988 // M is a type passed to a TestMain function to run the actual tests. 989 type M struct { 990 deps testDeps 991 tests []InternalTest 992 benchmarks []InternalBenchmark 993 examples []InternalExample 994 995 timer *time.Timer 996 afterOnce sync.Once 997 998 numRun int 999 } 1000 1001 // testDeps is an internal interface of functionality that is 1002 // passed into this package by a test's generated main package. 1003 // The canonical implementation of this interface is 1004 // testing/internal/testdeps's TestDeps. 1005 type testDeps interface { 1006 ImportPath() string 1007 MatchString(pat, str string) (bool, error) 1008 StartCPUProfile(io.Writer) error 1009 StopCPUProfile() 1010 StartTestLog(io.Writer) 1011 StopTestLog() error 1012 WriteProfileTo(string, io.Writer, int) error 1013 } 1014 1015 // MainStart is meant for use by tests generated by 'go test'. 1016 // It is not meant to be called directly and is not subject to the Go 1 compatibility document. 1017 // It may change signature from release to release. 1018 func MainStart(deps testDeps, tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample) *M { 1019 return &M{ 1020 deps: deps, 1021 tests: tests, 1022 benchmarks: benchmarks, 1023 examples: examples, 1024 } 1025 } 1026 1027 // Run runs the tests. It returns an exit code to pass to os.Exit. 1028 func (m *M) Run() int { 1029 // Count the number of calls to m.Run. 1030 // We only ever expected 1, but we didn't enforce that, 1031 // and now there are tests in the wild that call m.Run multiple times. 1032 // Sigh. golang.org/issue/23129. 1033 m.numRun++ 1034 1035 // TestMain may have already called flag.Parse. 1036 if !flag.Parsed() { 1037 flag.Parse() 1038 } 1039 1040 if *parallel < 1 { 1041 fmt.Fprintln(os.Stderr, "testing: -parallel can only be given a positive integer") 1042 flag.Usage() 1043 return 2 1044 } 1045 1046 if len(*matchList) != 0 { 1047 listTests(m.deps.MatchString, m.tests, m.benchmarks, m.examples) 1048 return 0 1049 } 1050 1051 parseCpuList() 1052 1053 m.before() 1054 defer m.after() 1055 m.startAlarm() 1056 haveExamples = len(m.examples) > 0 1057 testRan, testOk := runTests(m.deps.MatchString, m.tests) 1058 exampleRan, exampleOk := runExamples(m.deps.MatchString, m.examples) 1059 m.stopAlarm() 1060 if !testRan && !exampleRan && *matchBenchmarks == "" { 1061 fmt.Fprintln(os.Stderr, "testing: warning: no tests to run") 1062 } 1063 if !testOk || !exampleOk || !runBenchmarks(m.deps.ImportPath(), m.deps.MatchString, m.benchmarks) || race.Errors() > 0 { 1064 fmt.Println("FAIL") 1065 return 1 1066 } 1067 1068 fmt.Println("PASS") 1069 return 0 1070 } 1071 1072 func (t *T) report() { 1073 if t.parent == nil { 1074 return 1075 } 1076 dstr := fmtDuration(t.duration) 1077 format := "--- %s: %s (%s)\n" 1078 if t.Failed() { 1079 t.flushToParent(format, "FAIL", t.name, dstr) 1080 } else if t.chatty { 1081 if t.Skipped() { 1082 t.flushToParent(format, "SKIP", t.name, dstr) 1083 } else { 1084 t.flushToParent(format, "PASS", t.name, dstr) 1085 } 1086 } 1087 } 1088 1089 func listTests(matchString func(pat, str string) (bool, error), tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample) { 1090 if _, err := matchString(*matchList, "non-empty"); err != nil { 1091 fmt.Fprintf(os.Stderr, "testing: invalid regexp in -test.list (%q): %s\n", *matchList, err) 1092 os.Exit(1) 1093 } 1094 1095 for _, test := range tests { 1096 if ok, _ := matchString(*matchList, test.Name); ok { 1097 fmt.Println(test.Name) 1098 } 1099 } 1100 for _, bench := range benchmarks { 1101 if ok, _ := matchString(*matchList, bench.Name); ok { 1102 fmt.Println(bench.Name) 1103 } 1104 } 1105 for _, example := range examples { 1106 if ok, _ := matchString(*matchList, example.Name); ok { 1107 fmt.Println(example.Name) 1108 } 1109 } 1110 } 1111 1112 // An internal function but exported because it is cross-package; part of the implementation 1113 // of the "go test" command. 1114 func RunTests(matchString func(pat, str string) (bool, error), tests []InternalTest) (ok bool) { 1115 ran, ok := runTests(matchString, tests) 1116 if !ran && !haveExamples { 1117 fmt.Fprintln(os.Stderr, "testing: warning: no tests to run") 1118 } 1119 return ok 1120 } 1121 1122 func runTests(matchString func(pat, str string) (bool, error), tests []InternalTest) (ran, ok bool) { 1123 ok = true 1124 for _, procs := range cpuList { 1125 runtime.GOMAXPROCS(procs) 1126 for i := uint(0); i < *count; i++ { 1127 if shouldFailFast() { 1128 break 1129 } 1130 ctx := newTestContext(*parallel, newMatcher(matchString, *match, "-test.run")) 1131 t := &T{ 1132 common: common{ 1133 signal: make(chan bool), 1134 barrier: make(chan bool), 1135 w: os.Stdout, 1136 chatty: *chatty, 1137 }, 1138 context: ctx, 1139 } 1140 tRunner(t, func(t *T) { 1141 for _, test := range tests { 1142 t.Run(test.Name, test.F) 1143 } 1144 // Run catching the signal rather than the tRunner as a separate 1145 // goroutine to avoid adding a goroutine during the sequential 1146 // phase as this pollutes the stacktrace output when aborting. 1147 go func() { <-t.signal }() 1148 }) 1149 ok = ok && !t.Failed() 1150 ran = ran || t.ran 1151 } 1152 } 1153 return ran, ok 1154 } 1155 1156 // before runs before all testing. 1157 func (m *M) before() { 1158 if *memProfileRate > 0 { 1159 runtime.MemProfileRate = *memProfileRate 1160 } 1161 if *cpuProfile != "" { 1162 f, err := os.Create(toOutputDir(*cpuProfile)) 1163 if err != nil { 1164 fmt.Fprintf(os.Stderr, "testing: %s\n", err) 1165 return 1166 } 1167 if err := m.deps.StartCPUProfile(f); err != nil { 1168 fmt.Fprintf(os.Stderr, "testing: can't start cpu profile: %s\n", err) 1169 f.Close() 1170 return 1171 } 1172 // Could save f so after can call f.Close; not worth the effort. 1173 } 1174 if *traceFile != "" { 1175 f, err := os.Create(toOutputDir(*traceFile)) 1176 if err != nil { 1177 fmt.Fprintf(os.Stderr, "testing: %s\n", err) 1178 return 1179 } 1180 if err := trace.Start(f); err != nil { 1181 fmt.Fprintf(os.Stderr, "testing: can't start tracing: %s\n", err) 1182 f.Close() 1183 return 1184 } 1185 // Could save f so after can call f.Close; not worth the effort. 1186 } 1187 if *blockProfile != "" && *blockProfileRate >= 0 { 1188 runtime.SetBlockProfileRate(*blockProfileRate) 1189 } 1190 if *mutexProfile != "" && *mutexProfileFraction >= 0 { 1191 runtime.SetMutexProfileFraction(*mutexProfileFraction) 1192 } 1193 if *coverProfile != "" && cover.Mode == "" { 1194 fmt.Fprintf(os.Stderr, "testing: cannot use -test.coverprofile because test binary was not built with coverage enabled\n") 1195 os.Exit(2) 1196 } 1197 if *testlog != "" { 1198 // Note: Not using toOutputDir. 1199 // This file is for use by cmd/go, not users. 1200 var f *os.File 1201 var err error 1202 if m.numRun == 1 { 1203 f, err = os.Create(*testlog) 1204 } else { 1205 f, err = os.OpenFile(*testlog, os.O_WRONLY, 0) 1206 if err == nil { 1207 f.Seek(0, io.SeekEnd) 1208 } 1209 } 1210 if err != nil { 1211 fmt.Fprintf(os.Stderr, "testing: %s\n", err) 1212 os.Exit(2) 1213 } 1214 m.deps.StartTestLog(f) 1215 testlogFile = f 1216 } 1217 } 1218 1219 // after runs after all testing. 1220 func (m *M) after() { 1221 m.afterOnce.Do(func() { 1222 m.writeProfiles() 1223 }) 1224 } 1225 1226 func (m *M) writeProfiles() { 1227 if *testlog != "" { 1228 if err := m.deps.StopTestLog(); err != nil { 1229 fmt.Fprintf(os.Stderr, "testing: can't write %s: %s\n", *testlog, err) 1230 os.Exit(2) 1231 } 1232 if err := testlogFile.Close(); err != nil { 1233 fmt.Fprintf(os.Stderr, "testing: can't write %s: %s\n", *testlog, err) 1234 os.Exit(2) 1235 } 1236 } 1237 if *cpuProfile != "" { 1238 m.deps.StopCPUProfile() // flushes profile to disk 1239 } 1240 if *traceFile != "" { 1241 trace.Stop() // flushes trace to disk 1242 } 1243 if *memProfile != "" { 1244 f, err := os.Create(toOutputDir(*memProfile)) 1245 if err != nil { 1246 fmt.Fprintf(os.Stderr, "testing: %s\n", err) 1247 os.Exit(2) 1248 } 1249 runtime.GC() // materialize all statistics 1250 if err = m.deps.WriteProfileTo("allocs", f, 0); err != nil { 1251 fmt.Fprintf(os.Stderr, "testing: can't write %s: %s\n", *memProfile, err) 1252 os.Exit(2) 1253 } 1254 f.Close() 1255 } 1256 if *blockProfile != "" && *blockProfileRate >= 0 { 1257 f, err := os.Create(toOutputDir(*blockProfile)) 1258 if err != nil { 1259 fmt.Fprintf(os.Stderr, "testing: %s\n", err) 1260 os.Exit(2) 1261 } 1262 if err = m.deps.WriteProfileTo("block", f, 0); err != nil { 1263 fmt.Fprintf(os.Stderr, "testing: can't write %s: %s\n", *blockProfile, err) 1264 os.Exit(2) 1265 } 1266 f.Close() 1267 } 1268 if *mutexProfile != "" && *mutexProfileFraction >= 0 { 1269 f, err := os.Create(toOutputDir(*mutexProfile)) 1270 if err != nil { 1271 fmt.Fprintf(os.Stderr, "testing: %s\n", err) 1272 os.Exit(2) 1273 } 1274 if err = m.deps.WriteProfileTo("mutex", f, 0); err != nil { 1275 fmt.Fprintf(os.Stderr, "testing: can't write %s: %s\n", *blockProfile, err) 1276 os.Exit(2) 1277 } 1278 f.Close() 1279 } 1280 if cover.Mode != "" { 1281 coverReport() 1282 } 1283 } 1284 1285 // toOutputDir returns the file name relocated, if required, to outputDir. 1286 // Simple implementation to avoid pulling in path/filepath. 1287 func toOutputDir(path string) string { 1288 if *outputDir == "" || path == "" { 1289 return path 1290 } 1291 if runtime.GOOS == "windows" { 1292 // On Windows, it's clumsy, but we can be almost always correct 1293 // by just looking for a drive letter and a colon. 1294 // Absolute paths always have a drive letter (ignoring UNC). 1295 // Problem: if path == "C:A" and outputdir == "C:\Go" it's unclear 1296 // what to do, but even then path/filepath doesn't help. 1297 // TODO: Worth doing better? Probably not, because we're here only 1298 // under the management of go test. 1299 if len(path) >= 2 { 1300 letter, colon := path[0], path[1] 1301 if ('a' <= letter && letter <= 'z' || 'A' <= letter && letter <= 'Z') && colon == ':' { 1302 // If path starts with a drive letter we're stuck with it regardless. 1303 return path 1304 } 1305 } 1306 } 1307 if os.IsPathSeparator(path[0]) { 1308 return path 1309 } 1310 return fmt.Sprintf("%s%c%s", *outputDir, os.PathSeparator, path) 1311 } 1312 1313 // startAlarm starts an alarm if requested. 1314 func (m *M) startAlarm() { 1315 if *timeout > 0 { 1316 m.timer = time.AfterFunc(*timeout, func() { 1317 m.after() 1318 debug.SetTraceback("all") 1319 panic(fmt.Sprintf("test timed out after %v", *timeout)) 1320 }) 1321 } 1322 } 1323 1324 // stopAlarm turns off the alarm. 1325 func (m *M) stopAlarm() { 1326 if *timeout > 0 { 1327 m.timer.Stop() 1328 } 1329 } 1330 1331 func parseCpuList() { 1332 for _, val := range strings.Split(*cpuListStr, ",") { 1333 val = strings.TrimSpace(val) 1334 if val == "" { 1335 continue 1336 } 1337 cpu, err := strconv.Atoi(val) 1338 if err != nil || cpu <= 0 { 1339 fmt.Fprintf(os.Stderr, "testing: invalid value %q for -test.cpu\n", val) 1340 os.Exit(1) 1341 } 1342 cpuList = append(cpuList, cpu) 1343 } 1344 if cpuList == nil { 1345 cpuList = append(cpuList, runtime.GOMAXPROCS(-1)) 1346 } 1347 } 1348 1349 func shouldFailFast() bool { 1350 return *failFast && atomic.LoadUint32(&numFailed) > 0 1351 }