github.com/hongwozai/go-src-1.4.3@v0.0.0-20191127132709-dc3fce3dbccb/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 can be any alphanumeric string (but the first letter must not be in 10 // [a-z]) and 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 // http://golang.org/cmd/go/#hdr-Description_of_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 benchark 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 // Example functions without output comments are compiled but not executed. 99 // 100 // The naming convention to declare examples for the package, a function F, a type T and 101 // method M on type T are: 102 // 103 // func Example() { ... } 104 // func ExampleF() { ... } 105 // func ExampleT() { ... } 106 // func ExampleT_M() { ... } 107 // 108 // Multiple example functions for a package/type/function/method may be provided by 109 // appending a distinct suffix to the name. The suffix must start with a 110 // lower-case letter. 111 // 112 // func Example_suffix() { ... } 113 // func ExampleF_suffix() { ... } 114 // func ExampleT_suffix() { ... } 115 // func ExampleT_M_suffix() { ... } 116 // 117 // The entire test file is presented as the example when it contains a single 118 // example function, at least one other function, type, variable, or constant 119 // declaration, and no test or benchmark functions. 120 // 121 // Main 122 // 123 // It is sometimes necessary for a test program to do extra setup or teardown 124 // before or after testing. It is also sometimes necessary for a test to control 125 // which code runs on the main thread. To support these and other cases, 126 // if a test file contains a function: 127 // 128 // func TestMain(m *testing.M) 129 // 130 // then the generated test will call TestMain(m) instead of running the tests 131 // directly. TestMain runs in the main goroutine and can do whatever setup 132 // and teardown is necessary around a call to m.Run. It should then call 133 // os.Exit with the result of m.Run. 134 // 135 // The minimal implementation of TestMain is: 136 // 137 // func TestMain(m *testing.M) { os.Exit(m.Run()) } 138 // 139 // In effect, that is the implementation used when no TestMain is explicitly defined. 140 package testing 141 142 import ( 143 "bytes" 144 "flag" 145 "fmt" 146 "os" 147 "runtime" 148 "runtime/pprof" 149 "strconv" 150 "strings" 151 "sync" 152 "time" 153 ) 154 155 var ( 156 // The short flag requests that tests run more quickly, but its functionality 157 // is provided by test writers themselves. The testing package is just its 158 // home. The all.bash installation script sets it to make installation more 159 // efficient, but by default the flag is off so a plain "go test" will do a 160 // full test of the package. 161 short = flag.Bool("test.short", false, "run smaller test suite to save time") 162 163 // The directory in which to create profile files and the like. When run from 164 // "go test", the binary always runs in the source directory for the package; 165 // this flag lets "go test" tell the binary to write the files in the directory where 166 // the "go test" command is run. 167 outputDir = flag.String("test.outputdir", "", "directory in which to write profiles") 168 169 // Report as tests are run; default is silent for success. 170 chatty = flag.Bool("test.v", false, "verbose: print additional output") 171 coverProfile = flag.String("test.coverprofile", "", "write a coverage profile to the named file after execution") 172 match = flag.String("test.run", "", "regular expression to select tests and examples to run") 173 memProfile = flag.String("test.memprofile", "", "write a memory profile to the named file after execution") 174 memProfileRate = flag.Int("test.memprofilerate", 0, "if >=0, sets runtime.MemProfileRate") 175 cpuProfile = flag.String("test.cpuprofile", "", "write a cpu profile to the named file during execution") 176 blockProfile = flag.String("test.blockprofile", "", "write a goroutine blocking profile to the named file after execution") 177 blockProfileRate = flag.Int("test.blockprofilerate", 1, "if >= 0, calls runtime.SetBlockProfileRate()") 178 timeout = flag.Duration("test.timeout", 0, "if positive, sets an aggregate time limit for all tests") 179 cpuListStr = flag.String("test.cpu", "", "comma-separated list of number of CPUs to use for each test") 180 parallel = flag.Int("test.parallel", runtime.GOMAXPROCS(0), "maximum test parallelism") 181 182 haveExamples bool // are there examples? 183 184 cpuList []int 185 ) 186 187 // common holds the elements common between T and B and 188 // captures common methods such as Errorf. 189 type common struct { 190 mu sync.RWMutex // guards output and failed 191 output []byte // Output generated by test or benchmark. 192 failed bool // Test or benchmark has failed. 193 skipped bool // Test of benchmark has been skipped. 194 finished bool 195 196 start time.Time // Time test or benchmark started 197 duration time.Duration 198 self interface{} // To be sent on signal channel when done. 199 signal chan interface{} // Output for serial tests. 200 } 201 202 // Short reports whether the -test.short flag is set. 203 func Short() bool { 204 return *short 205 } 206 207 // Verbose reports whether the -test.v flag is set. 208 func Verbose() bool { 209 return *chatty 210 } 211 212 // decorate prefixes the string with the file and line of the call site 213 // and inserts the final newline if needed and indentation tabs for formatting. 214 func decorate(s string) string { 215 _, file, line, ok := runtime.Caller(3) // decorate + log + public function. 216 if ok { 217 // Truncate file name at last file name separator. 218 if index := strings.LastIndex(file, "/"); index >= 0 { 219 file = file[index+1:] 220 } else if index = strings.LastIndex(file, "\\"); index >= 0 { 221 file = file[index+1:] 222 } 223 } else { 224 file = "???" 225 line = 1 226 } 227 buf := new(bytes.Buffer) 228 // Every line is indented at least one tab. 229 buf.WriteByte('\t') 230 fmt.Fprintf(buf, "%s:%d: ", file, line) 231 lines := strings.Split(s, "\n") 232 if l := len(lines); l > 1 && lines[l-1] == "" { 233 lines = lines[:l-1] 234 } 235 for i, line := range lines { 236 if i > 0 { 237 // Second and subsequent lines are indented an extra tab. 238 buf.WriteString("\n\t\t") 239 } 240 buf.WriteString(line) 241 } 242 buf.WriteByte('\n') 243 return buf.String() 244 } 245 246 // fmtDuration returns a string representing d in the form "87.00s". 247 func fmtDuration(d time.Duration) string { 248 return fmt.Sprintf("%.2fs", d.Seconds()) 249 } 250 251 // TB is the interface common to T and B. 252 type TB interface { 253 Error(args ...interface{}) 254 Errorf(format string, args ...interface{}) 255 Fail() 256 FailNow() 257 Failed() bool 258 Fatal(args ...interface{}) 259 Fatalf(format string, args ...interface{}) 260 Log(args ...interface{}) 261 Logf(format string, args ...interface{}) 262 Skip(args ...interface{}) 263 SkipNow() 264 Skipf(format string, args ...interface{}) 265 Skipped() bool 266 267 // A private method to prevent users implementing the 268 // interface and so future additions to it will not 269 // violate Go 1 compatibility. 270 private() 271 } 272 273 var _ TB = (*T)(nil) 274 var _ TB = (*B)(nil) 275 276 // T is a type passed to Test functions to manage test state and support formatted test logs. 277 // Logs are accumulated during execution and dumped to standard error when done. 278 type T struct { 279 common 280 name string // Name of test. 281 startParallel chan bool // Parallel tests will wait on this. 282 } 283 284 func (c *common) private() {} 285 286 // Fail marks the function as having failed but continues execution. 287 func (c *common) Fail() { 288 c.mu.Lock() 289 defer c.mu.Unlock() 290 c.failed = true 291 } 292 293 // Failed reports whether the function has failed. 294 func (c *common) Failed() bool { 295 c.mu.RLock() 296 defer c.mu.RUnlock() 297 return c.failed 298 } 299 300 // FailNow marks the function as having failed and stops its execution. 301 // Execution will continue at the next test or benchmark. 302 // FailNow must be called from the goroutine running the 303 // test or benchmark function, not from other goroutines 304 // created during the test. Calling FailNow does not stop 305 // those other goroutines. 306 func (c *common) FailNow() { 307 c.Fail() 308 309 // Calling runtime.Goexit will exit the goroutine, which 310 // will run the deferred functions in this goroutine, 311 // which will eventually run the deferred lines in tRunner, 312 // which will signal to the test loop that this test is done. 313 // 314 // A previous version of this code said: 315 // 316 // c.duration = ... 317 // c.signal <- c.self 318 // runtime.Goexit() 319 // 320 // This previous version duplicated code (those lines are in 321 // tRunner no matter what), but worse the goroutine teardown 322 // implicit in runtime.Goexit was not guaranteed to complete 323 // before the test exited. If a test deferred an important cleanup 324 // function (like removing temporary files), there was no guarantee 325 // it would run on a test failure. Because we send on c.signal during 326 // a top-of-stack deferred function now, we know that the send 327 // only happens after any other stacked defers have completed. 328 c.finished = true 329 runtime.Goexit() 330 } 331 332 // log generates the output. It's always at the same stack depth. 333 func (c *common) log(s string) { 334 c.mu.Lock() 335 defer c.mu.Unlock() 336 c.output = append(c.output, decorate(s)...) 337 } 338 339 // Log formats its arguments using default formatting, analogous to Println, 340 // and records the text in the error log. The text will be printed only if 341 // the test fails or the -test.v flag is set. 342 func (c *common) Log(args ...interface{}) { c.log(fmt.Sprintln(args...)) } 343 344 // Logf formats its arguments according to the format, analogous to Printf, 345 // and records the text in the error log. The text will be printed only if 346 // the test fails or the -test.v flag is set. 347 func (c *common) Logf(format string, args ...interface{}) { c.log(fmt.Sprintf(format, args...)) } 348 349 // Error is equivalent to Log followed by Fail. 350 func (c *common) Error(args ...interface{}) { 351 c.log(fmt.Sprintln(args...)) 352 c.Fail() 353 } 354 355 // Errorf is equivalent to Logf followed by Fail. 356 func (c *common) Errorf(format string, args ...interface{}) { 357 c.log(fmt.Sprintf(format, args...)) 358 c.Fail() 359 } 360 361 // Fatal is equivalent to Log followed by FailNow. 362 func (c *common) Fatal(args ...interface{}) { 363 c.log(fmt.Sprintln(args...)) 364 c.FailNow() 365 } 366 367 // Fatalf is equivalent to Logf followed by FailNow. 368 func (c *common) Fatalf(format string, args ...interface{}) { 369 c.log(fmt.Sprintf(format, args...)) 370 c.FailNow() 371 } 372 373 // Skip is equivalent to Log followed by SkipNow. 374 func (c *common) Skip(args ...interface{}) { 375 c.log(fmt.Sprintln(args...)) 376 c.SkipNow() 377 } 378 379 // Skipf is equivalent to Logf followed by SkipNow. 380 func (c *common) Skipf(format string, args ...interface{}) { 381 c.log(fmt.Sprintf(format, args...)) 382 c.SkipNow() 383 } 384 385 // SkipNow marks the test as having been skipped and stops its execution. 386 // Execution will continue at the next test or benchmark. See also FailNow. 387 // SkipNow must be called from the goroutine running the test, not from 388 // other goroutines created during the test. Calling SkipNow does not stop 389 // those other goroutines. 390 func (c *common) SkipNow() { 391 c.skip() 392 c.finished = true 393 runtime.Goexit() 394 } 395 396 func (c *common) skip() { 397 c.mu.Lock() 398 defer c.mu.Unlock() 399 c.skipped = true 400 } 401 402 // Skipped reports whether the test was skipped. 403 func (c *common) Skipped() bool { 404 c.mu.RLock() 405 defer c.mu.RUnlock() 406 return c.skipped 407 } 408 409 // Parallel signals that this test is to be run in parallel with (and only with) 410 // other parallel tests. 411 func (t *T) Parallel() { 412 t.signal <- (*T)(nil) // Release main testing loop 413 <-t.startParallel // Wait for serial tests to finish 414 // Assuming Parallel is the first thing a test does, which is reasonable, 415 // reinitialize the test's start time because it's actually starting now. 416 t.start = time.Now() 417 } 418 419 // An internal type but exported because it is cross-package; part of the implementation 420 // of the "go test" command. 421 type InternalTest struct { 422 Name string 423 F func(*T) 424 } 425 426 func tRunner(t *T, test *InternalTest) { 427 // When this goroutine is done, either because test.F(t) 428 // returned normally or because a test failure triggered 429 // a call to runtime.Goexit, record the duration and send 430 // a signal saying that the test is done. 431 defer func() { 432 t.duration = time.Now().Sub(t.start) 433 // If the test panicked, print any test output before dying. 434 err := recover() 435 if !t.finished && err == nil { 436 err = fmt.Errorf("test executed panic(nil) or runtime.Goexit") 437 } 438 if err != nil { 439 t.Fail() 440 t.report() 441 panic(err) 442 } 443 t.signal <- t 444 }() 445 446 t.start = time.Now() 447 test.F(t) 448 t.finished = true 449 } 450 451 // An internal function but exported because it is cross-package; part of the implementation 452 // of the "go test" command. 453 func Main(matchString func(pat, str string) (bool, error), tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample) { 454 os.Exit(MainStart(matchString, tests, benchmarks, examples).Run()) 455 } 456 457 // M is a type passed to a TestMain function to run the actual tests. 458 type M struct { 459 matchString func(pat, str string) (bool, error) 460 tests []InternalTest 461 benchmarks []InternalBenchmark 462 examples []InternalExample 463 } 464 465 // MainStart is meant for use by tests generated by 'go test'. 466 // It is not meant to be called directly and is not subject to the Go 1 compatibility document. 467 // It may change signature from release to release. 468 func MainStart(matchString func(pat, str string) (bool, error), tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample) *M { 469 return &M{ 470 matchString: matchString, 471 tests: tests, 472 benchmarks: benchmarks, 473 examples: examples, 474 } 475 } 476 477 // Run runs the tests. It returns an exit code to pass to os.Exit. 478 func (m *M) Run() int { 479 flag.Parse() 480 parseCpuList() 481 482 before() 483 startAlarm() 484 haveExamples = len(m.examples) > 0 485 testOk := RunTests(m.matchString, m.tests) 486 exampleOk := RunExamples(m.matchString, m.examples) 487 stopAlarm() 488 if !testOk || !exampleOk { 489 fmt.Println("FAIL") 490 after() 491 return 1 492 } 493 fmt.Println("PASS") 494 RunBenchmarks(m.matchString, m.benchmarks) 495 after() 496 return 0 497 } 498 499 func (t *T) report() { 500 dstr := fmtDuration(t.duration) 501 format := "--- %s: %s (%s)\n%s" 502 if t.Failed() { 503 fmt.Printf(format, "FAIL", t.name, dstr, t.output) 504 } else if *chatty { 505 if t.Skipped() { 506 fmt.Printf(format, "SKIP", t.name, dstr, t.output) 507 } else { 508 fmt.Printf(format, "PASS", t.name, dstr, t.output) 509 } 510 } 511 } 512 513 func RunTests(matchString func(pat, str string) (bool, error), tests []InternalTest) (ok bool) { 514 ok = true 515 if len(tests) == 0 && !haveExamples { 516 fmt.Fprintln(os.Stderr, "testing: warning: no tests to run") 517 return 518 } 519 for _, procs := range cpuList { 520 runtime.GOMAXPROCS(procs) 521 // We build a new channel tree for each run of the loop. 522 // collector merges in one channel all the upstream signals from parallel tests. 523 // If all tests pump to the same channel, a bug can occur where a test 524 // kicks off a goroutine that Fails, yet the test still delivers a completion signal, 525 // which skews the counting. 526 var collector = make(chan interface{}) 527 528 numParallel := 0 529 startParallel := make(chan bool) 530 531 for i := 0; i < len(tests); i++ { 532 matched, err := matchString(*match, tests[i].Name) 533 if err != nil { 534 fmt.Fprintf(os.Stderr, "testing: invalid regexp for -test.run: %s\n", err) 535 os.Exit(1) 536 } 537 if !matched { 538 continue 539 } 540 testName := tests[i].Name 541 if procs != 1 { 542 testName = fmt.Sprintf("%s-%d", tests[i].Name, procs) 543 } 544 t := &T{ 545 common: common{ 546 signal: make(chan interface{}), 547 }, 548 name: testName, 549 startParallel: startParallel, 550 } 551 t.self = t 552 if *chatty { 553 fmt.Printf("=== RUN %s\n", t.name) 554 } 555 go tRunner(t, &tests[i]) 556 out := (<-t.signal).(*T) 557 if out == nil { // Parallel run. 558 go func() { 559 collector <- <-t.signal 560 }() 561 numParallel++ 562 continue 563 } 564 t.report() 565 ok = ok && !out.Failed() 566 } 567 568 running := 0 569 for numParallel+running > 0 { 570 if running < *parallel && numParallel > 0 { 571 startParallel <- true 572 running++ 573 numParallel-- 574 continue 575 } 576 t := (<-collector).(*T) 577 t.report() 578 ok = ok && !t.Failed() 579 running-- 580 } 581 } 582 return 583 } 584 585 // before runs before all testing. 586 func before() { 587 if *memProfileRate > 0 { 588 runtime.MemProfileRate = *memProfileRate 589 } 590 if *cpuProfile != "" { 591 f, err := os.Create(toOutputDir(*cpuProfile)) 592 if err != nil { 593 fmt.Fprintf(os.Stderr, "testing: %s", err) 594 return 595 } 596 if err := pprof.StartCPUProfile(f); err != nil { 597 fmt.Fprintf(os.Stderr, "testing: can't start cpu profile: %s", err) 598 f.Close() 599 return 600 } 601 // Could save f so after can call f.Close; not worth the effort. 602 } 603 if *blockProfile != "" && *blockProfileRate >= 0 { 604 runtime.SetBlockProfileRate(*blockProfileRate) 605 } 606 if *coverProfile != "" && cover.Mode == "" { 607 fmt.Fprintf(os.Stderr, "testing: cannot use -test.coverprofile because test binary was not built with coverage enabled\n") 608 os.Exit(2) 609 } 610 } 611 612 // after runs after all testing. 613 func after() { 614 if *cpuProfile != "" { 615 pprof.StopCPUProfile() // flushes profile to disk 616 } 617 if *memProfile != "" { 618 f, err := os.Create(toOutputDir(*memProfile)) 619 if err != nil { 620 fmt.Fprintf(os.Stderr, "testing: %s\n", err) 621 os.Exit(2) 622 } 623 runtime.GC() // materialize all statistics 624 if err = pprof.WriteHeapProfile(f); err != nil { 625 fmt.Fprintf(os.Stderr, "testing: can't write %s: %s\n", *memProfile, err) 626 os.Exit(2) 627 } 628 f.Close() 629 } 630 if *blockProfile != "" && *blockProfileRate >= 0 { 631 f, err := os.Create(toOutputDir(*blockProfile)) 632 if err != nil { 633 fmt.Fprintf(os.Stderr, "testing: %s\n", err) 634 os.Exit(2) 635 } 636 if err = pprof.Lookup("block").WriteTo(f, 0); err != nil { 637 fmt.Fprintf(os.Stderr, "testing: can't write %s: %s\n", *blockProfile, err) 638 os.Exit(2) 639 } 640 f.Close() 641 } 642 if cover.Mode != "" { 643 coverReport() 644 } 645 } 646 647 // toOutputDir returns the file name relocated, if required, to outputDir. 648 // Simple implementation to avoid pulling in path/filepath. 649 func toOutputDir(path string) string { 650 if *outputDir == "" || path == "" { 651 return path 652 } 653 if runtime.GOOS == "windows" { 654 // On Windows, it's clumsy, but we can be almost always correct 655 // by just looking for a drive letter and a colon. 656 // Absolute paths always have a drive letter (ignoring UNC). 657 // Problem: if path == "C:A" and outputdir == "C:\Go" it's unclear 658 // what to do, but even then path/filepath doesn't help. 659 // TODO: Worth doing better? Probably not, because we're here only 660 // under the management of go test. 661 if len(path) >= 2 { 662 letter, colon := path[0], path[1] 663 if ('a' <= letter && letter <= 'z' || 'A' <= letter && letter <= 'Z') && colon == ':' { 664 // If path starts with a drive letter we're stuck with it regardless. 665 return path 666 } 667 } 668 } 669 if os.IsPathSeparator(path[0]) { 670 return path 671 } 672 return fmt.Sprintf("%s%c%s", *outputDir, os.PathSeparator, path) 673 } 674 675 var timer *time.Timer 676 677 // startAlarm starts an alarm if requested. 678 func startAlarm() { 679 if *timeout > 0 { 680 timer = time.AfterFunc(*timeout, func() { 681 panic(fmt.Sprintf("test timed out after %v", *timeout)) 682 }) 683 } 684 } 685 686 // stopAlarm turns off the alarm. 687 func stopAlarm() { 688 if *timeout > 0 { 689 timer.Stop() 690 } 691 } 692 693 func parseCpuList() { 694 for _, val := range strings.Split(*cpuListStr, ",") { 695 val = strings.TrimSpace(val) 696 if val == "" { 697 continue 698 } 699 cpu, err := strconv.Atoi(val) 700 if err != nil || cpu <= 0 { 701 fmt.Fprintf(os.Stderr, "testing: invalid value %q for -test.cpu\n", val) 702 os.Exit(1) 703 } 704 cpuList = append(cpuList, cpu) 705 } 706 if cpuList == nil { 707 cpuList = append(cpuList, runtime.GOMAXPROCS(-1)) 708 } 709 }