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