testing.go 22 KB

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