github.com/fjballest/golang@v0.0.0-20151209143359-e4c5fe594ca8/src/testing/testing.go (about)

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