github.com/rakyll/go@v0.0.0-20170216000551-64c02460d703/test/run.go (about) 1 // skip 2 3 // Copyright 2012 The Go Authors. All rights reserved. 4 // Use of this source code is governed by a BSD-style 5 // license that can be found in the LICENSE file. 6 7 // Run runs tests in the test directory. 8 // 9 // TODO(bradfitz): docs of some sort, once we figure out how we're changing 10 // headers of files 11 package main 12 13 import ( 14 "bytes" 15 "errors" 16 "flag" 17 "fmt" 18 "hash/fnv" 19 "io" 20 "io/ioutil" 21 "log" 22 "os" 23 "os/exec" 24 "path" 25 "path/filepath" 26 "regexp" 27 "runtime" 28 "sort" 29 "strconv" 30 "strings" 31 "time" 32 "unicode" 33 ) 34 35 var ( 36 verbose = flag.Bool("v", false, "verbose. if set, parallelism is set to 1.") 37 keep = flag.Bool("k", false, "keep. keep temporary directory.") 38 numParallel = flag.Int("n", runtime.NumCPU(), "number of parallel tests to run") 39 summary = flag.Bool("summary", false, "show summary of results") 40 showSkips = flag.Bool("show_skips", false, "show skipped tests") 41 runSkips = flag.Bool("run_skips", false, "run skipped tests (ignore skip and build tags)") 42 linkshared = flag.Bool("linkshared", false, "") 43 updateErrors = flag.Bool("update_errors", false, "update error messages in test file based on compiler output") 44 runoutputLimit = flag.Int("l", defaultRunOutputLimit(), "number of parallel runoutput tests to run") 45 46 shard = flag.Int("shard", 0, "shard index to run. Only applicable if -shards is non-zero.") 47 shards = flag.Int("shards", 0, "number of shards. If 0, all tests are run. This is used by the continuous build.") 48 ) 49 50 var ( 51 goos, goarch string 52 53 // dirs are the directories to look for *.go files in. 54 // TODO(bradfitz): just use all directories? 55 dirs = []string{".", "ken", "chan", "interface", "syntax", "dwarf", "fixedbugs"} 56 57 // ratec controls the max number of tests running at a time. 58 ratec chan bool 59 60 // toRun is the channel of tests to run. 61 // It is nil until the first test is started. 62 toRun chan *test 63 64 // rungatec controls the max number of runoutput tests 65 // executed in parallel as they can each consume a lot of memory. 66 rungatec chan bool 67 ) 68 69 // maxTests is an upper bound on the total number of tests. 70 // It is used as a channel buffer size to make sure sends don't block. 71 const maxTests = 5000 72 73 func main() { 74 flag.Parse() 75 76 goos = getenv("GOOS", runtime.GOOS) 77 goarch = getenv("GOARCH", runtime.GOARCH) 78 79 findExecCmd() 80 81 // Disable parallelism if printing or if using a simulator. 82 if *verbose || len(findExecCmd()) > 0 { 83 *numParallel = 1 84 } 85 86 ratec = make(chan bool, *numParallel) 87 rungatec = make(chan bool, *runoutputLimit) 88 89 var tests []*test 90 if flag.NArg() > 0 { 91 for _, arg := range flag.Args() { 92 if arg == "-" || arg == "--" { 93 // Permit running: 94 // $ go run run.go - env.go 95 // $ go run run.go -- env.go 96 // $ go run run.go - ./fixedbugs 97 // $ go run run.go -- ./fixedbugs 98 continue 99 } 100 if fi, err := os.Stat(arg); err == nil && fi.IsDir() { 101 for _, baseGoFile := range goFiles(arg) { 102 tests = append(tests, startTest(arg, baseGoFile)) 103 } 104 } else if strings.HasSuffix(arg, ".go") { 105 dir, file := filepath.Split(arg) 106 tests = append(tests, startTest(dir, file)) 107 } else { 108 log.Fatalf("can't yet deal with non-directory and non-go file %q", arg) 109 } 110 } 111 } else { 112 for _, dir := range dirs { 113 for _, baseGoFile := range goFiles(dir) { 114 tests = append(tests, startTest(dir, baseGoFile)) 115 } 116 } 117 } 118 119 failed := false 120 resCount := map[string]int{} 121 for _, test := range tests { 122 <-test.donec 123 status := "ok " 124 errStr := "" 125 if e, isSkip := test.err.(skipError); isSkip { 126 test.err = nil 127 errStr = "unexpected skip for " + path.Join(test.dir, test.gofile) + ": " + string(e) 128 status = "FAIL" 129 } 130 if test.err != nil { 131 status = "FAIL" 132 errStr = test.err.Error() 133 } 134 if status == "FAIL" { 135 failed = true 136 } 137 resCount[status]++ 138 dt := fmt.Sprintf("%.3fs", test.dt.Seconds()) 139 if status == "FAIL" { 140 fmt.Printf("# go run run.go -- %s\n%s\nFAIL\t%s\t%s\n", 141 path.Join(test.dir, test.gofile), 142 errStr, test.goFileName(), dt) 143 continue 144 } 145 if !*verbose { 146 continue 147 } 148 fmt.Printf("%s\t%s\t%s\n", status, test.goFileName(), dt) 149 } 150 151 if *summary { 152 for k, v := range resCount { 153 fmt.Printf("%5d %s\n", v, k) 154 } 155 } 156 157 if failed { 158 os.Exit(1) 159 } 160 } 161 162 func toolPath(name string) string { 163 p := filepath.Join(os.Getenv("GOROOT"), "bin", "tool", name) 164 if _, err := os.Stat(p); err != nil { 165 log.Fatalf("didn't find binary at %s", p) 166 } 167 return p 168 } 169 170 func shardMatch(name string) bool { 171 if *shards == 0 { 172 return true 173 } 174 h := fnv.New32() 175 io.WriteString(h, name) 176 return int(h.Sum32()%uint32(*shards)) == *shard 177 } 178 179 func goFiles(dir string) []string { 180 f, err := os.Open(dir) 181 check(err) 182 dirnames, err := f.Readdirnames(-1) 183 check(err) 184 names := []string{} 185 for _, name := range dirnames { 186 if !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".go") && shardMatch(name) { 187 names = append(names, name) 188 } 189 } 190 sort.Strings(names) 191 return names 192 } 193 194 type runCmd func(...string) ([]byte, error) 195 196 func compileFile(runcmd runCmd, longname string) (out []byte, err error) { 197 cmd := []string{"go", "tool", "compile", "-e"} 198 if *linkshared { 199 cmd = append(cmd, "-dynlink", "-installsuffix=dynlink") 200 } 201 cmd = append(cmd, longname) 202 return runcmd(cmd...) 203 } 204 205 func compileInDir(runcmd runCmd, dir string, flags []string, names ...string) (out []byte, err error) { 206 cmd := []string{"go", "tool", "compile", "-e", "-D", ".", "-I", "."} 207 cmd = append(cmd, flags...) 208 if *linkshared { 209 cmd = append(cmd, "-dynlink", "-installsuffix=dynlink") 210 } 211 for _, name := range names { 212 cmd = append(cmd, filepath.Join(dir, name)) 213 } 214 return runcmd(cmd...) 215 } 216 217 func linkFile(runcmd runCmd, goname string) (err error) { 218 pfile := strings.Replace(goname, ".go", ".o", -1) 219 cmd := []string{"go", "tool", "link", "-w", "-o", "a.exe", "-L", "."} 220 if *linkshared { 221 cmd = append(cmd, "-linkshared", "-installsuffix=dynlink") 222 } 223 cmd = append(cmd, pfile) 224 _, err = runcmd(cmd...) 225 return 226 } 227 228 // skipError describes why a test was skipped. 229 type skipError string 230 231 func (s skipError) Error() string { return string(s) } 232 233 func check(err error) { 234 if err != nil { 235 log.Fatal(err) 236 } 237 } 238 239 // test holds the state of a test. 240 type test struct { 241 dir, gofile string 242 donec chan bool // closed when done 243 dt time.Duration 244 245 src string 246 247 tempDir string 248 err error 249 } 250 251 // startTest 252 func startTest(dir, gofile string) *test { 253 t := &test{ 254 dir: dir, 255 gofile: gofile, 256 donec: make(chan bool, 1), 257 } 258 if toRun == nil { 259 toRun = make(chan *test, maxTests) 260 go runTests() 261 } 262 select { 263 case toRun <- t: 264 default: 265 panic("toRun buffer size (maxTests) is too small") 266 } 267 return t 268 } 269 270 // runTests runs tests in parallel, but respecting the order they 271 // were enqueued on the toRun channel. 272 func runTests() { 273 for { 274 ratec <- true 275 t := <-toRun 276 go func() { 277 t.run() 278 <-ratec 279 }() 280 } 281 } 282 283 var cwd, _ = os.Getwd() 284 285 func (t *test) goFileName() string { 286 return filepath.Join(t.dir, t.gofile) 287 } 288 289 func (t *test) goDirName() string { 290 return filepath.Join(t.dir, strings.Replace(t.gofile, ".go", ".dir", -1)) 291 } 292 293 func goDirFiles(longdir string) (filter []os.FileInfo, err error) { 294 files, dirErr := ioutil.ReadDir(longdir) 295 if dirErr != nil { 296 return nil, dirErr 297 } 298 for _, gofile := range files { 299 if filepath.Ext(gofile.Name()) == ".go" { 300 filter = append(filter, gofile) 301 } 302 } 303 return 304 } 305 306 var packageRE = regexp.MustCompile(`(?m)^package (\w+)`) 307 308 // If singlefilepkgs is set, each file is considered a separate package 309 // even if the package names are the same. 310 func goDirPackages(longdir string, singlefilepkgs bool) ([][]string, error) { 311 files, err := goDirFiles(longdir) 312 if err != nil { 313 return nil, err 314 } 315 var pkgs [][]string 316 m := make(map[string]int) 317 for _, file := range files { 318 name := file.Name() 319 data, err := ioutil.ReadFile(filepath.Join(longdir, name)) 320 if err != nil { 321 return nil, err 322 } 323 pkgname := packageRE.FindStringSubmatch(string(data)) 324 if pkgname == nil { 325 return nil, fmt.Errorf("cannot find package name in %s", name) 326 } 327 i, ok := m[pkgname[1]] 328 if singlefilepkgs || !ok { 329 i = len(pkgs) 330 pkgs = append(pkgs, nil) 331 m[pkgname[1]] = i 332 } 333 pkgs[i] = append(pkgs[i], name) 334 } 335 return pkgs, nil 336 } 337 338 type context struct { 339 GOOS string 340 GOARCH string 341 } 342 343 // shouldTest looks for build tags in a source file and returns 344 // whether the file should be used according to the tags. 345 func shouldTest(src string, goos, goarch string) (ok bool, whyNot string) { 346 if *runSkips { 347 return true, "" 348 } 349 for _, line := range strings.Split(src, "\n") { 350 line = strings.TrimSpace(line) 351 if strings.HasPrefix(line, "//") { 352 line = line[2:] 353 } else { 354 continue 355 } 356 line = strings.TrimSpace(line) 357 if len(line) == 0 || line[0] != '+' { 358 continue 359 } 360 ctxt := &context{ 361 GOOS: goos, 362 GOARCH: goarch, 363 } 364 words := strings.Fields(line) 365 if words[0] == "+build" { 366 ok := false 367 for _, word := range words[1:] { 368 if ctxt.match(word) { 369 ok = true 370 break 371 } 372 } 373 if !ok { 374 // no matching tag found. 375 return false, line 376 } 377 } 378 } 379 // no build tags 380 return true, "" 381 } 382 383 func (ctxt *context) match(name string) bool { 384 if name == "" { 385 return false 386 } 387 if i := strings.Index(name, ","); i >= 0 { 388 // comma-separated list 389 return ctxt.match(name[:i]) && ctxt.match(name[i+1:]) 390 } 391 if strings.HasPrefix(name, "!!") { // bad syntax, reject always 392 return false 393 } 394 if strings.HasPrefix(name, "!") { // negation 395 return len(name) > 1 && !ctxt.match(name[1:]) 396 } 397 398 // Tags must be letters, digits, underscores or dots. 399 // Unlike in Go identifiers, all digits are fine (e.g., "386"). 400 for _, c := range name { 401 if !unicode.IsLetter(c) && !unicode.IsDigit(c) && c != '_' && c != '.' { 402 return false 403 } 404 } 405 406 if name == ctxt.GOOS || name == ctxt.GOARCH { 407 return true 408 } 409 410 if name == "test_run" { 411 return true 412 } 413 414 return false 415 } 416 417 func init() { checkShouldTest() } 418 419 // run runs a test. 420 func (t *test) run() { 421 start := time.Now() 422 defer func() { 423 t.dt = time.Since(start) 424 close(t.donec) 425 }() 426 427 srcBytes, err := ioutil.ReadFile(t.goFileName()) 428 if err != nil { 429 t.err = err 430 return 431 } 432 t.src = string(srcBytes) 433 if t.src[0] == '\n' { 434 t.err = skipError("starts with newline") 435 return 436 } 437 438 // Execution recipe stops at first blank line. 439 pos := strings.Index(t.src, "\n\n") 440 if pos == -1 { 441 t.err = errors.New("double newline not found") 442 return 443 } 444 action := t.src[:pos] 445 if nl := strings.Index(action, "\n"); nl >= 0 && strings.Contains(action[:nl], "+build") { 446 // skip first line 447 action = action[nl+1:] 448 } 449 if strings.HasPrefix(action, "//") { 450 action = action[2:] 451 } 452 453 // Check for build constraints only up to the actual code. 454 pkgPos := strings.Index(t.src, "\npackage") 455 if pkgPos == -1 { 456 pkgPos = pos // some files are intentionally malformed 457 } 458 if ok, why := shouldTest(t.src[:pkgPos], goos, goarch); !ok { 459 if *showSkips { 460 fmt.Printf("%-20s %-20s: %s\n", "skip", t.goFileName(), why) 461 } 462 return 463 } 464 465 var args, flags []string 466 var tim int 467 wantError := false 468 wantAuto := false 469 singlefilepkgs := false 470 f := strings.Fields(action) 471 if len(f) > 0 { 472 action = f[0] 473 args = f[1:] 474 } 475 476 // TODO: Clean up/simplify this switch statement. 477 switch action { 478 case "rundircmpout": 479 action = "rundir" 480 case "cmpout": 481 action = "run" // the run case already looks for <dir>/<test>.out files 482 case "compile", "compiledir", "build", "run", "buildrun", "runoutput", "rundir": 483 // nothing to do 484 case "errorcheckandrundir": 485 wantError = false // should be no error if also will run 486 case "errorcheckwithauto": 487 action = "errorcheck" 488 wantAuto = true 489 wantError = true 490 case "errorcheck", "errorcheckdir", "errorcheckoutput": 491 wantError = true 492 case "skip": 493 if *runSkips { 494 break 495 } 496 return 497 default: 498 t.err = skipError("skipped; unknown pattern: " + action) 499 return 500 } 501 502 // collect flags 503 for len(args) > 0 && strings.HasPrefix(args[0], "-") { 504 switch args[0] { 505 case "-0": 506 wantError = false 507 case "-s": 508 singlefilepkgs = true 509 case "-t": // timeout in seconds 510 args = args[1:] 511 var err error 512 tim, err = strconv.Atoi(args[0]) 513 if err != nil { 514 t.err = fmt.Errorf("need number of seconds for -t timeout, got %s instead", args[0]) 515 } 516 517 default: 518 flags = append(flags, args[0]) 519 } 520 args = args[1:] 521 } 522 523 t.makeTempDir() 524 if !*keep { 525 defer os.RemoveAll(t.tempDir) 526 } 527 528 err = ioutil.WriteFile(filepath.Join(t.tempDir, t.gofile), srcBytes, 0644) 529 check(err) 530 531 // A few tests (of things like the environment) require these to be set. 532 if os.Getenv("GOOS") == "" { 533 os.Setenv("GOOS", runtime.GOOS) 534 } 535 if os.Getenv("GOARCH") == "" { 536 os.Setenv("GOARCH", runtime.GOARCH) 537 } 538 539 useTmp := true 540 runcmd := func(args ...string) ([]byte, error) { 541 cmd := exec.Command(args[0], args[1:]...) 542 var buf bytes.Buffer 543 cmd.Stdout = &buf 544 cmd.Stderr = &buf 545 if useTmp { 546 cmd.Dir = t.tempDir 547 cmd.Env = envForDir(cmd.Dir) 548 } else { 549 cmd.Env = os.Environ() 550 } 551 552 var err error 553 554 if tim != 0 { 555 err = cmd.Start() 556 // This command-timeout code adapted from cmd/go/test.go 557 if err == nil { 558 tick := time.NewTimer(time.Duration(tim) * time.Second) 559 done := make(chan error) 560 go func() { 561 done <- cmd.Wait() 562 }() 563 select { 564 case err = <-done: 565 // ok 566 case <-tick.C: 567 cmd.Process.Kill() 568 err = <-done 569 // err = errors.New("Test timeout") 570 } 571 tick.Stop() 572 } 573 } else { 574 err = cmd.Run() 575 } 576 if err != nil { 577 err = fmt.Errorf("%s\n%s", err, buf.Bytes()) 578 } 579 return buf.Bytes(), err 580 } 581 582 long := filepath.Join(cwd, t.goFileName()) 583 switch action { 584 default: 585 t.err = fmt.Errorf("unimplemented action %q", action) 586 587 case "errorcheck": 588 cmdline := []string{"go", "tool", "compile", "-e", "-o", "a.o"} 589 // No need to add -dynlink even if linkshared if we're just checking for errors... 590 cmdline = append(cmdline, flags...) 591 cmdline = append(cmdline, long) 592 out, err := runcmd(cmdline...) 593 if wantError { 594 if err == nil { 595 t.err = fmt.Errorf("compilation succeeded unexpectedly\n%s", out) 596 return 597 } 598 } else { 599 if err != nil { 600 t.err = err 601 return 602 } 603 } 604 if *updateErrors { 605 t.updateErrors(string(out), long) 606 } 607 t.err = t.errorCheck(string(out), wantAuto, long, t.gofile) 608 return 609 610 case "compile": 611 _, t.err = compileFile(runcmd, long) 612 613 case "compiledir": 614 // Compile all files in the directory in lexicographic order. 615 longdir := filepath.Join(cwd, t.goDirName()) 616 pkgs, err := goDirPackages(longdir, singlefilepkgs) 617 if err != nil { 618 t.err = err 619 return 620 } 621 for _, gofiles := range pkgs { 622 _, t.err = compileInDir(runcmd, longdir, flags, gofiles...) 623 if t.err != nil { 624 return 625 } 626 } 627 628 case "errorcheckdir", "errorcheckandrundir": 629 // errorcheck all files in lexicographic order 630 // useful for finding importing errors 631 longdir := filepath.Join(cwd, t.goDirName()) 632 pkgs, err := goDirPackages(longdir, singlefilepkgs) 633 if err != nil { 634 t.err = err 635 return 636 } 637 for i, gofiles := range pkgs { 638 out, err := compileInDir(runcmd, longdir, flags, gofiles...) 639 if i == len(pkgs)-1 { 640 if wantError && err == nil { 641 t.err = fmt.Errorf("compilation succeeded unexpectedly\n%s", out) 642 return 643 } else if !wantError && err != nil { 644 t.err = err 645 return 646 } 647 } else if err != nil { 648 t.err = err 649 return 650 } 651 var fullshort []string 652 for _, name := range gofiles { 653 fullshort = append(fullshort, filepath.Join(longdir, name), name) 654 } 655 t.err = t.errorCheck(string(out), wantAuto, fullshort...) 656 if t.err != nil { 657 break 658 } 659 } 660 if action == "errorcheckdir" { 661 return 662 } 663 fallthrough 664 665 case "rundir": 666 // Compile all files in the directory in lexicographic order. 667 // then link as if the last file is the main package and run it 668 longdir := filepath.Join(cwd, t.goDirName()) 669 pkgs, err := goDirPackages(longdir, singlefilepkgs) 670 if err != nil { 671 t.err = err 672 return 673 } 674 for i, gofiles := range pkgs { 675 _, err := compileInDir(runcmd, longdir, flags, gofiles...) 676 if err != nil { 677 t.err = err 678 return 679 } 680 if i == len(pkgs)-1 { 681 err = linkFile(runcmd, gofiles[0]) 682 if err != nil { 683 t.err = err 684 return 685 } 686 var cmd []string 687 cmd = append(cmd, findExecCmd()...) 688 cmd = append(cmd, filepath.Join(t.tempDir, "a.exe")) 689 cmd = append(cmd, args...) 690 out, err := runcmd(cmd...) 691 if err != nil { 692 t.err = err 693 return 694 } 695 if strings.Replace(string(out), "\r\n", "\n", -1) != t.expectedOutput() { 696 t.err = fmt.Errorf("incorrect output\n%s", out) 697 } 698 } 699 } 700 701 case "build": 702 _, err := runcmd("go", "build", "-o", "a.exe", long) 703 if err != nil { 704 t.err = err 705 } 706 707 case "buildrun": // build binary, then run binary, instead of go run. Useful for timeout tests where failure mode is infinite loop. 708 // TODO: not supported on NaCl 709 useTmp = true 710 cmd := []string{"go", "build", "-o", "a.exe"} 711 if *linkshared { 712 cmd = append(cmd, "-linkshared") 713 } 714 longdirgofile := filepath.Join(filepath.Join(cwd, t.dir), t.gofile) 715 cmd = append(cmd, flags...) 716 cmd = append(cmd, longdirgofile) 717 out, err := runcmd(cmd...) 718 if err != nil { 719 t.err = err 720 return 721 } 722 cmd = []string{"./a.exe"} 723 out, err = runcmd(append(cmd, args...)...) 724 if err != nil { 725 t.err = err 726 return 727 } 728 729 if strings.Replace(string(out), "\r\n", "\n", -1) != t.expectedOutput() { 730 t.err = fmt.Errorf("incorrect output\n%s", out) 731 } 732 733 case "run": 734 useTmp = false 735 cmd := []string{"go", "run"} 736 if *linkshared { 737 cmd = append(cmd, "-linkshared") 738 } 739 cmd = append(cmd, t.goFileName()) 740 out, err := runcmd(append(cmd, args...)...) 741 if err != nil { 742 t.err = err 743 return 744 } 745 if strings.Replace(string(out), "\r\n", "\n", -1) != t.expectedOutput() { 746 t.err = fmt.Errorf("incorrect output\n%s", out) 747 } 748 749 case "runoutput": 750 rungatec <- true 751 defer func() { 752 <-rungatec 753 }() 754 useTmp = false 755 cmd := []string{"go", "run"} 756 if *linkshared { 757 cmd = append(cmd, "-linkshared") 758 } 759 cmd = append(cmd, t.goFileName()) 760 out, err := runcmd(append(cmd, args...)...) 761 if err != nil { 762 t.err = err 763 return 764 } 765 tfile := filepath.Join(t.tempDir, "tmp__.go") 766 if err := ioutil.WriteFile(tfile, out, 0666); err != nil { 767 t.err = fmt.Errorf("write tempfile:%s", err) 768 return 769 } 770 cmd = []string{"go", "run"} 771 if *linkshared { 772 cmd = append(cmd, "-linkshared") 773 } 774 cmd = append(cmd, tfile) 775 out, err = runcmd(cmd...) 776 if err != nil { 777 t.err = err 778 return 779 } 780 if string(out) != t.expectedOutput() { 781 t.err = fmt.Errorf("incorrect output\n%s", out) 782 } 783 784 case "errorcheckoutput": 785 useTmp = false 786 cmd := []string{"go", "run"} 787 if *linkshared { 788 cmd = append(cmd, "-linkshared") 789 } 790 cmd = append(cmd, t.goFileName()) 791 out, err := runcmd(append(cmd, args...)...) 792 if err != nil { 793 t.err = err 794 return 795 } 796 tfile := filepath.Join(t.tempDir, "tmp__.go") 797 err = ioutil.WriteFile(tfile, out, 0666) 798 if err != nil { 799 t.err = fmt.Errorf("write tempfile:%s", err) 800 return 801 } 802 cmdline := []string{"go", "tool", "compile", "-e", "-o", "a.o"} 803 cmdline = append(cmdline, flags...) 804 cmdline = append(cmdline, tfile) 805 out, err = runcmd(cmdline...) 806 if wantError { 807 if err == nil { 808 t.err = fmt.Errorf("compilation succeeded unexpectedly\n%s", out) 809 return 810 } 811 } else { 812 if err != nil { 813 t.err = err 814 return 815 } 816 } 817 t.err = t.errorCheck(string(out), false, tfile, "tmp__.go") 818 return 819 } 820 } 821 822 var execCmd []string 823 824 func findExecCmd() []string { 825 if execCmd != nil { 826 return execCmd 827 } 828 execCmd = []string{} // avoid work the second time 829 if goos == runtime.GOOS && goarch == runtime.GOARCH { 830 return execCmd 831 } 832 path, err := exec.LookPath(fmt.Sprintf("go_%s_%s_exec", goos, goarch)) 833 if err == nil { 834 execCmd = []string{path} 835 } 836 return execCmd 837 } 838 839 func (t *test) String() string { 840 return filepath.Join(t.dir, t.gofile) 841 } 842 843 func (t *test) makeTempDir() { 844 var err error 845 t.tempDir, err = ioutil.TempDir("", "") 846 check(err) 847 if *keep { 848 log.Printf("Temporary directory is %s", t.tempDir) 849 } 850 } 851 852 func (t *test) expectedOutput() string { 853 filename := filepath.Join(t.dir, t.gofile) 854 filename = filename[:len(filename)-len(".go")] 855 filename += ".out" 856 b, _ := ioutil.ReadFile(filename) 857 return string(b) 858 } 859 860 func splitOutput(out string, wantAuto bool) []string { 861 // gc error messages continue onto additional lines with leading tabs. 862 // Split the output at the beginning of each line that doesn't begin with a tab. 863 // <autogenerated> lines are impossible to match so those are filtered out. 864 var res []string 865 for _, line := range strings.Split(out, "\n") { 866 if strings.HasSuffix(line, "\r") { // remove '\r', output by compiler on windows 867 line = line[:len(line)-1] 868 } 869 if strings.HasPrefix(line, "\t") { 870 res[len(res)-1] += "\n" + line 871 } else if strings.HasPrefix(line, "go tool") || strings.HasPrefix(line, "#") || !wantAuto && strings.HasPrefix(line, "<autogenerated>") { 872 continue 873 } else if strings.TrimSpace(line) != "" { 874 res = append(res, line) 875 } 876 } 877 return res 878 } 879 880 func (t *test) errorCheck(outStr string, wantAuto bool, fullshort ...string) (err error) { 881 defer func() { 882 if *verbose && err != nil { 883 log.Printf("%s gc output:\n%s", t, outStr) 884 } 885 }() 886 var errs []error 887 out := splitOutput(outStr, wantAuto) 888 889 // Cut directory name. 890 for i := range out { 891 for j := 0; j < len(fullshort); j += 2 { 892 full, short := fullshort[j], fullshort[j+1] 893 out[i] = strings.Replace(out[i], full, short, -1) 894 } 895 } 896 897 var want []wantedError 898 for j := 0; j < len(fullshort); j += 2 { 899 full, short := fullshort[j], fullshort[j+1] 900 want = append(want, t.wantedErrors(full, short)...) 901 } 902 903 for _, we := range want { 904 var errmsgs []string 905 if we.auto { 906 errmsgs, out = partitionStrings("<autogenerated>", out) 907 } else { 908 errmsgs, out = partitionStrings(we.prefix, out) 909 } 910 if len(errmsgs) == 0 { 911 errs = append(errs, fmt.Errorf("%s:%d: missing error %q", we.file, we.lineNum, we.reStr)) 912 continue 913 } 914 matched := false 915 n := len(out) 916 for _, errmsg := range errmsgs { 917 // Assume errmsg says "file:line: foo". 918 // Cut leading "file:line: " to avoid accidental matching of file name instead of message. 919 text := errmsg 920 if i := strings.Index(text, " "); i >= 0 { 921 text = text[i+1:] 922 } 923 if we.re.MatchString(text) { 924 matched = true 925 } else { 926 out = append(out, errmsg) 927 } 928 } 929 if !matched { 930 errs = append(errs, fmt.Errorf("%s:%d: no match for %#q in:\n\t%s", we.file, we.lineNum, we.reStr, strings.Join(out[n:], "\n\t"))) 931 continue 932 } 933 } 934 935 if len(out) > 0 { 936 errs = append(errs, fmt.Errorf("Unmatched Errors:")) 937 for _, errLine := range out { 938 errs = append(errs, fmt.Errorf("%s", errLine)) 939 } 940 } 941 942 if len(errs) == 0 { 943 return nil 944 } 945 if len(errs) == 1 { 946 return errs[0] 947 } 948 var buf bytes.Buffer 949 fmt.Fprintf(&buf, "\n") 950 for _, err := range errs { 951 fmt.Fprintf(&buf, "%s\n", err.Error()) 952 } 953 return errors.New(buf.String()) 954 } 955 956 func (t *test) updateErrors(out, file string) { 957 base := path.Base(file) 958 // Read in source file. 959 src, err := ioutil.ReadFile(file) 960 if err != nil { 961 fmt.Fprintln(os.Stderr, err) 962 return 963 } 964 lines := strings.Split(string(src), "\n") 965 // Remove old errors. 966 for i, ln := range lines { 967 pos := strings.Index(ln, " // ERROR ") 968 if pos >= 0 { 969 lines[i] = ln[:pos] 970 } 971 } 972 // Parse new errors. 973 errors := make(map[int]map[string]bool) 974 tmpRe := regexp.MustCompile(`autotmp_[0-9]+`) 975 for _, errStr := range splitOutput(out, false) { 976 colon1 := strings.Index(errStr, ":") 977 if colon1 < 0 || errStr[:colon1] != file { 978 continue 979 } 980 colon2 := strings.Index(errStr[colon1+1:], ":") 981 if colon2 < 0 { 982 continue 983 } 984 colon2 += colon1 + 1 985 line, err := strconv.Atoi(errStr[colon1+1 : colon2]) 986 line-- 987 if err != nil || line < 0 || line >= len(lines) { 988 continue 989 } 990 msg := errStr[colon2+2:] 991 msg = strings.Replace(msg, file, base, -1) // normalize file mentions in error itself 992 msg = strings.TrimLeft(msg, " \t") 993 for _, r := range []string{`\`, `*`, `+`, `[`, `]`, `(`, `)`} { 994 msg = strings.Replace(msg, r, `\`+r, -1) 995 } 996 msg = strings.Replace(msg, `"`, `.`, -1) 997 msg = tmpRe.ReplaceAllLiteralString(msg, `autotmp_[0-9]+`) 998 if errors[line] == nil { 999 errors[line] = make(map[string]bool) 1000 } 1001 errors[line][msg] = true 1002 } 1003 // Add new errors. 1004 for line, errs := range errors { 1005 var sorted []string 1006 for e := range errs { 1007 sorted = append(sorted, e) 1008 } 1009 sort.Strings(sorted) 1010 lines[line] += " // ERROR" 1011 for _, e := range sorted { 1012 lines[line] += fmt.Sprintf(` "%s$"`, e) 1013 } 1014 } 1015 // Write new file. 1016 err = ioutil.WriteFile(file, []byte(strings.Join(lines, "\n")), 0640) 1017 if err != nil { 1018 fmt.Fprintln(os.Stderr, err) 1019 return 1020 } 1021 // Polish. 1022 exec.Command("go", "fmt", file).CombinedOutput() 1023 } 1024 1025 // matchPrefix reports whether s is of the form ^(.*/)?prefix(:|[), 1026 // That is, it needs the file name prefix followed by a : or a [, 1027 // and possibly preceded by a directory name. 1028 func matchPrefix(s, prefix string) bool { 1029 i := strings.Index(s, ":") 1030 if i < 0 { 1031 return false 1032 } 1033 j := strings.LastIndex(s[:i], "/") 1034 s = s[j+1:] 1035 if len(s) <= len(prefix) || s[:len(prefix)] != prefix { 1036 return false 1037 } 1038 switch s[len(prefix)] { 1039 case '[', ':': 1040 return true 1041 } 1042 return false 1043 } 1044 1045 func partitionStrings(prefix string, strs []string) (matched, unmatched []string) { 1046 for _, s := range strs { 1047 if matchPrefix(s, prefix) { 1048 matched = append(matched, s) 1049 } else { 1050 unmatched = append(unmatched, s) 1051 } 1052 } 1053 return 1054 } 1055 1056 type wantedError struct { 1057 reStr string 1058 re *regexp.Regexp 1059 lineNum int 1060 auto bool // match <autogenerated> line 1061 file string 1062 prefix string 1063 } 1064 1065 var ( 1066 errRx = regexp.MustCompile(`// (?:GC_)?ERROR (.*)`) 1067 errAutoRx = regexp.MustCompile(`// (?:GC_)?ERRORAUTO (.*)`) 1068 errQuotesRx = regexp.MustCompile(`"([^"]*)"`) 1069 lineRx = regexp.MustCompile(`LINE(([+-])([0-9]+))?`) 1070 ) 1071 1072 func (t *test) wantedErrors(file, short string) (errs []wantedError) { 1073 cache := make(map[string]*regexp.Regexp) 1074 1075 src, _ := ioutil.ReadFile(file) 1076 for i, line := range strings.Split(string(src), "\n") { 1077 lineNum := i + 1 1078 if strings.Contains(line, "////") { 1079 // double comment disables ERROR 1080 continue 1081 } 1082 var auto bool 1083 m := errAutoRx.FindStringSubmatch(line) 1084 if m != nil { 1085 auto = true 1086 } else { 1087 m = errRx.FindStringSubmatch(line) 1088 } 1089 if m == nil { 1090 continue 1091 } 1092 all := m[1] 1093 mm := errQuotesRx.FindAllStringSubmatch(all, -1) 1094 if mm == nil { 1095 log.Fatalf("%s:%d: invalid errchk line: %s", t.goFileName(), lineNum, line) 1096 } 1097 for _, m := range mm { 1098 rx := lineRx.ReplaceAllStringFunc(m[1], func(m string) string { 1099 n := lineNum 1100 if strings.HasPrefix(m, "LINE+") { 1101 delta, _ := strconv.Atoi(m[5:]) 1102 n += delta 1103 } else if strings.HasPrefix(m, "LINE-") { 1104 delta, _ := strconv.Atoi(m[5:]) 1105 n -= delta 1106 } 1107 return fmt.Sprintf("%s:%d", short, n) 1108 }) 1109 re := cache[rx] 1110 if re == nil { 1111 var err error 1112 re, err = regexp.Compile(rx) 1113 if err != nil { 1114 log.Fatalf("%s:%d: invalid regexp \"%s\" in ERROR line: %v", t.goFileName(), lineNum, rx, err) 1115 } 1116 cache[rx] = re 1117 } 1118 prefix := fmt.Sprintf("%s:%d", short, lineNum) 1119 errs = append(errs, wantedError{ 1120 reStr: rx, 1121 re: re, 1122 prefix: prefix, 1123 auto: auto, 1124 lineNum: lineNum, 1125 file: short, 1126 }) 1127 } 1128 } 1129 1130 return 1131 } 1132 1133 // defaultRunOutputLimit returns the number of runoutput tests that 1134 // can be executed in parallel. 1135 func defaultRunOutputLimit() int { 1136 const maxArmCPU = 2 1137 1138 cpu := runtime.NumCPU() 1139 if runtime.GOARCH == "arm" && cpu > maxArmCPU { 1140 cpu = maxArmCPU 1141 } 1142 return cpu 1143 } 1144 1145 // checkShouldTest runs sanity checks on the shouldTest function. 1146 func checkShouldTest() { 1147 assert := func(ok bool, _ string) { 1148 if !ok { 1149 panic("fail") 1150 } 1151 } 1152 assertNot := func(ok bool, _ string) { assert(!ok, "") } 1153 1154 // Simple tests. 1155 assert(shouldTest("// +build linux", "linux", "arm")) 1156 assert(shouldTest("// +build !windows", "linux", "arm")) 1157 assertNot(shouldTest("// +build !windows", "windows", "amd64")) 1158 1159 // A file with no build tags will always be tested. 1160 assert(shouldTest("// This is a test.", "os", "arch")) 1161 1162 // Build tags separated by a space are OR-ed together. 1163 assertNot(shouldTest("// +build arm 386", "linux", "amd64")) 1164 1165 // Build tags separated by a comma are AND-ed together. 1166 assertNot(shouldTest("// +build !windows,!plan9", "windows", "amd64")) 1167 assertNot(shouldTest("// +build !windows,!plan9", "plan9", "386")) 1168 1169 // Build tags on multiple lines are AND-ed together. 1170 assert(shouldTest("// +build !windows\n// +build amd64", "linux", "amd64")) 1171 assertNot(shouldTest("// +build !windows\n// +build amd64", "windows", "amd64")) 1172 1173 // Test that (!a OR !b) matches anything. 1174 assert(shouldTest("// +build !windows !plan9", "windows", "amd64")) 1175 } 1176 1177 // envForDir returns a copy of the environment 1178 // suitable for running in the given directory. 1179 // The environment is the current process's environment 1180 // but with an updated $PWD, so that an os.Getwd in the 1181 // child will be faster. 1182 func envForDir(dir string) []string { 1183 env := os.Environ() 1184 for i, kv := range env { 1185 if strings.HasPrefix(kv, "PWD=") { 1186 env[i] = "PWD=" + dir 1187 return env 1188 } 1189 } 1190 env = append(env, "PWD="+dir) 1191 return env 1192 } 1193 1194 func getenv(key, def string) string { 1195 value := os.Getenv(key) 1196 if value != "" { 1197 return value 1198 } 1199 return def 1200 }