github.com/mdempsky/go@v0.0.0-20151201204031-5dd372bd1e70/src/cmd/go/test.go (about) 1 // Copyright 2011 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 main 6 7 import ( 8 "bytes" 9 "errors" 10 "fmt" 11 "go/ast" 12 "go/build" 13 "go/doc" 14 "go/parser" 15 "go/token" 16 "os" 17 "os/exec" 18 "path" 19 "path/filepath" 20 "regexp" 21 "runtime" 22 "sort" 23 "strings" 24 "text/template" 25 "time" 26 "unicode" 27 "unicode/utf8" 28 ) 29 30 // Break init loop. 31 func init() { 32 cmdTest.Run = runTest 33 } 34 35 const testUsage = "test [-c] [-i] [build and test flags] [packages] [flags for test binary]" 36 37 var cmdTest = &Command{ 38 CustomFlags: true, 39 UsageLine: testUsage, 40 Short: "test packages", 41 Long: ` 42 'Go test' automates testing the packages named by the import paths. 43 It prints a summary of the test results in the format: 44 45 ok archive/tar 0.011s 46 FAIL archive/zip 0.022s 47 ok compress/gzip 0.033s 48 ... 49 50 followed by detailed output for each failed package. 51 52 'Go test' recompiles each package along with any files with names matching 53 the file pattern "*_test.go". 54 Files whose names begin with "_" (including "_test.go") or "." are ignored. 55 These additional files can contain test functions, benchmark functions, and 56 example functions. See 'go help testfunc' for more. 57 Each listed package causes the execution of a separate test binary. 58 59 Test files that declare a package with the suffix "_test" will be compiled as a 60 separate package, and then linked and run with the main test binary. 61 62 By default, go test needs no arguments. It compiles and tests the package 63 with source in the current directory, including tests, and runs the tests. 64 65 The package is built in a temporary directory so it does not interfere with the 66 non-test installation. 67 68 ` + strings.TrimSpace(testFlag1) + ` See 'go help testflag' for details. 69 70 If the test binary needs any other flags, they should be presented after the 71 package names. The go tool treats as a flag the first argument that begins with 72 a minus sign that it does not recognize itself; that argument and all subsequent 73 arguments are passed as arguments to the test binary. 74 75 For more about build flags, see 'go help build'. 76 For more about specifying packages, see 'go help packages'. 77 78 See also: go build, go vet. 79 `, 80 } 81 82 const testFlag1 = ` 83 In addition to the build flags, the flags handled by 'go test' itself are: 84 85 -c 86 Compile the test binary to pkg.test but do not run it 87 (where pkg is the last element of the package's import path). 88 The file name can be changed with the -o flag. 89 90 -exec xprog 91 Run the test binary using xprog. The behavior is the same as 92 in 'go run'. See 'go help run' for details. 93 94 -i 95 Install packages that are dependencies of the test. 96 Do not run the test. 97 98 -o file 99 Compile the test binary to the named file. 100 The test still runs (unless -c or -i is specified). 101 102 The test binary also accepts flags that control execution of the test; these 103 flags are also accessible by 'go test'. 104 ` 105 106 var helpTestflag = &Command{ 107 UsageLine: "testflag", 108 Short: "description of testing flags", 109 Long: ` 110 The 'go test' command takes both flags that apply to 'go test' itself 111 and flags that apply to the resulting test binary. 112 113 Several of the flags control profiling and write an execution profile 114 suitable for "go tool pprof"; run "go tool pprof -h" for more 115 information. The --alloc_space, --alloc_objects, and --show_bytes 116 options of pprof control how the information is presented. 117 118 The following flags are recognized by the 'go test' command and 119 control the execution of any test: 120 121 ` + strings.TrimSpace(testFlag2) + ` 122 `, 123 } 124 125 const testFlag2 = ` 126 -bench regexp 127 Run benchmarks matching the regular expression. 128 By default, no benchmarks run. To run all benchmarks, 129 use '-bench .' or '-bench=.'. 130 131 -benchmem 132 Print memory allocation statistics for benchmarks. 133 134 -benchtime t 135 Run enough iterations of each benchmark to take t, specified 136 as a time.Duration (for example, -benchtime 1h30s). 137 The default is 1 second (1s). 138 139 -blockprofile block.out 140 Write a goroutine blocking profile to the specified file 141 when all tests are complete. 142 Writes test binary as -c would. 143 144 -blockprofilerate n 145 Control the detail provided in goroutine blocking profiles by 146 calling runtime.SetBlockProfileRate with n. 147 See 'go doc runtime.SetBlockProfileRate'. 148 The profiler aims to sample, on average, one blocking event every 149 n nanoseconds the program spends blocked. By default, 150 if -test.blockprofile is set without this flag, all blocking events 151 are recorded, equivalent to -test.blockprofilerate=1. 152 153 -count n 154 Run each test and benchmark n times (default 1). 155 If -cpu is set, run n times for each GOMAXPROCS value. 156 Examples are always run once. 157 158 -cover 159 Enable coverage analysis. 160 161 -covermode set,count,atomic 162 Set the mode for coverage analysis for the package[s] 163 being tested. The default is "set" unless -race is enabled, 164 in which case it is "atomic". 165 The values: 166 set: bool: does this statement run? 167 count: int: how many times does this statement run? 168 atomic: int: count, but correct in multithreaded tests; 169 significantly more expensive. 170 Sets -cover. 171 172 -coverpkg pkg1,pkg2,pkg3 173 Apply coverage analysis in each test to the given list of packages. 174 The default is for each test to analyze only the package being tested. 175 Packages are specified as import paths. 176 Sets -cover. 177 178 -coverprofile cover.out 179 Write a coverage profile to the file after all tests have passed. 180 Sets -cover. 181 182 -cpu 1,2,4 183 Specify a list of GOMAXPROCS values for which the tests or 184 benchmarks should be executed. The default is the current value 185 of GOMAXPROCS. 186 187 -cpuprofile cpu.out 188 Write a CPU profile to the specified file before exiting. 189 Writes test binary as -c would. 190 191 -memprofile mem.out 192 Write a memory profile to the file after all tests have passed. 193 Writes test binary as -c would. 194 195 -memprofilerate n 196 Enable more precise (and expensive) memory profiles by setting 197 runtime.MemProfileRate. See 'go doc runtime.MemProfileRate'. 198 To profile all memory allocations, use -test.memprofilerate=1 199 and pass --alloc_space flag to the pprof tool. 200 201 -outputdir directory 202 Place output files from profiling in the specified directory, 203 by default the directory in which "go test" is running. 204 205 -parallel n 206 Allow parallel execution of test functions that call t.Parallel. 207 The value of this flag is the maximum number of tests to run 208 simultaneously; by default, it is set to the value of GOMAXPROCS. 209 210 -run regexp 211 Run only those tests and examples matching the regular 212 expression. 213 214 -short 215 Tell long-running tests to shorten their run time. 216 It is off by default but set during all.bash so that installing 217 the Go tree can run a sanity check but not spend time running 218 exhaustive tests. 219 220 -timeout t 221 If a test runs longer than t, panic. 222 The default is 10 minutes (10m). 223 224 -trace trace.out 225 Write an execution trace to the specified file before exiting. 226 Writes test binary as -c would. 227 228 -v 229 Verbose output: log all tests as they are run. Also print all 230 text from Log and Logf calls even if the test succeeds. 231 232 The test binary, called pkg.test where pkg is the name of the 233 directory containing the package sources, can be invoked directly 234 after building it with 'go test -c'. When invoking the test binary 235 directly, each of the standard flag names must be prefixed with 'test.', 236 as in -test.run=TestMyFunc or -test.v. 237 238 When running 'go test', flags not listed above are passed through 239 unaltered. For instance, the command 240 241 go test -x -v -cpuprofile=prof.out -dir=testdata -update 242 243 will compile the test binary and then run it as 244 245 pkg.test -test.v -test.cpuprofile=prof.out -dir=testdata -update 246 247 The test flags that generate profiles (other than for coverage) also 248 leave the test binary in pkg.test for use when analyzing the profiles. 249 250 Flags not recognized by 'go test' must be placed after any specified packages. 251 ` 252 253 var helpTestfunc = &Command{ 254 UsageLine: "testfunc", 255 Short: "description of testing functions", 256 Long: ` 257 The 'go test' command expects to find test, benchmark, and example functions 258 in the "*_test.go" files corresponding to the package under test. 259 260 A test function is one named TestXXX (where XXX is any alphanumeric string 261 not starting with a lower case letter) and should have the signature, 262 263 func TestXXX(t *testing.T) { ... } 264 265 A benchmark function is one named BenchmarkXXX and should have the signature, 266 267 func BenchmarkXXX(b *testing.B) { ... } 268 269 An example function is similar to a test function but, instead of using 270 *testing.T to report success or failure, prints output to os.Stdout. 271 That output is compared against the function's "Output:" comment, which 272 must be the last comment in the function body (see example below). An 273 example with no such comment, or with no text after "Output:" is compiled 274 but not executed. 275 276 Godoc displays the body of ExampleXXX to demonstrate the use 277 of the function, constant, or variable XXX. An example of a method M with 278 receiver type T or *T is named ExampleT_M. There may be multiple examples 279 for a given function, constant, or variable, distinguished by a trailing _xxx, 280 where xxx is a suffix not beginning with an upper case letter. 281 282 Here is an example of an example: 283 284 func ExamplePrintln() { 285 Println("The output of\nthis example.") 286 // Output: The output of 287 // this example. 288 } 289 290 The entire test file is presented as the example when it contains a single 291 example function, at least one other function, type, variable, or constant 292 declaration, and no test or benchmark functions. 293 294 See the documentation of the testing package for more information. 295 `, 296 } 297 298 var ( 299 testC bool // -c flag 300 testCover bool // -cover flag 301 testCoverMode string // -covermode flag 302 testCoverPaths []string // -coverpkg flag 303 testCoverPkgs []*Package // -coverpkg flag 304 testO string // -o flag 305 testProfile bool // some profiling flag 306 testNeedBinary bool // profile needs to keep binary around 307 testV bool // -v flag 308 testTimeout string // -timeout flag 309 testArgs []string 310 testBench bool 311 testStreamOutput bool // show output as it is generated 312 testShowPass bool // show passing output 313 314 testKillTimeout = 10 * time.Minute 315 ) 316 317 var testMainDeps = map[string]bool{ 318 // Dependencies for testmain. 319 "testing": true, 320 "regexp": true, 321 "os": true, 322 } 323 324 func runTest(cmd *Command, args []string) { 325 var pkgArgs []string 326 pkgArgs, testArgs = testFlags(args) 327 328 findExecCmd() // initialize cached result 329 330 instrumentInit() 331 buildModeInit() 332 pkgs := packagesForBuild(pkgArgs) 333 if len(pkgs) == 0 { 334 fatalf("no packages to test") 335 } 336 337 if testC && len(pkgs) != 1 { 338 fatalf("cannot use -c flag with multiple packages") 339 } 340 if testO != "" && len(pkgs) != 1 { 341 fatalf("cannot use -o flag with multiple packages") 342 } 343 if testProfile && len(pkgs) != 1 { 344 fatalf("cannot use test profile flag with multiple packages") 345 } 346 347 // If a test timeout was given and is parseable, set our kill timeout 348 // to that timeout plus one minute. This is a backup alarm in case 349 // the test wedges with a goroutine spinning and its background 350 // timer does not get a chance to fire. 351 if dt, err := time.ParseDuration(testTimeout); err == nil && dt > 0 { 352 testKillTimeout = dt + 1*time.Minute 353 } 354 355 // show passing test output (after buffering) with -v flag. 356 // must buffer because tests are running in parallel, and 357 // otherwise the output will get mixed. 358 testShowPass = testV 359 360 // stream test output (no buffering) when no package has 361 // been given on the command line (implicit current directory) 362 // or when benchmarking. 363 // Also stream if we're showing output anyway with a 364 // single package under test or if parallelism is set to 1. 365 // In these cases, streaming the output produces the same result 366 // as not streaming, just more immediately. 367 testStreamOutput = len(pkgArgs) == 0 || testBench || 368 (testShowPass && (len(pkgs) == 1 || buildP == 1)) 369 370 var b builder 371 b.init() 372 373 if buildI { 374 buildV = testV 375 376 deps := make(map[string]bool) 377 for dep := range testMainDeps { 378 deps[dep] = true 379 } 380 381 for _, p := range pkgs { 382 // Dependencies for each test. 383 for _, path := range p.Imports { 384 deps[path] = true 385 } 386 for _, path := range p.vendored(p.TestImports) { 387 deps[path] = true 388 } 389 for _, path := range p.vendored(p.XTestImports) { 390 deps[path] = true 391 } 392 } 393 394 // translate C to runtime/cgo 395 if deps["C"] { 396 delete(deps, "C") 397 deps["runtime/cgo"] = true 398 if goos == runtime.GOOS && goarch == runtime.GOARCH && !buildRace && !buildMSan { 399 deps["cmd/cgo"] = true 400 } 401 } 402 // Ignore pseudo-packages. 403 delete(deps, "unsafe") 404 405 all := []string{} 406 for path := range deps { 407 if !build.IsLocalImport(path) { 408 all = append(all, path) 409 } 410 } 411 sort.Strings(all) 412 413 a := &action{} 414 for _, p := range packagesForBuild(all) { 415 a.deps = append(a.deps, b.action(modeInstall, modeInstall, p)) 416 } 417 b.do(a) 418 if !testC || a.failed { 419 return 420 } 421 b.init() 422 } 423 424 var builds, runs, prints []*action 425 426 if testCoverPaths != nil { 427 // Load packages that were asked about for coverage. 428 // packagesForBuild exits if the packages cannot be loaded. 429 testCoverPkgs = packagesForBuild(testCoverPaths) 430 431 // Warn about -coverpkg arguments that are not actually used. 432 used := make(map[string]bool) 433 for _, p := range pkgs { 434 used[p.ImportPath] = true 435 for _, dep := range p.Deps { 436 used[dep] = true 437 } 438 } 439 for _, p := range testCoverPkgs { 440 if !used[p.ImportPath] { 441 fmt.Fprintf(os.Stderr, "warning: no packages being tested depend on %s\n", p.ImportPath) 442 } 443 } 444 445 // Mark all the coverage packages for rebuilding with coverage. 446 for _, p := range testCoverPkgs { 447 // There is nothing to cover in package unsafe; it comes from the compiler. 448 if p.ImportPath == "unsafe" { 449 continue 450 } 451 p.Stale = true // rebuild 452 p.fake = true // do not warn about rebuild 453 p.coverMode = testCoverMode 454 var coverFiles []string 455 coverFiles = append(coverFiles, p.GoFiles...) 456 coverFiles = append(coverFiles, p.CgoFiles...) 457 coverFiles = append(coverFiles, p.TestGoFiles...) 458 p.coverVars = declareCoverVars(p.ImportPath, coverFiles...) 459 } 460 } 461 462 // Prepare build + run + print actions for all packages being tested. 463 for _, p := range pkgs { 464 buildTest, runTest, printTest, err := b.test(p) 465 if err != nil { 466 str := err.Error() 467 if strings.HasPrefix(str, "\n") { 468 str = str[1:] 469 } 470 failed := fmt.Sprintf("FAIL\t%s [setup failed]\n", p.ImportPath) 471 472 if p.ImportPath != "" { 473 errorf("# %s\n%s\n%s", p.ImportPath, str, failed) 474 } else { 475 errorf("%s\n%s", str, failed) 476 } 477 continue 478 } 479 builds = append(builds, buildTest) 480 runs = append(runs, runTest) 481 prints = append(prints, printTest) 482 } 483 484 // Ultimately the goal is to print the output. 485 root := &action{deps: prints} 486 487 // Force the printing of results to happen in order, 488 // one at a time. 489 for i, a := range prints { 490 if i > 0 { 491 a.deps = append(a.deps, prints[i-1]) 492 } 493 } 494 495 // Force benchmarks to run in serial. 496 if !testC && testBench { 497 // The first run must wait for all builds. 498 // Later runs must wait for the previous run's print. 499 for i, run := range runs { 500 if i == 0 { 501 run.deps = append(run.deps, builds...) 502 } else { 503 run.deps = append(run.deps, prints[i-1]) 504 } 505 } 506 } 507 508 // If we are building any out-of-date packages other 509 // than those under test, warn. 510 okBuild := map[*Package]bool{} 511 for _, p := range pkgs { 512 okBuild[p] = true 513 } 514 warned := false 515 for _, a := range actionList(root) { 516 if a.p == nil || okBuild[a.p] { 517 continue 518 } 519 okBuild[a.p] = true // warn at most once 520 521 // Don't warn about packages being rebuilt because of 522 // things like coverage analysis. 523 for _, p1 := range a.p.imports { 524 if p1.fake { 525 a.p.fake = true 526 } 527 } 528 529 if a.f != nil && !okBuild[a.p] && !a.p.fake && !a.p.local { 530 if !warned { 531 fmt.Fprintf(os.Stderr, "warning: building out-of-date packages:\n") 532 warned = true 533 } 534 fmt.Fprintf(os.Stderr, "\t%s\n", a.p.ImportPath) 535 } 536 } 537 if warned { 538 args := strings.Join(pkgArgs, " ") 539 if args != "" { 540 args = " " + args 541 } 542 extraOpts := "" 543 if buildRace { 544 extraOpts = "-race " 545 } 546 if buildMSan { 547 extraOpts = "-msan " 548 } 549 fmt.Fprintf(os.Stderr, "installing these packages with 'go test %s-i%s' will speed future tests.\n\n", extraOpts, args) 550 } 551 552 b.do(root) 553 } 554 555 func contains(x []string, s string) bool { 556 for _, t := range x { 557 if t == s { 558 return true 559 } 560 } 561 return false 562 } 563 564 var windowsBadWords = []string{ 565 "install", 566 "patch", 567 "setup", 568 "update", 569 } 570 571 func (b *builder) test(p *Package) (buildAction, runAction, printAction *action, err error) { 572 if len(p.TestGoFiles)+len(p.XTestGoFiles) == 0 { 573 build := b.action(modeBuild, modeBuild, p) 574 run := &action{p: p, deps: []*action{build}} 575 print := &action{f: (*builder).notest, p: p, deps: []*action{run}} 576 return build, run, print, nil 577 } 578 579 // Build Package structs describing: 580 // ptest - package + test files 581 // pxtest - package of external test files 582 // pmain - pkg.test binary 583 var ptest, pxtest, pmain *Package 584 585 var imports, ximports []*Package 586 var stk importStack 587 stk.push(p.ImportPath + " (test)") 588 for i, path := range p.TestImports { 589 p1 := loadImport(path, p.Dir, p, &stk, p.build.TestImportPos[path], useVendor) 590 if p1.Error != nil { 591 return nil, nil, nil, p1.Error 592 } 593 if len(p1.DepsErrors) > 0 { 594 err := p1.DepsErrors[0] 595 err.Pos = "" // show full import stack 596 return nil, nil, nil, err 597 } 598 if contains(p1.Deps, p.ImportPath) || p1.ImportPath == p.ImportPath { 599 // Same error that loadPackage returns (via reusePackage) in pkg.go. 600 // Can't change that code, because that code is only for loading the 601 // non-test copy of a package. 602 err := &PackageError{ 603 ImportStack: testImportStack(stk[0], p1, p.ImportPath), 604 Err: "import cycle not allowed in test", 605 isImportCycle: true, 606 } 607 return nil, nil, nil, err 608 } 609 p.TestImports[i] = p1.ImportPath 610 imports = append(imports, p1) 611 } 612 stk.pop() 613 stk.push(p.ImportPath + "_test") 614 pxtestNeedsPtest := false 615 for i, path := range p.XTestImports { 616 p1 := loadImport(path, p.Dir, p, &stk, p.build.XTestImportPos[path], useVendor) 617 if p1.Error != nil { 618 return nil, nil, nil, p1.Error 619 } 620 if len(p1.DepsErrors) > 0 { 621 err := p1.DepsErrors[0] 622 err.Pos = "" // show full import stack 623 return nil, nil, nil, err 624 } 625 if p1.ImportPath == p.ImportPath { 626 pxtestNeedsPtest = true 627 } else { 628 ximports = append(ximports, p1) 629 } 630 p.XTestImports[i] = p1.ImportPath 631 } 632 stk.pop() 633 634 // Use last element of import path, not package name. 635 // They differ when package name is "main". 636 // But if the import path is "command-line-arguments", 637 // like it is during 'go run', use the package name. 638 var elem string 639 if p.ImportPath == "command-line-arguments" { 640 elem = p.Name 641 } else { 642 _, elem = path.Split(p.ImportPath) 643 } 644 testBinary := elem + ".test" 645 646 // The ptest package needs to be importable under the 647 // same import path that p has, but we cannot put it in 648 // the usual place in the temporary tree, because then 649 // other tests will see it as the real package. 650 // Instead we make a _test directory under the import path 651 // and then repeat the import path there. We tell the 652 // compiler and linker to look in that _test directory first. 653 // 654 // That is, if the package under test is unicode/utf8, 655 // then the normal place to write the package archive is 656 // $WORK/unicode/utf8.a, but we write the test package archive to 657 // $WORK/unicode/utf8/_test/unicode/utf8.a. 658 // We write the external test package archive to 659 // $WORK/unicode/utf8/_test/unicode/utf8_test.a. 660 testDir := filepath.Join(b.work, filepath.FromSlash(p.ImportPath+"/_test")) 661 ptestObj := buildToolchain.pkgpath(testDir, p) 662 663 // Create the directory for the .a files. 664 ptestDir, _ := filepath.Split(ptestObj) 665 if err := b.mkdir(ptestDir); err != nil { 666 return nil, nil, nil, err 667 } 668 669 // Should we apply coverage analysis locally, 670 // only for this package and only for this test? 671 // Yes, if -cover is on but -coverpkg has not specified 672 // a list of packages for global coverage. 673 localCover := testCover && testCoverPaths == nil 674 675 // Test package. 676 if len(p.TestGoFiles) > 0 || localCover || p.Name == "main" { 677 ptest = new(Package) 678 *ptest = *p 679 ptest.GoFiles = nil 680 ptest.GoFiles = append(ptest.GoFiles, p.GoFiles...) 681 ptest.GoFiles = append(ptest.GoFiles, p.TestGoFiles...) 682 ptest.target = "" 683 ptest.Imports = stringList(p.Imports, p.TestImports) 684 ptest.imports = append(append([]*Package{}, p.imports...), imports...) 685 ptest.pkgdir = testDir 686 ptest.fake = true 687 ptest.forceLibrary = true 688 ptest.Stale = true 689 ptest.build = new(build.Package) 690 *ptest.build = *p.build 691 m := map[string][]token.Position{} 692 for k, v := range p.build.ImportPos { 693 m[k] = append(m[k], v...) 694 } 695 for k, v := range p.build.TestImportPos { 696 m[k] = append(m[k], v...) 697 } 698 ptest.build.ImportPos = m 699 700 if localCover { 701 ptest.coverMode = testCoverMode 702 var coverFiles []string 703 coverFiles = append(coverFiles, ptest.GoFiles...) 704 coverFiles = append(coverFiles, ptest.CgoFiles...) 705 ptest.coverVars = declareCoverVars(ptest.ImportPath, coverFiles...) 706 } 707 } else { 708 ptest = p 709 } 710 711 // External test package. 712 if len(p.XTestGoFiles) > 0 { 713 pxtest = &Package{ 714 Name: p.Name + "_test", 715 ImportPath: p.ImportPath + "_test", 716 localPrefix: p.localPrefix, 717 Root: p.Root, 718 Dir: p.Dir, 719 GoFiles: p.XTestGoFiles, 720 Imports: p.XTestImports, 721 build: &build.Package{ 722 ImportPos: p.build.XTestImportPos, 723 }, 724 imports: ximports, 725 pkgdir: testDir, 726 fake: true, 727 external: true, 728 Stale: true, 729 } 730 if pxtestNeedsPtest { 731 pxtest.imports = append(pxtest.imports, ptest) 732 } 733 } 734 735 // Action for building pkg.test. 736 pmain = &Package{ 737 Name: "main", 738 Dir: testDir, 739 GoFiles: []string{"_testmain.go"}, 740 ImportPath: "testmain", 741 Root: p.Root, 742 build: &build.Package{Name: "main"}, 743 pkgdir: testDir, 744 fake: true, 745 Stale: true, 746 omitDWARF: !testC && !testNeedBinary, 747 } 748 749 // The generated main also imports testing, regexp, and os. 750 stk.push("testmain") 751 for dep := range testMainDeps { 752 if dep == ptest.ImportPath { 753 pmain.imports = append(pmain.imports, ptest) 754 } else { 755 p1 := loadImport(dep, "", nil, &stk, nil, 0) 756 if p1.Error != nil { 757 return nil, nil, nil, p1.Error 758 } 759 pmain.imports = append(pmain.imports, p1) 760 } 761 } 762 763 if testCoverPkgs != nil { 764 // Add imports, but avoid duplicates. 765 seen := map[*Package]bool{p: true, ptest: true} 766 for _, p1 := range pmain.imports { 767 seen[p1] = true 768 } 769 for _, p1 := range testCoverPkgs { 770 if !seen[p1] { 771 seen[p1] = true 772 pmain.imports = append(pmain.imports, p1) 773 } 774 } 775 } 776 777 // Do initial scan for metadata needed for writing _testmain.go 778 // Use that metadata to update the list of imports for package main. 779 // The list of imports is used by recompileForTest and by the loop 780 // afterward that gathers t.Cover information. 781 t, err := loadTestFuncs(ptest) 782 if err != nil { 783 return nil, nil, nil, err 784 } 785 if len(ptest.GoFiles) > 0 { 786 pmain.imports = append(pmain.imports, ptest) 787 t.ImportTest = true 788 } 789 if pxtest != nil { 790 pmain.imports = append(pmain.imports, pxtest) 791 t.ImportXtest = true 792 } 793 794 if ptest != p && localCover { 795 // We have made modifications to the package p being tested 796 // and are rebuilding p (as ptest), writing it to the testDir tree. 797 // Arrange to rebuild, writing to that same tree, all packages q 798 // such that the test depends on q, and q depends on p. 799 // This makes sure that q sees the modifications to p. 800 // Strictly speaking, the rebuild is only necessary if the 801 // modifications to p change its export metadata, but 802 // determining that is a bit tricky, so we rebuild always. 803 // 804 // This will cause extra compilation, so for now we only do it 805 // when testCover is set. The conditions are more general, though, 806 // and we may find that we need to do it always in the future. 807 recompileForTest(pmain, p, ptest, testDir) 808 } 809 810 if buildContext.GOOS == "darwin" { 811 if buildContext.GOARCH == "arm" || buildContext.GOARCH == "arm64" { 812 t.NeedCgo = true 813 } 814 } 815 816 for _, cp := range pmain.imports { 817 if len(cp.coverVars) > 0 { 818 t.Cover = append(t.Cover, coverInfo{cp, cp.coverVars}) 819 } 820 } 821 822 if !buildN { 823 // writeTestmain writes _testmain.go. This must happen after recompileForTest, 824 // because recompileForTest modifies XXX. 825 if err := writeTestmain(filepath.Join(testDir, "_testmain.go"), t); err != nil { 826 return nil, nil, nil, err 827 } 828 } 829 830 computeStale(pmain) 831 832 if ptest != p { 833 a := b.action(modeBuild, modeBuild, ptest) 834 a.objdir = testDir + string(filepath.Separator) + "_obj_test" + string(filepath.Separator) 835 a.objpkg = ptestObj 836 a.target = ptestObj 837 a.link = false 838 } 839 840 if pxtest != nil { 841 a := b.action(modeBuild, modeBuild, pxtest) 842 a.objdir = testDir + string(filepath.Separator) + "_obj_xtest" + string(filepath.Separator) 843 a.objpkg = buildToolchain.pkgpath(testDir, pxtest) 844 a.target = a.objpkg 845 } 846 847 a := b.action(modeBuild, modeBuild, pmain) 848 a.objdir = testDir + string(filepath.Separator) 849 a.objpkg = filepath.Join(testDir, "main.a") 850 a.target = filepath.Join(testDir, testBinary) + exeSuffix 851 if goos == "windows" { 852 // There are many reserved words on Windows that, 853 // if used in the name of an executable, cause Windows 854 // to try to ask for extra permissions. 855 // The word list includes setup, install, update, and patch, 856 // but it does not appear to be defined anywhere. 857 // We have run into this trying to run the 858 // go.codereview/patch tests. 859 // For package names containing those words, use test.test.exe 860 // instead of pkgname.test.exe. 861 // Note that this file name is only used in the Go command's 862 // temporary directory. If the -c or other flags are 863 // given, the code below will still use pkgname.test.exe. 864 // There are two user-visible effects of this change. 865 // First, you can actually run 'go test' in directories that 866 // have names that Windows thinks are installer-like, 867 // without getting a dialog box asking for more permissions. 868 // Second, in the Windows process listing during go test, 869 // the test shows up as test.test.exe, not pkgname.test.exe. 870 // That second one is a drawback, but it seems a small 871 // price to pay for the test running at all. 872 // If maintaining the list of bad words is too onerous, 873 // we could just do this always on Windows. 874 for _, bad := range windowsBadWords { 875 if strings.Contains(testBinary, bad) { 876 a.target = filepath.Join(testDir, "test.test") + exeSuffix 877 break 878 } 879 } 880 } 881 buildAction = a 882 883 if testC || testNeedBinary { 884 // -c or profiling flag: create action to copy binary to ./test.out. 885 target := filepath.Join(cwd, testBinary+exeSuffix) 886 if testO != "" { 887 target = testO 888 if !filepath.IsAbs(target) { 889 target = filepath.Join(cwd, target) 890 } 891 } 892 buildAction = &action{ 893 f: (*builder).install, 894 deps: []*action{buildAction}, 895 p: pmain, 896 target: target, 897 } 898 runAction = buildAction // make sure runAction != nil even if not running test 899 } 900 if testC { 901 printAction = &action{p: p, deps: []*action{runAction}} // nop 902 } else { 903 // run test 904 runAction = &action{ 905 f: (*builder).runTest, 906 deps: []*action{buildAction}, 907 p: p, 908 ignoreFail: true, 909 } 910 cleanAction := &action{ 911 f: (*builder).cleanTest, 912 deps: []*action{runAction}, 913 p: p, 914 } 915 printAction = &action{ 916 f: (*builder).printTest, 917 deps: []*action{cleanAction}, 918 p: p, 919 } 920 } 921 922 return buildAction, runAction, printAction, nil 923 } 924 925 func testImportStack(top string, p *Package, target string) []string { 926 stk := []string{top, p.ImportPath} 927 Search: 928 for p.ImportPath != target { 929 for _, p1 := range p.imports { 930 if p1.ImportPath == target || contains(p1.Deps, target) { 931 stk = append(stk, p1.ImportPath) 932 p = p1 933 continue Search 934 } 935 } 936 // Can't happen, but in case it does... 937 stk = append(stk, "<lost path to cycle>") 938 break 939 } 940 return stk 941 } 942 943 func recompileForTest(pmain, preal, ptest *Package, testDir string) { 944 // The "test copy" of preal is ptest. 945 // For each package that depends on preal, make a "test copy" 946 // that depends on ptest. And so on, up the dependency tree. 947 testCopy := map[*Package]*Package{preal: ptest} 948 for _, p := range packageList([]*Package{pmain}) { 949 // Copy on write. 950 didSplit := false 951 split := func() { 952 if didSplit { 953 return 954 } 955 didSplit = true 956 if p.pkgdir != testDir { 957 p1 := new(Package) 958 testCopy[p] = p1 959 *p1 = *p 960 p1.imports = make([]*Package, len(p.imports)) 961 copy(p1.imports, p.imports) 962 p = p1 963 p.pkgdir = testDir 964 p.target = "" 965 p.fake = true 966 p.Stale = true 967 } 968 } 969 970 // Update p.deps and p.imports to use at test copies. 971 for i, dep := range p.deps { 972 if p1 := testCopy[dep]; p1 != nil && p1 != dep { 973 split() 974 p.deps[i] = p1 975 } 976 } 977 for i, imp := range p.imports { 978 if p1 := testCopy[imp]; p1 != nil && p1 != imp { 979 split() 980 p.imports[i] = p1 981 } 982 } 983 } 984 } 985 986 var coverIndex = 0 987 988 // isTestFile reports whether the source file is a set of tests and should therefore 989 // be excluded from coverage analysis. 990 func isTestFile(file string) bool { 991 // We don't cover tests, only the code they test. 992 return strings.HasSuffix(file, "_test.go") 993 } 994 995 // declareCoverVars attaches the required cover variables names 996 // to the files, to be used when annotating the files. 997 func declareCoverVars(importPath string, files ...string) map[string]*CoverVar { 998 coverVars := make(map[string]*CoverVar) 999 for _, file := range files { 1000 if isTestFile(file) { 1001 continue 1002 } 1003 coverVars[file] = &CoverVar{ 1004 File: filepath.Join(importPath, file), 1005 Var: fmt.Sprintf("GoCover_%d", coverIndex), 1006 } 1007 coverIndex++ 1008 } 1009 return coverVars 1010 } 1011 1012 // runTest is the action for running a test binary. 1013 func (b *builder) runTest(a *action) error { 1014 args := stringList(findExecCmd(), a.deps[0].target, testArgs) 1015 a.testOutput = new(bytes.Buffer) 1016 1017 if buildN || buildX { 1018 b.showcmd("", "%s", strings.Join(args, " ")) 1019 if buildN { 1020 return nil 1021 } 1022 } 1023 1024 if a.failed { 1025 // We were unable to build the binary. 1026 a.failed = false 1027 fmt.Fprintf(a.testOutput, "FAIL\t%s [build failed]\n", a.p.ImportPath) 1028 setExitStatus(1) 1029 return nil 1030 } 1031 1032 cmd := exec.Command(args[0], args[1:]...) 1033 cmd.Dir = a.p.Dir 1034 cmd.Env = envForDir(cmd.Dir, origEnv) 1035 var buf bytes.Buffer 1036 if testStreamOutput { 1037 cmd.Stdout = os.Stdout 1038 cmd.Stderr = os.Stderr 1039 } else { 1040 cmd.Stdout = &buf 1041 cmd.Stderr = &buf 1042 } 1043 1044 // If there are any local SWIG dependencies, we want to load 1045 // the shared library from the build directory. 1046 if a.p.usesSwig() { 1047 env := cmd.Env 1048 found := false 1049 prefix := "LD_LIBRARY_PATH=" 1050 for i, v := range env { 1051 if strings.HasPrefix(v, prefix) { 1052 env[i] = v + ":." 1053 found = true 1054 break 1055 } 1056 } 1057 if !found { 1058 env = append(env, "LD_LIBRARY_PATH=.") 1059 } 1060 cmd.Env = env 1061 } 1062 1063 t0 := time.Now() 1064 err := cmd.Start() 1065 1066 // This is a last-ditch deadline to detect and 1067 // stop wedged test binaries, to keep the builders 1068 // running. 1069 if err == nil { 1070 tick := time.NewTimer(testKillTimeout) 1071 startSigHandlers() 1072 done := make(chan error) 1073 go func() { 1074 done <- cmd.Wait() 1075 }() 1076 Outer: 1077 select { 1078 case err = <-done: 1079 // ok 1080 case <-tick.C: 1081 if signalTrace != nil { 1082 // Send a quit signal in the hope that the program will print 1083 // a stack trace and exit. Give it five seconds before resorting 1084 // to Kill. 1085 cmd.Process.Signal(signalTrace) 1086 select { 1087 case err = <-done: 1088 fmt.Fprintf(&buf, "*** Test killed with %v: ran too long (%v).\n", signalTrace, testKillTimeout) 1089 break Outer 1090 case <-time.After(5 * time.Second): 1091 } 1092 } 1093 cmd.Process.Kill() 1094 err = <-done 1095 fmt.Fprintf(&buf, "*** Test killed: ran too long (%v).\n", testKillTimeout) 1096 } 1097 tick.Stop() 1098 } 1099 out := buf.Bytes() 1100 t := fmt.Sprintf("%.3fs", time.Since(t0).Seconds()) 1101 if err == nil { 1102 if testShowPass { 1103 a.testOutput.Write(out) 1104 } 1105 fmt.Fprintf(a.testOutput, "ok \t%s\t%s%s\n", a.p.ImportPath, t, coveragePercentage(out)) 1106 return nil 1107 } 1108 1109 setExitStatus(1) 1110 if len(out) > 0 { 1111 a.testOutput.Write(out) 1112 // assume printing the test binary's exit status is superfluous 1113 } else { 1114 fmt.Fprintf(a.testOutput, "%s\n", err) 1115 } 1116 fmt.Fprintf(a.testOutput, "FAIL\t%s\t%s\n", a.p.ImportPath, t) 1117 1118 return nil 1119 } 1120 1121 // coveragePercentage returns the coverage results (if enabled) for the 1122 // test. It uncovers the data by scanning the output from the test run. 1123 func coveragePercentage(out []byte) string { 1124 if !testCover { 1125 return "" 1126 } 1127 // The string looks like 1128 // test coverage for encoding/binary: 79.9% of statements 1129 // Extract the piece from the percentage to the end of the line. 1130 re := regexp.MustCompile(`coverage: (.*)\n`) 1131 matches := re.FindSubmatch(out) 1132 if matches == nil { 1133 // Probably running "go test -cover" not "go test -cover fmt". 1134 // The coverage output will appear in the output directly. 1135 return "" 1136 } 1137 return fmt.Sprintf("\tcoverage: %s", matches[1]) 1138 } 1139 1140 // cleanTest is the action for cleaning up after a test. 1141 func (b *builder) cleanTest(a *action) error { 1142 if buildWork { 1143 return nil 1144 } 1145 run := a.deps[0] 1146 testDir := filepath.Join(b.work, filepath.FromSlash(run.p.ImportPath+"/_test")) 1147 os.RemoveAll(testDir) 1148 return nil 1149 } 1150 1151 // printTest is the action for printing a test result. 1152 func (b *builder) printTest(a *action) error { 1153 clean := a.deps[0] 1154 run := clean.deps[0] 1155 os.Stdout.Write(run.testOutput.Bytes()) 1156 run.testOutput = nil 1157 return nil 1158 } 1159 1160 // notest is the action for testing a package with no test files. 1161 func (b *builder) notest(a *action) error { 1162 fmt.Printf("? \t%s\t[no test files]\n", a.p.ImportPath) 1163 return nil 1164 } 1165 1166 // isTestMain tells whether fn is a TestMain(m *testing.M) function. 1167 func isTestMain(fn *ast.FuncDecl) bool { 1168 if fn.Name.String() != "TestMain" || 1169 fn.Type.Results != nil && len(fn.Type.Results.List) > 0 || 1170 fn.Type.Params == nil || 1171 len(fn.Type.Params.List) != 1 || 1172 len(fn.Type.Params.List[0].Names) > 1 { 1173 return false 1174 } 1175 ptr, ok := fn.Type.Params.List[0].Type.(*ast.StarExpr) 1176 if !ok { 1177 return false 1178 } 1179 // We can't easily check that the type is *testing.M 1180 // because we don't know how testing has been imported, 1181 // but at least check that it's *M or *something.M. 1182 if name, ok := ptr.X.(*ast.Ident); ok && name.Name == "M" { 1183 return true 1184 } 1185 if sel, ok := ptr.X.(*ast.SelectorExpr); ok && sel.Sel.Name == "M" { 1186 return true 1187 } 1188 return false 1189 } 1190 1191 // isTest tells whether name looks like a test (or benchmark, according to prefix). 1192 // It is a Test (say) if there is a character after Test that is not a lower-case letter. 1193 // We don't want TesticularCancer. 1194 func isTest(name, prefix string) bool { 1195 if !strings.HasPrefix(name, prefix) { 1196 return false 1197 } 1198 if len(name) == len(prefix) { // "Test" is ok 1199 return true 1200 } 1201 rune, _ := utf8.DecodeRuneInString(name[len(prefix):]) 1202 return !unicode.IsLower(rune) 1203 } 1204 1205 type coverInfo struct { 1206 Package *Package 1207 Vars map[string]*CoverVar 1208 } 1209 1210 // loadTestFuncs returns the testFuncs describing the tests that will be run. 1211 func loadTestFuncs(ptest *Package) (*testFuncs, error) { 1212 t := &testFuncs{ 1213 Package: ptest, 1214 } 1215 for _, file := range ptest.TestGoFiles { 1216 if err := t.load(filepath.Join(ptest.Dir, file), "_test", &t.ImportTest, &t.NeedTest); err != nil { 1217 return nil, err 1218 } 1219 } 1220 for _, file := range ptest.XTestGoFiles { 1221 if err := t.load(filepath.Join(ptest.Dir, file), "_xtest", &t.ImportXtest, &t.NeedXtest); err != nil { 1222 return nil, err 1223 } 1224 } 1225 return t, nil 1226 } 1227 1228 // writeTestmain writes the _testmain.go file for t to the file named out. 1229 func writeTestmain(out string, t *testFuncs) error { 1230 f, err := os.Create(out) 1231 if err != nil { 1232 return err 1233 } 1234 defer f.Close() 1235 1236 if err := testmainTmpl.Execute(f, t); err != nil { 1237 return err 1238 } 1239 1240 return nil 1241 } 1242 1243 type testFuncs struct { 1244 Tests []testFunc 1245 Benchmarks []testFunc 1246 Examples []testFunc 1247 TestMain *testFunc 1248 Package *Package 1249 ImportTest bool 1250 NeedTest bool 1251 ImportXtest bool 1252 NeedXtest bool 1253 NeedCgo bool 1254 Cover []coverInfo 1255 } 1256 1257 func (t *testFuncs) CoverMode() string { 1258 return testCoverMode 1259 } 1260 1261 func (t *testFuncs) CoverEnabled() bool { 1262 return testCover 1263 } 1264 1265 // Covered returns a string describing which packages are being tested for coverage. 1266 // If the covered package is the same as the tested package, it returns the empty string. 1267 // Otherwise it is a comma-separated human-readable list of packages beginning with 1268 // " in", ready for use in the coverage message. 1269 func (t *testFuncs) Covered() string { 1270 if testCoverPaths == nil { 1271 return "" 1272 } 1273 return " in " + strings.Join(testCoverPaths, ", ") 1274 } 1275 1276 // Tested returns the name of the package being tested. 1277 func (t *testFuncs) Tested() string { 1278 return t.Package.Name 1279 } 1280 1281 type testFunc struct { 1282 Package string // imported package name (_test or _xtest) 1283 Name string // function name 1284 Output string // output, for examples 1285 } 1286 1287 var testFileSet = token.NewFileSet() 1288 1289 func (t *testFuncs) load(filename, pkg string, doImport, seen *bool) error { 1290 f, err := parser.ParseFile(testFileSet, filename, nil, parser.ParseComments) 1291 if err != nil { 1292 return expandScanner(err) 1293 } 1294 for _, d := range f.Decls { 1295 n, ok := d.(*ast.FuncDecl) 1296 if !ok { 1297 continue 1298 } 1299 if n.Recv != nil { 1300 continue 1301 } 1302 name := n.Name.String() 1303 switch { 1304 case isTestMain(n): 1305 if t.TestMain != nil { 1306 return errors.New("multiple definitions of TestMain") 1307 } 1308 t.TestMain = &testFunc{pkg, name, ""} 1309 *doImport, *seen = true, true 1310 case isTest(name, "Test"): 1311 t.Tests = append(t.Tests, testFunc{pkg, name, ""}) 1312 *doImport, *seen = true, true 1313 case isTest(name, "Benchmark"): 1314 t.Benchmarks = append(t.Benchmarks, testFunc{pkg, name, ""}) 1315 *doImport, *seen = true, true 1316 } 1317 } 1318 ex := doc.Examples(f) 1319 sort.Sort(byOrder(ex)) 1320 for _, e := range ex { 1321 *doImport = true // import test file whether executed or not 1322 if e.Output == "" && !e.EmptyOutput { 1323 // Don't run examples with no output. 1324 continue 1325 } 1326 t.Examples = append(t.Examples, testFunc{pkg, "Example" + e.Name, e.Output}) 1327 *seen = true 1328 } 1329 return nil 1330 } 1331 1332 type byOrder []*doc.Example 1333 1334 func (x byOrder) Len() int { return len(x) } 1335 func (x byOrder) Swap(i, j int) { x[i], x[j] = x[j], x[i] } 1336 func (x byOrder) Less(i, j int) bool { return x[i].Order < x[j].Order } 1337 1338 var testmainTmpl = template.Must(template.New("main").Parse(` 1339 package main 1340 1341 import ( 1342 {{if not .TestMain}} 1343 "os" 1344 {{end}} 1345 "regexp" 1346 "testing" 1347 1348 {{if .ImportTest}} 1349 {{if .NeedTest}}_test{{else}}_{{end}} {{.Package.ImportPath | printf "%q"}} 1350 {{end}} 1351 {{if .ImportXtest}} 1352 {{if .NeedXtest}}_xtest{{else}}_{{end}} {{.Package.ImportPath | printf "%s_test" | printf "%q"}} 1353 {{end}} 1354 {{range $i, $p := .Cover}} 1355 _cover{{$i}} {{$p.Package.ImportPath | printf "%q"}} 1356 {{end}} 1357 1358 {{if .NeedCgo}} 1359 _ "runtime/cgo" 1360 {{end}} 1361 ) 1362 1363 var tests = []testing.InternalTest{ 1364 {{range .Tests}} 1365 {"{{.Name}}", {{.Package}}.{{.Name}}}, 1366 {{end}} 1367 } 1368 1369 var benchmarks = []testing.InternalBenchmark{ 1370 {{range .Benchmarks}} 1371 {"{{.Name}}", {{.Package}}.{{.Name}}}, 1372 {{end}} 1373 } 1374 1375 var examples = []testing.InternalExample{ 1376 {{range .Examples}} 1377 {"{{.Name}}", {{.Package}}.{{.Name}}, {{.Output | printf "%q"}}}, 1378 {{end}} 1379 } 1380 1381 var matchPat string 1382 var matchRe *regexp.Regexp 1383 1384 func matchString(pat, str string) (result bool, err error) { 1385 if matchRe == nil || matchPat != pat { 1386 matchPat = pat 1387 matchRe, err = regexp.Compile(matchPat) 1388 if err != nil { 1389 return 1390 } 1391 } 1392 return matchRe.MatchString(str), nil 1393 } 1394 1395 {{if .CoverEnabled}} 1396 1397 // Only updated by init functions, so no need for atomicity. 1398 var ( 1399 coverCounters = make(map[string][]uint32) 1400 coverBlocks = make(map[string][]testing.CoverBlock) 1401 ) 1402 1403 func init() { 1404 {{range $i, $p := .Cover}} 1405 {{range $file, $cover := $p.Vars}} 1406 coverRegisterFile({{printf "%q" $cover.File}}, _cover{{$i}}.{{$cover.Var}}.Count[:], _cover{{$i}}.{{$cover.Var}}.Pos[:], _cover{{$i}}.{{$cover.Var}}.NumStmt[:]) 1407 {{end}} 1408 {{end}} 1409 } 1410 1411 func coverRegisterFile(fileName string, counter []uint32, pos []uint32, numStmts []uint16) { 1412 if 3*len(counter) != len(pos) || len(counter) != len(numStmts) { 1413 panic("coverage: mismatched sizes") 1414 } 1415 if coverCounters[fileName] != nil { 1416 // Already registered. 1417 return 1418 } 1419 coverCounters[fileName] = counter 1420 block := make([]testing.CoverBlock, len(counter)) 1421 for i := range counter { 1422 block[i] = testing.CoverBlock{ 1423 Line0: pos[3*i+0], 1424 Col0: uint16(pos[3*i+2]), 1425 Line1: pos[3*i+1], 1426 Col1: uint16(pos[3*i+2]>>16), 1427 Stmts: numStmts[i], 1428 } 1429 } 1430 coverBlocks[fileName] = block 1431 } 1432 {{end}} 1433 1434 func main() { 1435 {{if .CoverEnabled}} 1436 testing.RegisterCover(testing.Cover{ 1437 Mode: {{printf "%q" .CoverMode}}, 1438 Counters: coverCounters, 1439 Blocks: coverBlocks, 1440 CoveredPackages: {{printf "%q" .Covered}}, 1441 }) 1442 {{end}} 1443 m := testing.MainStart(matchString, tests, benchmarks, examples) 1444 {{with .TestMain}} 1445 {{.Package}}.{{.Name}}(m) 1446 {{else}} 1447 os.Exit(m.Run()) 1448 {{end}} 1449 } 1450 1451 `))