...
Run Format

Source file src/testing/testing.go

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

View as plain text