...

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 does not start with a lowercase letter. The function name
    10	// 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	// A simple test function looks like this:
    21	//
    22	//     func TestAbs(t *testing.T) {
    23	//         got := Abs(-1)
    24	//         if got != 1 {
    25	//             t.Errorf("Abs(-1) = %d; want 1", got)
    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-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	// The comment prefix "Unordered output:" is like "Output:", but matches any
    99	// line order:
   100	//
   101	//     func ExamplePerm() {
   102	//         for _, value := range Perm(4) {
   103	//             fmt.Println(value)
   104	//         }
   105	//         // Unordered output: 4
   106	//         // 2
   107	//         // 1
   108	//         // 3
   109	//         // 0
   110	//     }
   111	//
   112	// Example functions without output comments are compiled but not executed.
   113	//
   114	// The naming convention to declare examples for the package, a function F, a type T and
   115	// method M on type T are:
   116	//
   117	//     func Example() { ... }
   118	//     func ExampleF() { ... }
   119	//     func ExampleT() { ... }
   120	//     func ExampleT_M() { ... }
   121	//
   122	// Multiple example functions for a package/type/function/method may be provided by
   123	// appending a distinct suffix to the name. The suffix must start with a
   124	// lower-case letter.
   125	//
   126	//     func Example_suffix() { ... }
   127	//     func ExampleF_suffix() { ... }
   128	//     func ExampleT_suffix() { ... }
   129	//     func ExampleT_M_suffix() { ... }
   130	//
   131	// The entire test file is presented as the example when it contains a single
   132	// example function, at least one other function, type, variable, or constant
   133	// declaration, and no test or benchmark functions.
   134	//
   135	// Skipping
   136	//
   137	// Tests or benchmarks may be skipped at run time with a call to
   138	// the Skip method of *T or *B:
   139	//
   140	//     func TestTimeConsuming(t *testing.T) {
   141	//         if testing.Short() {
   142	//             t.Skip("skipping test in short mode.")
   143	//         }
   144	//         ...
   145	//     }
   146	//
   147	// Subtests and Sub-benchmarks
   148	//
   149	// The Run methods of T and B allow defining subtests and sub-benchmarks,
   150	// without having to define separate functions for each. This enables uses
   151	// like table-driven benchmarks and creating hierarchical tests.
   152	// It also provides a way to share common setup and tear-down code:
   153	//
   154	//     func TestFoo(t *testing.T) {
   155	//         // <setup code>
   156	//         t.Run("A=1", func(t *testing.T) { ... })
   157	//         t.Run("A=2", func(t *testing.T) { ... })
   158	//         t.Run("B=1", func(t *testing.T) { ... })
   159	//         // <tear-down code>
   160	//     }
   161	//
   162	// Each subtest and sub-benchmark has a unique name: the combination of the name
   163	// of the top-level test and the sequence of names passed to Run, separated by
   164	// slashes, with an optional trailing sequence number for disambiguation.
   165	//
   166	// The argument to the -run and -bench command-line flags is an unanchored regular
   167	// expression that matches the test's name. For tests with multiple slash-separated
   168	// elements, such as subtests, the argument is itself slash-separated, with
   169	// expressions matching each name element in turn. Because it is unanchored, an
   170	// empty expression matches any string.
   171	// For example, using "matching" to mean "whose name contains":
   172	//
   173	//     go test -run ''      # Run all tests.
   174	//     go test -run Foo     # Run top-level tests matching "Foo", such as "TestFooBar".
   175	//     go test -run Foo/A=  # For top-level tests matching "Foo", run subtests matching "A=".
   176	//     go test -run /A=1    # For all top-level tests, run subtests matching "A=1".
   177	//
   178	// Subtests can also be used to control parallelism. A parent test will only
   179	// complete once all of its subtests complete. In this example, all tests are
   180	// run in parallel with each other, and only with each other, regardless of
   181	// other top-level tests that may be defined:
   182	//
   183	//     func TestGroupedParallel(t *testing.T) {
   184	//         for _, tc := range tests {
   185	//             tc := tc // capture range variable
   186	//             t.Run(tc.Name, func(t *testing.T) {
   187	//                 t.Parallel()
   188	//                 ...
   189	//             })
   190	//         }
   191	//     }
   192	//
   193	// The race detector kills the program if it exceeds 8192 concurrent goroutines,
   194	// so use care when running parallel tests with the -race flag set.
   195	//
   196	// Run does not return until parallel subtests have completed, providing a way
   197	// to clean up after a group of parallel tests:
   198	//
   199	//     func TestTeardownParallel(t *testing.T) {
   200	//         // This Run will not return until the parallel tests finish.
   201	//         t.Run("group", func(t *testing.T) {
   202	//             t.Run("Test1", parallelTest1)
   203	//             t.Run("Test2", parallelTest2)
   204	//             t.Run("Test3", parallelTest3)
   205	//         })
   206	//         // <tear-down code>
   207	//     }
   208	//
   209	// Main
   210	//
   211	// It is sometimes necessary for a test program to do extra setup or teardown
   212	// before or after testing. It is also sometimes necessary for a test to control
   213	// which code runs on the main thread. To support these and other cases,
   214	// if a test file contains a function:
   215	//
   216	//	func TestMain(m *testing.M)
   217	//
   218	// then the generated test will call TestMain(m) instead of running the tests
   219	// directly. TestMain runs in the main goroutine and can do whatever setup
   220	// and teardown is necessary around a call to m.Run. It should then call
   221	// os.Exit with the result of m.Run. When TestMain is called, flag.Parse has
   222	// not been run. If TestMain depends on command-line flags, including those
   223	// of the testing package, it should call flag.Parse explicitly.
   224	//
   225	// A simple implementation of TestMain is:
   226	//
   227	//	func TestMain(m *testing.M) {
   228	//		// call flag.Parse() here if TestMain uses flags
   229	//		os.Exit(m.Run())
   230	//	}
   231	//
   232	package testing
   233	
   234	import (
   235		"bytes"
   236		"errors"
   237		"flag"
   238		"fmt"
   239		"internal/race"
   240		"io"
   241		"os"
   242		"runtime"
   243		"runtime/debug"
   244		"runtime/trace"
   245		"strconv"
   246		"strings"
   247		"sync"
   248		"sync/atomic"
   249		"time"
   250	)
   251	
   252	var initRan bool
   253	
   254	// Init registers testing flags. These flags are automatically registered by
   255	// the "go test" command before running test functions, so Init is only needed
   256	// when calling functions such as Benchmark without using "go test".
   257	//
   258	// Init has no effect if it was already called.
   259	func Init() {
   260		if initRan {
   261			return
   262		}
   263		initRan = true
   264		// The short flag requests that tests run more quickly, but its functionality
   265		// is provided by test writers themselves. The testing package is just its
   266		// home. The all.bash installation script sets it to make installation more
   267		// efficient, but by default the flag is off so a plain "go test" will do a
   268		// full test of the package.
   269		short = flag.Bool("test.short", false, "run smaller test suite to save time")
   270	
   271		// The failfast flag requests that test execution stop after the first test failure.
   272		failFast = flag.Bool("test.failfast", false, "do not start new tests after the first test failure")
   273	
   274		// The directory in which to create profile files and the like. When run from
   275		// "go test", the binary always runs in the source directory for the package;
   276		// this flag lets "go test" tell the binary to write the files in the directory where
   277		// the "go test" command is run.
   278		outputDir = flag.String("test.outputdir", "", "write profiles to `dir`")
   279		// Report as tests are run; default is silent for success.
   280		chatty = flag.Bool("test.v", false, "verbose: print additional output")
   281		count = flag.Uint("test.count", 1, "run tests and benchmarks `n` times")
   282		coverProfile = flag.String("test.coverprofile", "", "write a coverage profile to `file`")
   283		matchList = flag.String("test.list", "", "list tests, examples, and benchmarks matching `regexp` then exit")
   284		match = flag.String("test.run", "", "run only tests and examples matching `regexp`")
   285		memProfile = flag.String("test.memprofile", "", "write an allocation profile to `file`")
   286		memProfileRate = flag.Int("test.memprofilerate", 0, "set memory allocation profiling `rate` (see runtime.MemProfileRate)")
   287		cpuProfile = flag.String("test.cpuprofile", "", "write a cpu profile to `file`")
   288		blockProfile = flag.String("test.blockprofile", "", "write a goroutine blocking profile to `file`")
   289		blockProfileRate = flag.Int("test.blockprofilerate", 1, "set blocking profile `rate` (see runtime.SetBlockProfileRate)")
   290		mutexProfile = flag.String("test.mutexprofile", "", "write a mutex contention profile to the named file after execution")
   291		mutexProfileFraction = flag.Int("test.mutexprofilefraction", 1, "if >= 0, calls runtime.SetMutexProfileFraction()")
   292		traceFile = flag.String("test.trace", "", "write an execution trace to `file`")
   293		timeout = flag.Duration("test.timeout", 0, "panic test binary after duration `d` (default 0, timeout disabled)")
   294		cpuListStr = flag.String("test.cpu", "", "comma-separated `list` of cpu counts to run each test with")
   295		parallel = flag.Int("test.parallel", runtime.GOMAXPROCS(0), "run at most `n` tests in parallel")
   296		testlog = flag.String("test.testlogfile", "", "write test action log to `file` (for use only by cmd/go)")
   297	
   298		initBenchmarkFlags()
   299	}
   300	
   301	var (
   302		// Flags, registered during Init.
   303		short                *bool
   304		failFast             *bool
   305		outputDir            *string
   306		chatty               *bool
   307		count                *uint
   308		coverProfile         *string
   309		matchList            *string
   310		match                *string
   311		memProfile           *string
   312		memProfileRate       *int
   313		cpuProfile           *string
   314		blockProfile         *string
   315		blockProfileRate     *int
   316		mutexProfile         *string
   317		mutexProfileFraction *int
   318		traceFile            *string
   319		timeout              *time.Duration
   320		cpuListStr           *string
   321		parallel             *int
   322		testlog              *string
   323	
   324		haveExamples bool // are there examples?
   325	
   326		cpuList     []int
   327		testlogFile *os.File
   328	
   329		numFailed uint32 // number of test failures
   330	)
   331	
   332	// The maximum number of stack frames to go through when skipping helper functions for
   333	// the purpose of decorating log messages.
   334	const maxStackLen = 50
   335	
   336	// common holds the elements common between T and B and
   337	// captures common methods such as Errorf.
   338	type common struct {
   339		mu      sync.RWMutex        // guards this group of fields
   340		output  []byte              // Output generated by test or benchmark.
   341		w       io.Writer           // For flushToParent.
   342		ran     bool                // Test or benchmark (or one of its subtests) was executed.
   343		failed  bool                // Test or benchmark has failed.
   344		skipped bool                // Test of benchmark has been skipped.
   345		done    bool                // Test is finished and all subtests have completed.
   346		helpers map[string]struct{} // functions to be skipped when writing file/line info
   347	
   348		chatty     bool   // A copy of the chatty flag.
   349		finished   bool   // Test function has completed.
   350		hasSub     int32  // written atomically
   351		raceErrors int    // number of races detected during test
   352		runner     string // function name of tRunner running the test
   353	
   354		parent   *common
   355		level    int       // Nesting depth of test or benchmark.
   356		creator  []uintptr // If level > 0, the stack trace at the point where the parent called t.Run.
   357		name     string    // Name of test or benchmark.
   358		start    time.Time // Time test or benchmark started
   359		duration time.Duration
   360		barrier  chan bool // To signal parallel subtests they may start.
   361		signal   chan bool // To signal a test is done.
   362		sub      []*T      // Queue of subtests to be run in parallel.
   363	}
   364	
   365	// Short reports whether the -test.short flag is set.
   366	func Short() bool {
   367		if short == nil {
   368			panic("testing: Short called before Init")
   369		}
   370		// Catch code that calls this from TestMain without first calling flag.Parse.
   371		if !flag.Parsed() {
   372			panic("testing: Short called before Parse")
   373		}
   374	
   375		return *short
   376	}
   377	
   378	// CoverMode reports what the test coverage mode is set to. The
   379	// values are "set", "count", or "atomic". The return value will be
   380	// empty if test coverage is not enabled.
   381	func CoverMode() string {
   382		return cover.Mode
   383	}
   384	
   385	// Verbose reports whether the -test.v flag is set.
   386	func Verbose() bool {
   387		// Same as in Short.
   388		if chatty == nil {
   389			panic("testing: Verbose called before Init")
   390		}
   391		if !flag.Parsed() {
   392			panic("testing: Verbose called before Parse")
   393		}
   394		return *chatty
   395	}
   396	
   397	// frameSkip searches, starting after skip frames, for the first caller frame
   398	// in a function not marked as a helper and returns that frame.
   399	// The search stops if it finds a tRunner function that
   400	// was the entry point into the test and the test is not a subtest.
   401	// This function must be called with c.mu held.
   402	func (c *common) frameSkip(skip int) runtime.Frame {
   403		// If the search continues into the parent test, we'll have to hold
   404		// its mu temporarily. If we then return, we need to unlock it.
   405		shouldUnlock := false
   406		defer func() {
   407			if shouldUnlock {
   408				c.mu.Unlock()
   409			}
   410		}()
   411		var pc [maxStackLen]uintptr
   412		// Skip two extra frames to account for this function
   413		// and runtime.Callers itself.
   414		n := runtime.Callers(skip+2, pc[:])
   415		if n == 0 {
   416			panic("testing: zero callers found")
   417		}
   418		frames := runtime.CallersFrames(pc[:n])
   419		var firstFrame, prevFrame, frame runtime.Frame
   420		for more := true; more; prevFrame = frame {
   421			frame, more = frames.Next()
   422			if firstFrame.PC == 0 {
   423				firstFrame = frame
   424			}
   425			if frame.Function == c.runner {
   426				// We've gone up all the way to the tRunner calling
   427				// the test function (so the user must have
   428				// called tb.Helper from inside that test function).
   429				// If this is a top-level test, only skip up to the test function itself.
   430				// If we're in a subtest, continue searching in the parent test,
   431				// starting from the point of the call to Run which created this subtest.
   432				if c.level > 1 {
   433					frames = runtime.CallersFrames(c.creator)
   434					parent := c.parent
   435					// We're no longer looking at the current c after this point,
   436					// so we should unlock its mu, unless it's the original receiver,
   437					// in which case our caller doesn't expect us to do that.
   438					if shouldUnlock {
   439						c.mu.Unlock()
   440					}
   441					c = parent
   442					// Remember to unlock c.mu when we no longer need it, either
   443					// because we went up another nesting level, or because we
   444					// returned.
   445					shouldUnlock = true
   446					c.mu.Lock()
   447					continue
   448				}
   449				return prevFrame
   450			}
   451			if _, ok := c.helpers[frame.Function]; !ok {
   452				// Found a frame that wasn't inside a helper function.
   453				return frame
   454			}
   455		}
   456		return firstFrame
   457	}
   458	
   459	// decorate prefixes the string with the file and line of the call site
   460	// and inserts the final newline if needed and indentation spaces for formatting.
   461	// This function must be called with c.mu held.
   462	func (c *common) decorate(s string, skip int) string {
   463		frame := c.frameSkip(skip)
   464		file := frame.File
   465		line := frame.Line
   466		if file != "" {
   467			// Truncate file name at last file name separator.
   468			if index := strings.LastIndex(file, "/"); index >= 0 {
   469				file = file[index+1:]
   470			} else if index = strings.LastIndex(file, "\\"); index >= 0 {
   471				file = file[index+1:]
   472			}
   473		} else {
   474			file = "???"
   475		}
   476		if line == 0 {
   477			line = 1
   478		}
   479		buf := new(strings.Builder)
   480		// Every line is indented at least 4 spaces.
   481		buf.WriteString("    ")
   482		fmt.Fprintf(buf, "%s:%d: ", file, line)
   483		lines := strings.Split(s, "\n")
   484		if l := len(lines); l > 1 && lines[l-1] == "" {
   485			lines = lines[:l-1]
   486		}
   487		for i, line := range lines {
   488			if i > 0 {
   489				// Second and subsequent lines are indented an additional 4 spaces.
   490				buf.WriteString("\n        ")
   491			}
   492			buf.WriteString(line)
   493		}
   494		buf.WriteByte('\n')
   495		return buf.String()
   496	}
   497	
   498	// flushToParent writes c.output to the parent after first writing the header
   499	// with the given format and arguments.
   500	func (c *common) flushToParent(format string, args ...interface{}) {
   501		p := c.parent
   502		p.mu.Lock()
   503		defer p.mu.Unlock()
   504	
   505		fmt.Fprintf(p.w, format, args...)
   506	
   507		c.mu.Lock()
   508		defer c.mu.Unlock()
   509		io.Copy(p.w, bytes.NewReader(c.output))
   510		c.output = c.output[:0]
   511	}
   512	
   513	type indenter struct {
   514		c *common
   515	}
   516	
   517	func (w indenter) Write(b []byte) (n int, err error) {
   518		n = len(b)
   519		for len(b) > 0 {
   520			end := bytes.IndexByte(b, '\n')
   521			if end == -1 {
   522				end = len(b)
   523			} else {
   524				end++
   525			}
   526			// An indent of 4 spaces will neatly align the dashes with the status
   527			// indicator of the parent.
   528			const indent = "    "
   529			w.c.output = append(w.c.output, indent...)
   530			w.c.output = append(w.c.output, b[:end]...)
   531			b = b[end:]
   532		}
   533		return
   534	}
   535	
   536	// fmtDuration returns a string representing d in the form "87.00s".
   537	func fmtDuration(d time.Duration) string {
   538		return fmt.Sprintf("%.2fs", d.Seconds())
   539	}
   540	
   541	// TB is the interface common to T and B.
   542	type TB interface {
   543		Error(args ...interface{})
   544		Errorf(format string, args ...interface{})
   545		Fail()
   546		FailNow()
   547		Failed() bool
   548		Fatal(args ...interface{})
   549		Fatalf(format string, args ...interface{})
   550		Log(args ...interface{})
   551		Logf(format string, args ...interface{})
   552		Name() string
   553		Skip(args ...interface{})
   554		SkipNow()
   555		Skipf(format string, args ...interface{})
   556		Skipped() bool
   557		Helper()
   558	
   559		// A private method to prevent users implementing the
   560		// interface and so future additions to it will not
   561		// violate Go 1 compatibility.
   562		private()
   563	}
   564	
   565	var _ TB = (*T)(nil)
   566	var _ TB = (*B)(nil)
   567	
   568	// T is a type passed to Test functions to manage test state and support formatted test logs.
   569	// Logs are accumulated during execution and dumped to standard output when done.
   570	//
   571	// A test ends when its Test function returns or calls any of the methods
   572	// FailNow, Fatal, Fatalf, SkipNow, Skip, or Skipf. Those methods, as well as
   573	// the Parallel method, must be called only from the goroutine running the
   574	// Test function.
   575	//
   576	// The other reporting methods, such as the variations of Log and Error,
   577	// may be called simultaneously from multiple goroutines.
   578	type T struct {
   579		common
   580		isParallel bool
   581		context    *testContext // For running tests and subtests.
   582	}
   583	
   584	func (c *common) private() {}
   585	
   586	// Name returns the name of the running test or benchmark.
   587	func (c *common) Name() string {
   588		return c.name
   589	}
   590	
   591	func (c *common) setRan() {
   592		if c.parent != nil {
   593			c.parent.setRan()
   594		}
   595		c.mu.Lock()
   596		defer c.mu.Unlock()
   597		c.ran = true
   598	}
   599	
   600	// Fail marks the function as having failed but continues execution.
   601	func (c *common) Fail() {
   602		if c.parent != nil {
   603			c.parent.Fail()
   604		}
   605		c.mu.Lock()
   606		defer c.mu.Unlock()
   607		// c.done needs to be locked to synchronize checks to c.done in parent tests.
   608		if c.done {
   609			panic("Fail in goroutine after " + c.name + " has completed")
   610		}
   611		c.failed = true
   612	}
   613	
   614	// Failed reports whether the function has failed.
   615	func (c *common) Failed() bool {
   616		c.mu.RLock()
   617		failed := c.failed
   618		c.mu.RUnlock()
   619		return failed || c.raceErrors+race.Errors() > 0
   620	}
   621	
   622	// FailNow marks the function as having failed and stops its execution
   623	// by calling runtime.Goexit (which then runs all deferred calls in the
   624	// current goroutine).
   625	// Execution will continue at the next test or benchmark.
   626	// FailNow must be called from the goroutine running the
   627	// test or benchmark function, not from other goroutines
   628	// created during the test. Calling FailNow does not stop
   629	// those other goroutines.
   630	func (c *common) FailNow() {
   631		c.Fail()
   632	
   633		// Calling runtime.Goexit will exit the goroutine, which
   634		// will run the deferred functions in this goroutine,
   635		// which will eventually run the deferred lines in tRunner,
   636		// which will signal to the test loop that this test is done.
   637		//
   638		// A previous version of this code said:
   639		//
   640		//	c.duration = ...
   641		//	c.signal <- c.self
   642		//	runtime.Goexit()
   643		//
   644		// This previous version duplicated code (those lines are in
   645		// tRunner no matter what), but worse the goroutine teardown
   646		// implicit in runtime.Goexit was not guaranteed to complete
   647		// before the test exited. If a test deferred an important cleanup
   648		// function (like removing temporary files), there was no guarantee
   649		// it would run on a test failure. Because we send on c.signal during
   650		// a top-of-stack deferred function now, we know that the send
   651		// only happens after any other stacked defers have completed.
   652		c.finished = true
   653		runtime.Goexit()
   654	}
   655	
   656	// log generates the output. It's always at the same stack depth.
   657	func (c *common) log(s string) {
   658		c.logDepth(s, 3) // logDepth + log + public function
   659	}
   660	
   661	// logDepth generates the output at an arbitrary stack depth.
   662	func (c *common) logDepth(s string, depth int) {
   663		c.mu.Lock()
   664		defer c.mu.Unlock()
   665		if !c.done {
   666			c.output = append(c.output, c.decorate(s, depth+1)...)
   667		} else {
   668			// This test has already finished. Try and log this message
   669			// with our parent. If we don't have a parent, panic.
   670			for parent := c.parent; parent != nil; parent = parent.parent {
   671				parent.mu.Lock()
   672				defer parent.mu.Unlock()
   673				if !parent.done {
   674					parent.output = append(parent.output, parent.decorate(s, depth+1)...)
   675					return
   676				}
   677			}
   678			panic("Log in goroutine after " + c.name + " has completed")
   679		}
   680	}
   681	
   682	// Log formats its arguments using default formatting, analogous to Println,
   683	// and records the text in the error log. For tests, the text will be printed only if
   684	// the test fails or the -test.v flag is set. For benchmarks, the text is always
   685	// printed to avoid having performance depend on the value of the -test.v flag.
   686	func (c *common) Log(args ...interface{}) { c.log(fmt.Sprintln(args...)) }
   687	
   688	// Logf formats its arguments according to the format, analogous to Printf, and
   689	// records the text in the error log. A final newline is added if not provided. For
   690	// tests, the text will be printed only if the test fails or the -test.v flag is
   691	// set. For benchmarks, the text is always printed to avoid having performance
   692	// depend on the value of the -test.v flag.
   693	func (c *common) Logf(format string, args ...interface{}) { c.log(fmt.Sprintf(format, args...)) }
   694	
   695	// Error is equivalent to Log followed by Fail.
   696	func (c *common) Error(args ...interface{}) {
   697		c.log(fmt.Sprintln(args...))
   698		c.Fail()
   699	}
   700	
   701	// Errorf is equivalent to Logf followed by Fail.
   702	func (c *common) Errorf(format string, args ...interface{}) {
   703		c.log(fmt.Sprintf(format, args...))
   704		c.Fail()
   705	}
   706	
   707	// Fatal is equivalent to Log followed by FailNow.
   708	func (c *common) Fatal(args ...interface{}) {
   709		c.log(fmt.Sprintln(args...))
   710		c.FailNow()
   711	}
   712	
   713	// Fatalf is equivalent to Logf followed by FailNow.
   714	func (c *common) Fatalf(format string, args ...interface{}) {
   715		c.log(fmt.Sprintf(format, args...))
   716		c.FailNow()
   717	}
   718	
   719	// Skip is equivalent to Log followed by SkipNow.
   720	func (c *common) Skip(args ...interface{}) {
   721		c.log(fmt.Sprintln(args...))
   722		c.SkipNow()
   723	}
   724	
   725	// Skipf is equivalent to Logf followed by SkipNow.
   726	func (c *common) Skipf(format string, args ...interface{}) {
   727		c.log(fmt.Sprintf(format, args...))
   728		c.SkipNow()
   729	}
   730	
   731	// SkipNow marks the test as having been skipped and stops its execution
   732	// by calling runtime.Goexit.
   733	// If a test fails (see Error, Errorf, Fail) and is then skipped,
   734	// it is still considered to have failed.
   735	// Execution will continue at the next test or benchmark. See also FailNow.
   736	// SkipNow must be called from the goroutine running the test, not from
   737	// other goroutines created during the test. Calling SkipNow does not stop
   738	// those other goroutines.
   739	func (c *common) SkipNow() {
   740		c.skip()
   741		c.finished = true
   742		runtime.Goexit()
   743	}
   744	
   745	func (c *common) skip() {
   746		c.mu.Lock()
   747		defer c.mu.Unlock()
   748		c.skipped = true
   749	}
   750	
   751	// Skipped reports whether the test was skipped.
   752	func (c *common) Skipped() bool {
   753		c.mu.RLock()
   754		defer c.mu.RUnlock()
   755		return c.skipped
   756	}
   757	
   758	// Helper marks the calling function as a test helper function.
   759	// When printing file and line information, that function will be skipped.
   760	// Helper may be called simultaneously from multiple goroutines.
   761	func (c *common) Helper() {
   762		c.mu.Lock()
   763		defer c.mu.Unlock()
   764		if c.helpers == nil {
   765			c.helpers = make(map[string]struct{})
   766		}
   767		c.helpers[callerName(1)] = struct{}{}
   768	}
   769	
   770	// callerName gives the function name (qualified with a package path)
   771	// for the caller after skip frames (where 0 means the current function).
   772	func callerName(skip int) string {
   773		// Make room for the skip PC.
   774		var pc [1]uintptr
   775		n := runtime.Callers(skip+2, pc[:]) // skip + runtime.Callers + callerName
   776		if n == 0 {
   777			panic("testing: zero callers found")
   778		}
   779		frames := runtime.CallersFrames(pc[:n])
   780		frame, _ := frames.Next()
   781		return frame.Function
   782	}
   783	
   784	// Parallel signals that this test is to be run in parallel with (and only with)
   785	// other parallel tests. When a test is run multiple times due to use of
   786	// -test.count or -test.cpu, multiple instances of a single test never run in
   787	// parallel with each other.
   788	func (t *T) Parallel() {
   789		if t.isParallel {
   790			panic("testing: t.Parallel called multiple times")
   791		}
   792		t.isParallel = true
   793	
   794		// We don't want to include the time we spend waiting for serial tests
   795		// in the test duration. Record the elapsed time thus far and reset the
   796		// timer afterwards.
   797		t.duration += time.Since(t.start)
   798	
   799		// Add to the list of tests to be released by the parent.
   800		t.parent.sub = append(t.parent.sub, t)
   801		t.raceErrors += race.Errors()
   802	
   803		if t.chatty {
   804			// Print directly to root's io.Writer so there is no delay.
   805			root := t.parent
   806			for ; root.parent != nil; root = root.parent {
   807			}
   808			root.mu.Lock()
   809			fmt.Fprintf(root.w, "=== PAUSE %s\n", t.name)
   810			root.mu.Unlock()
   811		}
   812	
   813		t.signal <- true   // Release calling test.
   814		<-t.parent.barrier // Wait for the parent test to complete.
   815		t.context.waitParallel()
   816	
   817		if t.chatty {
   818			// Print directly to root's io.Writer so there is no delay.
   819			root := t.parent
   820			for ; root.parent != nil; root = root.parent {
   821			}
   822			root.mu.Lock()
   823			fmt.Fprintf(root.w, "=== CONT  %s\n", t.name)
   824			root.mu.Unlock()
   825		}
   826	
   827		t.start = time.Now()
   828		t.raceErrors += -race.Errors()
   829	}
   830	
   831	// An internal type but exported because it is cross-package; part of the implementation
   832	// of the "go test" command.
   833	type InternalTest struct {
   834		Name string
   835		F    func(*T)
   836	}
   837	
   838	var errNilPanicOrGoexit = errors.New("test executed panic(nil) or runtime.Goexit")
   839	
   840	func tRunner(t *T, fn func(t *T)) {
   841		t.runner = callerName(0)
   842	
   843		// When this goroutine is done, either because fn(t)
   844		// returned normally or because a test failure triggered
   845		// a call to runtime.Goexit, record the duration and send
   846		// a signal saying that the test is done.
   847		defer func() {
   848			if t.Failed() {
   849				atomic.AddUint32(&numFailed, 1)
   850			}
   851	
   852			if t.raceErrors+race.Errors() > 0 {
   853				t.Errorf("race detected during execution of test")
   854			}
   855	
   856			t.duration += time.Since(t.start)
   857			// If the test panicked, print any test output before dying.
   858			err := recover()
   859			signal := true
   860			if !t.finished && err == nil {
   861				err = errNilPanicOrGoexit
   862				for p := t.parent; p != nil; p = p.parent {
   863					if p.finished {
   864						t.Errorf("%v: subtest may have called FailNow on a parent test", err)
   865						err = nil
   866						signal = false
   867						break
   868					}
   869				}
   870			}
   871			if err != nil {
   872				t.Fail()
   873				t.report()
   874				panic(err)
   875			}
   876	
   877			if len(t.sub) > 0 {
   878				// Run parallel subtests.
   879				// Decrease the running count for this test.
   880				t.context.release()
   881				// Release the parallel subtests.
   882				close(t.barrier)
   883				// Wait for subtests to complete.
   884				for _, sub := range t.sub {
   885					<-sub.signal
   886				}
   887				if !t.isParallel {
   888					// Reacquire the count for sequential tests. See comment in Run.
   889					t.context.waitParallel()
   890				}
   891			} else if t.isParallel {
   892				// Only release the count for this test if it was run as a parallel
   893				// test. See comment in Run method.
   894				t.context.release()
   895			}
   896			t.report() // Report after all subtests have finished.
   897	
   898			// Do not lock t.done to allow race detector to detect race in case
   899			// the user does not appropriately synchronizes a goroutine.
   900			t.done = true
   901			if t.parent != nil && atomic.LoadInt32(&t.hasSub) == 0 {
   902				t.setRan()
   903			}
   904			t.signal <- signal
   905		}()
   906	
   907		t.start = time.Now()
   908		t.raceErrors = -race.Errors()
   909		fn(t)
   910	
   911		// code beyond here will not be executed when FailNow is invoked
   912		t.finished = true
   913	}
   914	
   915	// Run runs f as a subtest of t called name. It runs f in a separate goroutine
   916	// and blocks until f returns or calls t.Parallel to become a parallel test.
   917	// Run reports whether f succeeded (or at least did not fail before calling t.Parallel).
   918	//
   919	// Run may be called simultaneously from multiple goroutines, but all such calls
   920	// must return before the outer test function for t returns.
   921	func (t *T) Run(name string, f func(t *T)) bool {
   922		atomic.StoreInt32(&t.hasSub, 1)
   923		testName, ok, _ := t.context.match.fullName(&t.common, name)
   924		if !ok || shouldFailFast() {
   925			return true
   926		}
   927		// Record the stack trace at the point of this call so that if the subtest
   928		// function - which runs in a separate stack - is marked as a helper, we can
   929		// continue walking the stack into the parent test.
   930		var pc [maxStackLen]uintptr
   931		n := runtime.Callers(2, pc[:])
   932		t = &T{
   933			common: common{
   934				barrier: make(chan bool),
   935				signal:  make(chan bool),
   936				name:    testName,
   937				parent:  &t.common,
   938				level:   t.level + 1,
   939				creator: pc[:n],
   940				chatty:  t.chatty,
   941			},
   942			context: t.context,
   943		}
   944		t.w = indenter{&t.common}
   945	
   946		if t.chatty {
   947			// Print directly to root's io.Writer so there is no delay.
   948			root := t.parent
   949			for ; root.parent != nil; root = root.parent {
   950			}
   951			root.mu.Lock()
   952			fmt.Fprintf(root.w, "=== RUN   %s\n", t.name)
   953			root.mu.Unlock()
   954		}
   955		// Instead of reducing the running count of this test before calling the
   956		// tRunner and increasing it afterwards, we rely on tRunner keeping the
   957		// count correct. This ensures that a sequence of sequential tests runs
   958		// without being preempted, even when their parent is a parallel test. This
   959		// may especially reduce surprises if *parallel == 1.
   960		go tRunner(t, f)
   961		if !<-t.signal {
   962			// At this point, it is likely that FailNow was called on one of the
   963			// parent tests by one of the subtests. Continue aborting up the chain.
   964			runtime.Goexit()
   965		}
   966		return !t.failed
   967	}
   968	
   969	// testContext holds all fields that are common to all tests. This includes
   970	// synchronization primitives to run at most *parallel tests.
   971	type testContext struct {
   972		match *matcher
   973	
   974		mu sync.Mutex
   975	
   976		// Channel used to signal tests that are ready to be run in parallel.
   977		startParallel chan bool
   978	
   979		// running is the number of tests currently running in parallel.
   980		// This does not include tests that are waiting for subtests to complete.
   981		running int
   982	
   983		// numWaiting is the number tests waiting to be run in parallel.
   984		numWaiting int
   985	
   986		// maxParallel is a copy of the parallel flag.
   987		maxParallel int
   988	}
   989	
   990	func newTestContext(maxParallel int, m *matcher) *testContext {
   991		return &testContext{
   992			match:         m,
   993			startParallel: make(chan bool),
   994			maxParallel:   maxParallel,
   995			running:       1, // Set the count to 1 for the main (sequential) test.
   996		}
   997	}
   998	
   999	func (c *testContext) waitParallel() {
  1000		c.mu.Lock()
  1001		if c.running < c.maxParallel {
  1002			c.running++
  1003			c.mu.Unlock()
  1004			return
  1005		}
  1006		c.numWaiting++
  1007		c.mu.Unlock()
  1008		<-c.startParallel
  1009	}
  1010	
  1011	func (c *testContext) release() {
  1012		c.mu.Lock()
  1013		if c.numWaiting == 0 {
  1014			c.running--
  1015			c.mu.Unlock()
  1016			return
  1017		}
  1018		c.numWaiting--
  1019		c.mu.Unlock()
  1020		c.startParallel <- true // Pick a waiting test to be run.
  1021	}
  1022	
  1023	// No one should be using func Main anymore.
  1024	// See the doc comment on func Main and use MainStart instead.
  1025	var errMain = errors.New("testing: unexpected use of func Main")
  1026	
  1027	type matchStringOnly func(pat, str string) (bool, error)
  1028	
  1029	func (f matchStringOnly) MatchString(pat, str string) (bool, error)   { return f(pat, str) }
  1030	func (f matchStringOnly) StartCPUProfile(w io.Writer) error           { return errMain }
  1031	func (f matchStringOnly) StopCPUProfile()                             {}
  1032	func (f matchStringOnly) WriteProfileTo(string, io.Writer, int) error { return errMain }
  1033	func (f matchStringOnly) ImportPath() string                          { return "" }
  1034	func (f matchStringOnly) StartTestLog(io.Writer)                      {}
  1035	func (f matchStringOnly) StopTestLog() error                          { return errMain }
  1036	
  1037	// Main is an internal function, part of the implementation of the "go test" command.
  1038	// It was exported because it is cross-package and predates "internal" packages.
  1039	// It is no longer used by "go test" but preserved, as much as possible, for other
  1040	// systems that simulate "go test" using Main, but Main sometimes cannot be updated as
  1041	// new functionality is added to the testing package.
  1042	// Systems simulating "go test" should be updated to use MainStart.
  1043	func Main(matchString func(pat, str string) (bool, error), tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample) {
  1044		os.Exit(MainStart(matchStringOnly(matchString), tests, benchmarks, examples).Run())
  1045	}
  1046	
  1047	// M is a type passed to a TestMain function to run the actual tests.
  1048	type M struct {
  1049		deps       testDeps
  1050		tests      []InternalTest
  1051		benchmarks []InternalBenchmark
  1052		examples   []InternalExample
  1053	
  1054		timer     *time.Timer
  1055		afterOnce sync.Once
  1056	
  1057		numRun int
  1058	}
  1059	
  1060	// testDeps is an internal interface of functionality that is
  1061	// passed into this package by a test's generated main package.
  1062	// The canonical implementation of this interface is
  1063	// testing/internal/testdeps's TestDeps.
  1064	type testDeps interface {
  1065		ImportPath() string
  1066		MatchString(pat, str string) (bool, error)
  1067		StartCPUProfile(io.Writer) error
  1068		StopCPUProfile()
  1069		StartTestLog(io.Writer)
  1070		StopTestLog() error
  1071		WriteProfileTo(string, io.Writer, int) error
  1072	}
  1073	
  1074	// MainStart is meant for use by tests generated by 'go test'.
  1075	// It is not meant to be called directly and is not subject to the Go 1 compatibility document.
  1076	// It may change signature from release to release.
  1077	func MainStart(deps testDeps, tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample) *M {
  1078		Init()
  1079		return &M{
  1080			deps:       deps,
  1081			tests:      tests,
  1082			benchmarks: benchmarks,
  1083			examples:   examples,
  1084		}
  1085	}
  1086	
  1087	// Run runs the tests. It returns an exit code to pass to os.Exit.
  1088	func (m *M) Run() int {
  1089		// Count the number of calls to m.Run.
  1090		// We only ever expected 1, but we didn't enforce that,
  1091		// and now there are tests in the wild that call m.Run multiple times.
  1092		// Sigh. golang.org/issue/23129.
  1093		m.numRun++
  1094	
  1095		// TestMain may have already called flag.Parse.
  1096		if !flag.Parsed() {
  1097			flag.Parse()
  1098		}
  1099	
  1100		if *parallel < 1 {
  1101			fmt.Fprintln(os.Stderr, "testing: -parallel can only be given a positive integer")
  1102			flag.Usage()
  1103			return 2
  1104		}
  1105	
  1106		if len(*matchList) != 0 {
  1107			listTests(m.deps.MatchString, m.tests, m.benchmarks, m.examples)
  1108			return 0
  1109		}
  1110	
  1111		parseCpuList()
  1112	
  1113		m.before()
  1114		defer m.after()
  1115		m.startAlarm()
  1116		haveExamples = len(m.examples) > 0
  1117		testRan, testOk := runTests(m.deps.MatchString, m.tests)
  1118		exampleRan, exampleOk := runExamples(m.deps.MatchString, m.examples)
  1119		m.stopAlarm()
  1120		if !testRan && !exampleRan && *matchBenchmarks == "" {
  1121			fmt.Fprintln(os.Stderr, "testing: warning: no tests to run")
  1122		}
  1123		if !testOk || !exampleOk || !runBenchmarks(m.deps.ImportPath(), m.deps.MatchString, m.benchmarks) || race.Errors() > 0 {
  1124			fmt.Println("FAIL")
  1125			return 1
  1126		}
  1127	
  1128		fmt.Println("PASS")
  1129		return 0
  1130	}
  1131	
  1132	func (t *T) report() {
  1133		if t.parent == nil {
  1134			return
  1135		}
  1136		dstr := fmtDuration(t.duration)
  1137		format := "--- %s: %s (%s)\n"
  1138		if t.Failed() {
  1139			t.flushToParent(format, "FAIL", t.name, dstr)
  1140		} else if t.chatty {
  1141			if t.Skipped() {
  1142				t.flushToParent(format, "SKIP", t.name, dstr)
  1143			} else {
  1144				t.flushToParent(format, "PASS", t.name, dstr)
  1145			}
  1146		}
  1147	}
  1148	
  1149	func listTests(matchString func(pat, str string) (bool, error), tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample) {
  1150		if _, err := matchString(*matchList, "non-empty"); err != nil {
  1151			fmt.Fprintf(os.Stderr, "testing: invalid regexp in -test.list (%q): %s\n", *matchList, err)
  1152			os.Exit(1)
  1153		}
  1154	
  1155		for _, test := range tests {
  1156			if ok, _ := matchString(*matchList, test.Name); ok {
  1157				fmt.Println(test.Name)
  1158			}
  1159		}
  1160		for _, bench := range benchmarks {
  1161			if ok, _ := matchString(*matchList, bench.Name); ok {
  1162				fmt.Println(bench.Name)
  1163			}
  1164		}
  1165		for _, example := range examples {
  1166			if ok, _ := matchString(*matchList, example.Name); ok {
  1167				fmt.Println(example.Name)
  1168			}
  1169		}
  1170	}
  1171	
  1172	// An internal function but exported because it is cross-package; part of the implementation
  1173	// of the "go test" command.
  1174	func RunTests(matchString func(pat, str string) (bool, error), tests []InternalTest) (ok bool) {
  1175		ran, ok := runTests(matchString, tests)
  1176		if !ran && !haveExamples {
  1177			fmt.Fprintln(os.Stderr, "testing: warning: no tests to run")
  1178		}
  1179		return ok
  1180	}
  1181	
  1182	func runTests(matchString func(pat, str string) (bool, error), tests []InternalTest) (ran, ok bool) {
  1183		ok = true
  1184		for _, procs := range cpuList {
  1185			runtime.GOMAXPROCS(procs)
  1186			for i := uint(0); i < *count; i++ {
  1187				if shouldFailFast() {
  1188					break
  1189				}
  1190				ctx := newTestContext(*parallel, newMatcher(matchString, *match, "-test.run"))
  1191				t := &T{
  1192					common: common{
  1193						signal:  make(chan bool),
  1194						barrier: make(chan bool),
  1195						w:       os.Stdout,
  1196						chatty:  *chatty,
  1197					},
  1198					context: ctx,
  1199				}
  1200				tRunner(t, func(t *T) {
  1201					for _, test := range tests {
  1202						t.Run(test.Name, test.F)
  1203					}
  1204					// Run catching the signal rather than the tRunner as a separate
  1205					// goroutine to avoid adding a goroutine during the sequential
  1206					// phase as this pollutes the stacktrace output when aborting.
  1207					go func() { <-t.signal }()
  1208				})
  1209				ok = ok && !t.Failed()
  1210				ran = ran || t.ran
  1211			}
  1212		}
  1213		return ran, ok
  1214	}
  1215	
  1216	// before runs before all testing.
  1217	func (m *M) before() {
  1218		if *memProfileRate > 0 {
  1219			runtime.MemProfileRate = *memProfileRate
  1220		}
  1221		if *cpuProfile != "" {
  1222			f, err := os.Create(toOutputDir(*cpuProfile))
  1223			if err != nil {
  1224				fmt.Fprintf(os.Stderr, "testing: %s\n", err)
  1225				return
  1226			}
  1227			if err := m.deps.StartCPUProfile(f); err != nil {
  1228				fmt.Fprintf(os.Stderr, "testing: can't start cpu profile: %s\n", err)
  1229				f.Close()
  1230				return
  1231			}
  1232			// Could save f so after can call f.Close; not worth the effort.
  1233		}
  1234		if *traceFile != "" {
  1235			f, err := os.Create(toOutputDir(*traceFile))
  1236			if err != nil {
  1237				fmt.Fprintf(os.Stderr, "testing: %s\n", err)
  1238				return
  1239			}
  1240			if err := trace.Start(f); err != nil {
  1241				fmt.Fprintf(os.Stderr, "testing: can't start tracing: %s\n", err)
  1242				f.Close()
  1243				return
  1244			}
  1245			// Could save f so after can call f.Close; not worth the effort.
  1246		}
  1247		if *blockProfile != "" && *blockProfileRate >= 0 {
  1248			runtime.SetBlockProfileRate(*blockProfileRate)
  1249		}
  1250		if *mutexProfile != "" && *mutexProfileFraction >= 0 {
  1251			runtime.SetMutexProfileFraction(*mutexProfileFraction)
  1252		}
  1253		if *coverProfile != "" && cover.Mode == "" {
  1254			fmt.Fprintf(os.Stderr, "testing: cannot use -test.coverprofile because test binary was not built with coverage enabled\n")
  1255			os.Exit(2)
  1256		}
  1257		if *testlog != "" {
  1258			// Note: Not using toOutputDir.
  1259			// This file is for use by cmd/go, not users.
  1260			var f *os.File
  1261			var err error
  1262			if m.numRun == 1 {
  1263				f, err = os.Create(*testlog)
  1264			} else {
  1265				f, err = os.OpenFile(*testlog, os.O_WRONLY, 0)
  1266				if err == nil {
  1267					f.Seek(0, io.SeekEnd)
  1268				}
  1269			}
  1270			if err != nil {
  1271				fmt.Fprintf(os.Stderr, "testing: %s\n", err)
  1272				os.Exit(2)
  1273			}
  1274			m.deps.StartTestLog(f)
  1275			testlogFile = f
  1276		}
  1277	}
  1278	
  1279	// after runs after all testing.
  1280	func (m *M) after() {
  1281		m.afterOnce.Do(func() {
  1282			m.writeProfiles()
  1283		})
  1284	}
  1285	
  1286	func (m *M) writeProfiles() {
  1287		if *testlog != "" {
  1288			if err := m.deps.StopTestLog(); err != nil {
  1289				fmt.Fprintf(os.Stderr, "testing: can't write %s: %s\n", *testlog, err)
  1290				os.Exit(2)
  1291			}
  1292			if err := testlogFile.Close(); err != nil {
  1293				fmt.Fprintf(os.Stderr, "testing: can't write %s: %s\n", *testlog, err)
  1294				os.Exit(2)
  1295			}
  1296		}
  1297		if *cpuProfile != "" {
  1298			m.deps.StopCPUProfile() // flushes profile to disk
  1299		}
  1300		if *traceFile != "" {
  1301			trace.Stop() // flushes trace to disk
  1302		}
  1303		if *memProfile != "" {
  1304			f, err := os.Create(toOutputDir(*memProfile))
  1305			if err != nil {
  1306				fmt.Fprintf(os.Stderr, "testing: %s\n", err)
  1307				os.Exit(2)
  1308			}
  1309			runtime.GC() // materialize all statistics
  1310			if err = m.deps.WriteProfileTo("allocs", f, 0); err != nil {
  1311				fmt.Fprintf(os.Stderr, "testing: can't write %s: %s\n", *memProfile, err)
  1312				os.Exit(2)
  1313			}
  1314			f.Close()
  1315		}
  1316		if *blockProfile != "" && *blockProfileRate >= 0 {
  1317			f, err := os.Create(toOutputDir(*blockProfile))
  1318			if err != nil {
  1319				fmt.Fprintf(os.Stderr, "testing: %s\n", err)
  1320				os.Exit(2)
  1321			}
  1322			if err = m.deps.WriteProfileTo("block", f, 0); err != nil {
  1323				fmt.Fprintf(os.Stderr, "testing: can't write %s: %s\n", *blockProfile, err)
  1324				os.Exit(2)
  1325			}
  1326			f.Close()
  1327		}
  1328		if *mutexProfile != "" && *mutexProfileFraction >= 0 {
  1329			f, err := os.Create(toOutputDir(*mutexProfile))
  1330			if err != nil {
  1331				fmt.Fprintf(os.Stderr, "testing: %s\n", err)
  1332				os.Exit(2)
  1333			}
  1334			if err = m.deps.WriteProfileTo("mutex", f, 0); err != nil {
  1335				fmt.Fprintf(os.Stderr, "testing: can't write %s: %s\n", *mutexProfile, err)
  1336				os.Exit(2)
  1337			}
  1338			f.Close()
  1339		}
  1340		if cover.Mode != "" {
  1341			coverReport()
  1342		}
  1343	}
  1344	
  1345	// toOutputDir returns the file name relocated, if required, to outputDir.
  1346	// Simple implementation to avoid pulling in path/filepath.
  1347	func toOutputDir(path string) string {
  1348		if *outputDir == "" || path == "" {
  1349			return path
  1350		}
  1351		// On Windows, it's clumsy, but we can be almost always correct
  1352		// by just looking for a drive letter and a colon.
  1353		// Absolute paths always have a drive letter (ignoring UNC).
  1354		// Problem: if path == "C:A" and outputdir == "C:\Go" it's unclear
  1355		// what to do, but even then path/filepath doesn't help.
  1356		// TODO: Worth doing better? Probably not, because we're here only
  1357		// under the management of go test.
  1358		if runtime.GOOS == "windows" && len(path) >= 2 {
  1359			letter, colon := path[0], path[1]
  1360			if ('a' <= letter && letter <= 'z' || 'A' <= letter && letter <= 'Z') && colon == ':' {
  1361				// If path starts with a drive letter we're stuck with it regardless.
  1362				return path
  1363			}
  1364		}
  1365		if os.IsPathSeparator(path[0]) {
  1366			return path
  1367		}
  1368		return fmt.Sprintf("%s%c%s", *outputDir, os.PathSeparator, path)
  1369	}
  1370	
  1371	// startAlarm starts an alarm if requested.
  1372	func (m *M) startAlarm() {
  1373		if *timeout > 0 {
  1374			m.timer = time.AfterFunc(*timeout, func() {
  1375				m.after()
  1376				debug.SetTraceback("all")
  1377				panic(fmt.Sprintf("test timed out after %v", *timeout))
  1378			})
  1379		}
  1380	}
  1381	
  1382	// stopAlarm turns off the alarm.
  1383	func (m *M) stopAlarm() {
  1384		if *timeout > 0 {
  1385			m.timer.Stop()
  1386		}
  1387	}
  1388	
  1389	func parseCpuList() {
  1390		for _, val := range strings.Split(*cpuListStr, ",") {
  1391			val = strings.TrimSpace(val)
  1392			if val == "" {
  1393				continue
  1394			}
  1395			cpu, err := strconv.Atoi(val)
  1396			if err != nil || cpu <= 0 {
  1397				fmt.Fprintf(os.Stderr, "testing: invalid value %q for -test.cpu\n", val)
  1398				os.Exit(1)
  1399			}
  1400			cpuList = append(cpuList, cpu)
  1401		}
  1402		if cpuList == nil {
  1403			cpuList = append(cpuList, runtime.GOMAXPROCS(-1))
  1404		}
  1405	}
  1406	
  1407	func shouldFailFast() bool {
  1408		return *failFast && atomic.LoadUint32(&numFailed) > 0
  1409	}
  1410	

View as plain text