github.com/dannin/go@v0.0.0-20161031215817-d35dfd405eaa/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  // Subtests and Sub-benchmarks
   122  //
   123  // The Run methods of T and B allow defining subtests and sub-benchmarks,
   124  // without having to define separate functions for each. This enables uses
   125  // like table-driven benchmarks and creating hierarchical tests.
   126  // It also provides a way to share common setup and tear-down code:
   127  //
   128  //     func TestFoo(t *testing.T) {
   129  //         // <setup code>
   130  //         t.Run("A=1", func(t *testing.T) { ... })
   131  //         t.Run("A=2", func(t *testing.T) { ... })
   132  //         t.Run("B=1", func(t *testing.T) { ... })
   133  //         // <tear-down code>
   134  //     }
   135  //
   136  // Each subtest and sub-benchmark has a unique name: the combination of the name
   137  // of the top-level test and the sequence of names passed to Run, separated by
   138  // slashes, with an optional trailing sequence number for disambiguation.
   139  //
   140  // The argument to the -run and -bench command-line flags is an unanchored regular
   141  // expression that matches the test's name. For tests with multiple slash-separated
   142  // elements, such as subtests, the argument is itself slash-separated, with
   143  // expressions matching each name element in turn. Because it is unanchored, an
   144  // empty expression matches any string.
   145  // For example, using "matching" to mean "whose name contains":
   146  //
   147  //     go test -run ''      # Run all tests.
   148  //     go test -run Foo     # Run top-level tests matching "Foo", such as "TestFooBar".
   149  //     go test -run Foo/A=  # For top-level tests matching "Foo", run subtests matching "A=".
   150  //     go test -run /A=1    # For all top-level tests, run subtests matching "A=1".
   151  //
   152  // Subtests can also be used to control parallelism. A parent test will only
   153  // complete once all of its subtests complete. In this example, all tests are
   154  // run in parallel with each other, and only with each other, regardless of
   155  // other top-level tests that may be defined:
   156  //
   157  //     func TestGroupedParallel(t *testing.T) {
   158  //         for _, tc := range tests {
   159  //             tc := tc // capture range variable
   160  //             t.Run(tc.Name, func(t *testing.T) {
   161  //                 t.Parallel()
   162  //                 ...
   163  //             })
   164  //         }
   165  //     }
   166  //
   167  // Run does not return until parallel subtests have completed, providing a way
   168  // to clean up after a group of parallel tests:
   169  //
   170  //     func TestTeardownParallel(t *testing.T) {
   171  //         // This Run will not return until the parallel tests finish.
   172  //         t.Run("group", func(t *testing.T) {
   173  //             t.Run("Test1", parallelTest1)
   174  //             t.Run("Test2", parallelTest2)
   175  //             t.Run("Test3", parallelTest3)
   176  //         })
   177  //         // <tear-down code>
   178  //     }
   179  //
   180  // Main
   181  //
   182  // It is sometimes necessary for a test program to do extra setup or teardown
   183  // before or after testing. It is also sometimes necessary for a test to control
   184  // which code runs on the main thread. To support these and other cases,
   185  // if a test file contains a function:
   186  //
   187  //	func TestMain(m *testing.M)
   188  //
   189  // then the generated test will call TestMain(m) instead of running the tests
   190  // directly. TestMain runs in the main goroutine and can do whatever setup
   191  // and teardown is necessary around a call to m.Run. It should then call
   192  // os.Exit with the result of m.Run. When TestMain is called, flag.Parse has
   193  // not been run. If TestMain depends on command-line flags, including those
   194  // of the testing package, it should call flag.Parse explicitly.
   195  //
   196  // A simple implementation of TestMain is:
   197  //
   198  //	func TestMain(m *testing.M) {
   199  //		flag.Parse()
   200  //		os.Exit(m.Run())
   201  //	}
   202  //
   203  package testing
   204  
   205  import (
   206  	"bytes"
   207  	"flag"
   208  	"fmt"
   209  	"io"
   210  	"os"
   211  	"runtime"
   212  	"runtime/debug"
   213  	"runtime/pprof"
   214  	"runtime/trace"
   215  	"strconv"
   216  	"strings"
   217  	"sync"
   218  	"time"
   219  )
   220  
   221  var (
   222  	// The short flag requests that tests run more quickly, but its functionality
   223  	// is provided by test writers themselves. The testing package is just its
   224  	// home. The all.bash installation script sets it to make installation more
   225  	// efficient, but by default the flag is off so a plain "go test" will do a
   226  	// full test of the package.
   227  	short = flag.Bool("test.short", false, "run smaller test suite to save time")
   228  
   229  	// The directory in which to create profile files and the like. When run from
   230  	// "go test", the binary always runs in the source directory for the package;
   231  	// this flag lets "go test" tell the binary to write the files in the directory where
   232  	// the "go test" command is run.
   233  	outputDir = flag.String("test.outputdir", "", "write profiles to `dir`")
   234  
   235  	// Report as tests are run; default is silent for success.
   236  	chatty               = flag.Bool("test.v", false, "verbose: print additional output")
   237  	count                = flag.Uint("test.count", 1, "run tests and benchmarks `n` times")
   238  	coverProfile         = flag.String("test.coverprofile", "", "write a coverage profile to `file`")
   239  	match                = flag.String("test.run", "", "run only tests and examples matching `regexp`")
   240  	memProfile           = flag.String("test.memprofile", "", "write a memory profile to `file`")
   241  	memProfileRate       = flag.Int("test.memprofilerate", 0, "set memory profiling `rate` (see runtime.MemProfileRate)")
   242  	cpuProfile           = flag.String("test.cpuprofile", "", "write a cpu profile to `file`")
   243  	blockProfile         = flag.String("test.blockprofile", "", "write a goroutine blocking profile to `file`")
   244  	blockProfileRate     = flag.Int("test.blockprofilerate", 1, "set blocking profile `rate` (see runtime.SetBlockProfileRate)")
   245  	mutexProfile         = flag.String("test.mutexprofile", "", "write a mutex contention profile to the named file after execution")
   246  	mutexProfileFraction = flag.Int("test.mutexprofilefraction", 1, "if >= 0, calls runtime.SetMutexProfileFraction()")
   247  	traceFile            = flag.String("test.trace", "", "write an execution trace to `file`")
   248  	timeout              = flag.Duration("test.timeout", 0, "fail test binary execution after duration `d` (0 means unlimited)")
   249  	cpuListStr           = flag.String("test.cpu", "", "comma-separated `list` of cpu counts to run each test with")
   250  	parallel             = flag.Int("test.parallel", runtime.GOMAXPROCS(0), "run at most `n` tests in parallel")
   251  
   252  	haveExamples bool // are there examples?
   253  
   254  	cpuList []int
   255  )
   256  
   257  // common holds the elements common between T and B and
   258  // captures common methods such as Errorf.
   259  type common struct {
   260  	mu       sync.RWMutex // guards output, failed, and done.
   261  	output   []byte       // Output generated by test or benchmark.
   262  	w        io.Writer    // For flushToParent.
   263  	chatty   bool         // A copy of the chatty flag.
   264  	ran      bool         // Test or benchmark (or one of its subtests) was executed.
   265  	failed   bool         // Test or benchmark has failed.
   266  	skipped  bool         // Test of benchmark has been skipped.
   267  	finished bool         // Test function has completed.
   268  	done     bool         // Test is finished and all subtests have completed.
   269  	hasSub   bool
   270  
   271  	parent   *common
   272  	level    int       // Nesting depth of test or benchmark.
   273  	name     string    // Name of test or benchmark.
   274  	start    time.Time // Time test or benchmark started
   275  	duration time.Duration
   276  	barrier  chan bool // To signal parallel subtests they may start.
   277  	signal   chan bool // To signal a test is done.
   278  	sub      []*T      // Queue of subtests to be run in parallel.
   279  }
   280  
   281  // Short reports whether the -test.short flag is set.
   282  func Short() bool {
   283  	return *short
   284  }
   285  
   286  // Verbose reports whether the -test.v flag is set.
   287  func Verbose() bool {
   288  	return *chatty
   289  }
   290  
   291  // decorate prefixes the string with the file and line of the call site
   292  // and inserts the final newline if needed and indentation tabs for formatting.
   293  func decorate(s string) string {
   294  	_, file, line, ok := runtime.Caller(3) // decorate + log + public function.
   295  	if ok {
   296  		// Truncate file name at last file name separator.
   297  		if index := strings.LastIndex(file, "/"); index >= 0 {
   298  			file = file[index+1:]
   299  		} else if index = strings.LastIndex(file, "\\"); index >= 0 {
   300  			file = file[index+1:]
   301  		}
   302  	} else {
   303  		file = "???"
   304  		line = 1
   305  	}
   306  	buf := new(bytes.Buffer)
   307  	// Every line is indented at least one tab.
   308  	buf.WriteByte('\t')
   309  	fmt.Fprintf(buf, "%s:%d: ", file, line)
   310  	lines := strings.Split(s, "\n")
   311  	if l := len(lines); l > 1 && lines[l-1] == "" {
   312  		lines = lines[:l-1]
   313  	}
   314  	for i, line := range lines {
   315  		if i > 0 {
   316  			// Second and subsequent lines are indented an extra tab.
   317  			buf.WriteString("\n\t\t")
   318  		}
   319  		buf.WriteString(line)
   320  	}
   321  	buf.WriteByte('\n')
   322  	return buf.String()
   323  }
   324  
   325  // flushToParent writes c.output to the parent after first writing the header
   326  // with the given format and arguments.
   327  func (c *common) flushToParent(format string, args ...interface{}) {
   328  	p := c.parent
   329  	p.mu.Lock()
   330  	defer p.mu.Unlock()
   331  
   332  	fmt.Fprintf(p.w, format, args...)
   333  
   334  	c.mu.Lock()
   335  	defer c.mu.Unlock()
   336  	io.Copy(p.w, bytes.NewReader(c.output))
   337  	c.output = c.output[:0]
   338  }
   339  
   340  type indenter struct {
   341  	c *common
   342  }
   343  
   344  func (w indenter) Write(b []byte) (n int, err error) {
   345  	n = len(b)
   346  	for len(b) > 0 {
   347  		end := bytes.IndexByte(b, '\n')
   348  		if end == -1 {
   349  			end = len(b)
   350  		} else {
   351  			end++
   352  		}
   353  		// An indent of 4 spaces will neatly align the dashes with the status
   354  		// indicator of the parent.
   355  		const indent = "    "
   356  		w.c.output = append(w.c.output, indent...)
   357  		w.c.output = append(w.c.output, b[:end]...)
   358  		b = b[end:]
   359  	}
   360  	return
   361  }
   362  
   363  // fmtDuration returns a string representing d in the form "87.00s".
   364  func fmtDuration(d time.Duration) string {
   365  	return fmt.Sprintf("%.2fs", d.Seconds())
   366  }
   367  
   368  // TB is the interface common to T and B.
   369  type TB interface {
   370  	Error(args ...interface{})
   371  	Errorf(format string, args ...interface{})
   372  	Fail()
   373  	FailNow()
   374  	Failed() bool
   375  	Fatal(args ...interface{})
   376  	Fatalf(format string, args ...interface{})
   377  	Log(args ...interface{})
   378  	Logf(format string, args ...interface{})
   379  	Name() string
   380  	Skip(args ...interface{})
   381  	SkipNow()
   382  	Skipf(format string, args ...interface{})
   383  	Skipped() bool
   384  
   385  	// A private method to prevent users implementing the
   386  	// interface and so future additions to it will not
   387  	// violate Go 1 compatibility.
   388  	private()
   389  }
   390  
   391  var _ TB = (*T)(nil)
   392  var _ TB = (*B)(nil)
   393  
   394  // T is a type passed to Test functions to manage test state and support formatted test logs.
   395  // Logs are accumulated during execution and dumped to standard output when done.
   396  //
   397  // A test ends when its Test function returns or calls any of the methods
   398  // FailNow, Fatal, Fatalf, SkipNow, Skip, or Skipf. Those methods, as well as
   399  // the Parallel method, must be called only from the goroutine running the
   400  // Test function.
   401  //
   402  // The other reporting methods, such as the variations of Log and Error,
   403  // may be called simultaneously from multiple goroutines.
   404  type T struct {
   405  	common
   406  	isParallel bool
   407  	context    *testContext // For running tests and subtests.
   408  }
   409  
   410  func (c *common) private() {}
   411  
   412  // Name returns the name of the running test or benchmark.
   413  func (c *common) Name() string {
   414  	return c.name
   415  }
   416  
   417  func (c *common) setRan() {
   418  	if c.parent != nil {
   419  		c.parent.setRan()
   420  	}
   421  	c.mu.Lock()
   422  	defer c.mu.Unlock()
   423  	c.ran = true
   424  }
   425  
   426  // Fail marks the function as having failed but continues execution.
   427  func (c *common) Fail() {
   428  	if c.parent != nil {
   429  		c.parent.Fail()
   430  	}
   431  	c.mu.Lock()
   432  	defer c.mu.Unlock()
   433  	// c.done needs to be locked to synchronize checks to c.done in parent tests.
   434  	if c.done {
   435  		panic("Fail in goroutine after " + c.name + " has completed")
   436  	}
   437  	c.failed = true
   438  }
   439  
   440  // Failed reports whether the function has failed.
   441  func (c *common) Failed() bool {
   442  	c.mu.RLock()
   443  	defer c.mu.RUnlock()
   444  	return c.failed
   445  }
   446  
   447  // FailNow marks the function as having failed and stops its execution.
   448  // Execution will continue at the next test or benchmark.
   449  // FailNow must be called from the goroutine running the
   450  // test or benchmark function, not from other goroutines
   451  // created during the test. Calling FailNow does not stop
   452  // those other goroutines.
   453  func (c *common) FailNow() {
   454  	c.Fail()
   455  
   456  	// Calling runtime.Goexit will exit the goroutine, which
   457  	// will run the deferred functions in this goroutine,
   458  	// which will eventually run the deferred lines in tRunner,
   459  	// which will signal to the test loop that this test is done.
   460  	//
   461  	// A previous version of this code said:
   462  	//
   463  	//	c.duration = ...
   464  	//	c.signal <- c.self
   465  	//	runtime.Goexit()
   466  	//
   467  	// This previous version duplicated code (those lines are in
   468  	// tRunner no matter what), but worse the goroutine teardown
   469  	// implicit in runtime.Goexit was not guaranteed to complete
   470  	// before the test exited. If a test deferred an important cleanup
   471  	// function (like removing temporary files), there was no guarantee
   472  	// it would run on a test failure. Because we send on c.signal during
   473  	// a top-of-stack deferred function now, we know that the send
   474  	// only happens after any other stacked defers have completed.
   475  	c.finished = true
   476  	runtime.Goexit()
   477  }
   478  
   479  // log generates the output. It's always at the same stack depth.
   480  func (c *common) log(s string) {
   481  	c.mu.Lock()
   482  	defer c.mu.Unlock()
   483  	c.output = append(c.output, decorate(s)...)
   484  }
   485  
   486  // Log formats its arguments using default formatting, analogous to Println,
   487  // and records the text in the error log. For tests, the text will be printed only if
   488  // the test fails or the -test.v flag is set. For benchmarks, the text is always
   489  // printed to avoid having performance depend on the value of the -test.v flag.
   490  func (c *common) Log(args ...interface{}) { c.log(fmt.Sprintln(args...)) }
   491  
   492  // Logf formats its arguments according to the format, analogous to Printf, and
   493  // records the text in the error log. A final newline is added if not provided. For
   494  // tests, the text will be printed only if the test fails or the -test.v flag is
   495  // set. For benchmarks, the text is always printed to avoid having performance
   496  // depend on the value of the -test.v flag.
   497  func (c *common) Logf(format string, args ...interface{}) { c.log(fmt.Sprintf(format, args...)) }
   498  
   499  // Error is equivalent to Log followed by Fail.
   500  func (c *common) Error(args ...interface{}) {
   501  	c.log(fmt.Sprintln(args...))
   502  	c.Fail()
   503  }
   504  
   505  // Errorf is equivalent to Logf followed by Fail.
   506  func (c *common) Errorf(format string, args ...interface{}) {
   507  	c.log(fmt.Sprintf(format, args...))
   508  	c.Fail()
   509  }
   510  
   511  // Fatal is equivalent to Log followed by FailNow.
   512  func (c *common) Fatal(args ...interface{}) {
   513  	c.log(fmt.Sprintln(args...))
   514  	c.FailNow()
   515  }
   516  
   517  // Fatalf is equivalent to Logf followed by FailNow.
   518  func (c *common) Fatalf(format string, args ...interface{}) {
   519  	c.log(fmt.Sprintf(format, args...))
   520  	c.FailNow()
   521  }
   522  
   523  // Skip is equivalent to Log followed by SkipNow.
   524  func (c *common) Skip(args ...interface{}) {
   525  	c.log(fmt.Sprintln(args...))
   526  	c.SkipNow()
   527  }
   528  
   529  // Skipf is equivalent to Logf followed by SkipNow.
   530  func (c *common) Skipf(format string, args ...interface{}) {
   531  	c.log(fmt.Sprintf(format, args...))
   532  	c.SkipNow()
   533  }
   534  
   535  // SkipNow marks the test as having been skipped and stops its execution.
   536  // If a test fails (see Error, Errorf, Fail) and is then skipped,
   537  // it is still considered to have failed.
   538  // Execution will continue at the next test or benchmark. See also FailNow.
   539  // SkipNow must be called from the goroutine running the test, not from
   540  // other goroutines created during the test. Calling SkipNow does not stop
   541  // those other goroutines.
   542  func (c *common) SkipNow() {
   543  	c.skip()
   544  	c.finished = true
   545  	runtime.Goexit()
   546  }
   547  
   548  func (c *common) skip() {
   549  	c.mu.Lock()
   550  	defer c.mu.Unlock()
   551  	c.skipped = true
   552  }
   553  
   554  // Skipped reports whether the test was skipped.
   555  func (c *common) Skipped() bool {
   556  	c.mu.RLock()
   557  	defer c.mu.RUnlock()
   558  	return c.skipped
   559  }
   560  
   561  // Parallel signals that this test is to be run in parallel with (and only with)
   562  // other parallel tests.
   563  func (t *T) Parallel() {
   564  	if t.isParallel {
   565  		panic("testing: t.Parallel called multiple times")
   566  	}
   567  	t.isParallel = true
   568  
   569  	// We don't want to include the time we spend waiting for serial tests
   570  	// in the test duration. Record the elapsed time thus far and reset the
   571  	// timer afterwards.
   572  	t.duration += time.Since(t.start)
   573  
   574  	// Add to the list of tests to be released by the parent.
   575  	t.parent.sub = append(t.parent.sub, t)
   576  
   577  	t.signal <- true   // Release calling test.
   578  	<-t.parent.barrier // Wait for the parent test to complete.
   579  	t.context.waitParallel()
   580  	t.start = time.Now()
   581  }
   582  
   583  // An internal type but exported because it is cross-package; part of the implementation
   584  // of the "go test" command.
   585  type InternalTest struct {
   586  	Name string
   587  	F    func(*T)
   588  }
   589  
   590  func tRunner(t *T, fn func(t *T)) {
   591  	// When this goroutine is done, either because fn(t)
   592  	// returned normally or because a test failure triggered
   593  	// a call to runtime.Goexit, record the duration and send
   594  	// a signal saying that the test is done.
   595  	defer func() {
   596  		t.duration += time.Now().Sub(t.start)
   597  		// If the test panicked, print any test output before dying.
   598  		err := recover()
   599  		if !t.finished && err == nil {
   600  			err = fmt.Errorf("test executed panic(nil) or runtime.Goexit")
   601  		}
   602  		if err != nil {
   603  			t.Fail()
   604  			t.report()
   605  			panic(err)
   606  		}
   607  
   608  		if len(t.sub) > 0 {
   609  			// Run parallel subtests.
   610  			// Decrease the running count for this test.
   611  			t.context.release()
   612  			// Release the parallel subtests.
   613  			close(t.barrier)
   614  			// Wait for subtests to complete.
   615  			for _, sub := range t.sub {
   616  				<-sub.signal
   617  			}
   618  			if !t.isParallel {
   619  				// Reacquire the count for sequential tests. See comment in Run.
   620  				t.context.waitParallel()
   621  			}
   622  		} else if t.isParallel {
   623  			// Only release the count for this test if it was run as a parallel
   624  			// test. See comment in Run method.
   625  			t.context.release()
   626  		}
   627  		t.report() // Report after all subtests have finished.
   628  
   629  		// Do not lock t.done to allow race detector to detect race in case
   630  		// the user does not appropriately synchronizes a goroutine.
   631  		t.done = true
   632  		if t.parent != nil && !t.hasSub {
   633  			t.setRan()
   634  		}
   635  		t.signal <- true
   636  	}()
   637  
   638  	t.start = time.Now()
   639  	fn(t)
   640  	t.finished = true
   641  }
   642  
   643  // Run runs f as a subtest of t called name. It reports whether f succeeded.
   644  // Run will block until all its parallel subtests have completed.
   645  func (t *T) Run(name string, f func(t *T)) bool {
   646  	t.hasSub = true
   647  	testName, ok := t.context.match.fullName(&t.common, name)
   648  	if !ok {
   649  		return true
   650  	}
   651  	t = &T{
   652  		common: common{
   653  			barrier: make(chan bool),
   654  			signal:  make(chan bool),
   655  			name:    testName,
   656  			parent:  &t.common,
   657  			level:   t.level + 1,
   658  			chatty:  t.chatty,
   659  		},
   660  		context: t.context,
   661  	}
   662  	t.w = indenter{&t.common}
   663  
   664  	if t.chatty {
   665  		// Print directly to root's io.Writer so there is no delay.
   666  		root := t.parent
   667  		for ; root.parent != nil; root = root.parent {
   668  		}
   669  		fmt.Fprintf(root.w, "=== RUN   %s\n", t.name)
   670  	}
   671  	// Instead of reducing the running count of this test before calling the
   672  	// tRunner and increasing it afterwards, we rely on tRunner keeping the
   673  	// count correct. This ensures that a sequence of sequential tests runs
   674  	// without being preempted, even when their parent is a parallel test. This
   675  	// may especially reduce surprises if *parallel == 1.
   676  	go tRunner(t, f)
   677  	<-t.signal
   678  	return !t.failed
   679  }
   680  
   681  // testContext holds all fields that are common to all tests. This includes
   682  // synchronization primitives to run at most *parallel tests.
   683  type testContext struct {
   684  	match *matcher
   685  
   686  	mu sync.Mutex
   687  
   688  	// Channel used to signal tests that are ready to be run in parallel.
   689  	startParallel chan bool
   690  
   691  	// running is the number of tests currently running in parallel.
   692  	// This does not include tests that are waiting for subtests to complete.
   693  	running int
   694  
   695  	// numWaiting is the number tests waiting to be run in parallel.
   696  	numWaiting int
   697  
   698  	// maxParallel is a copy of the parallel flag.
   699  	maxParallel int
   700  }
   701  
   702  func newTestContext(maxParallel int, m *matcher) *testContext {
   703  	return &testContext{
   704  		match:         m,
   705  		startParallel: make(chan bool),
   706  		maxParallel:   maxParallel,
   707  		running:       1, // Set the count to 1 for the main (sequential) test.
   708  	}
   709  }
   710  
   711  func (c *testContext) waitParallel() {
   712  	c.mu.Lock()
   713  	if c.running < c.maxParallel {
   714  		c.running++
   715  		c.mu.Unlock()
   716  		return
   717  	}
   718  	c.numWaiting++
   719  	c.mu.Unlock()
   720  	<-c.startParallel
   721  }
   722  
   723  func (c *testContext) release() {
   724  	c.mu.Lock()
   725  	if c.numWaiting == 0 {
   726  		c.running--
   727  		c.mu.Unlock()
   728  		return
   729  	}
   730  	c.numWaiting--
   731  	c.mu.Unlock()
   732  	c.startParallel <- true // Pick a waiting test to be run.
   733  }
   734  
   735  // An internal function but exported because it is cross-package; part of the implementation
   736  // of the "go test" command.
   737  func Main(matchString func(pat, str string) (bool, error), tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample) {
   738  	os.Exit(MainStart(matchString, tests, benchmarks, examples).Run())
   739  }
   740  
   741  // M is a type passed to a TestMain function to run the actual tests.
   742  type M struct {
   743  	matchString func(pat, str string) (bool, error)
   744  	tests       []InternalTest
   745  	benchmarks  []InternalBenchmark
   746  	examples    []InternalExample
   747  }
   748  
   749  // MainStart is meant for use by tests generated by 'go test'.
   750  // It is not meant to be called directly and is not subject to the Go 1 compatibility document.
   751  // It may change signature from release to release.
   752  func MainStart(matchString func(pat, str string) (bool, error), tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample) *M {
   753  	return &M{
   754  		matchString: matchString,
   755  		tests:       tests,
   756  		benchmarks:  benchmarks,
   757  		examples:    examples,
   758  	}
   759  }
   760  
   761  // Run runs the tests. It returns an exit code to pass to os.Exit.
   762  func (m *M) Run() int {
   763  	// TestMain may have already called flag.Parse.
   764  	if !flag.Parsed() {
   765  		flag.Parse()
   766  	}
   767  
   768  	parseCpuList()
   769  
   770  	before()
   771  	startAlarm()
   772  	haveExamples = len(m.examples) > 0
   773  	testRan, testOk := runTests(m.matchString, m.tests)
   774  	exampleRan, exampleOk := runExamples(m.matchString, m.examples)
   775  	if !testRan && !exampleRan {
   776  		fmt.Fprintln(os.Stderr, "testing: warning: no tests to run")
   777  	}
   778  	if !testOk || !exampleOk || !runBenchmarks(m.matchString, m.benchmarks) {
   779  		fmt.Println("FAIL")
   780  		after()
   781  		return 1
   782  	}
   783  
   784  	fmt.Println("PASS")
   785  	after()
   786  	return 0
   787  }
   788  
   789  func (t *T) report() {
   790  	if t.parent == nil {
   791  		return
   792  	}
   793  	dstr := fmtDuration(t.duration)
   794  	format := "--- %s: %s (%s)\n"
   795  	if t.Failed() {
   796  		t.flushToParent(format, "FAIL", t.name, dstr)
   797  	} else if t.chatty {
   798  		if t.Skipped() {
   799  			t.flushToParent(format, "SKIP", t.name, dstr)
   800  		} else {
   801  			t.flushToParent(format, "PASS", t.name, dstr)
   802  		}
   803  	}
   804  }
   805  
   806  // An internal function but exported because it is cross-package; part of the implementation
   807  // of the "go test" command.
   808  func RunTests(matchString func(pat, str string) (bool, error), tests []InternalTest) (ok bool) {
   809  	ran, ok := runTests(matchString, tests)
   810  	if !ran && !haveExamples {
   811  		fmt.Fprintln(os.Stderr, "testing: warning: no tests to run")
   812  	}
   813  	return ok
   814  }
   815  
   816  func runTests(matchString func(pat, str string) (bool, error), tests []InternalTest) (ran, ok bool) {
   817  	ok = true
   818  	for _, procs := range cpuList {
   819  		runtime.GOMAXPROCS(procs)
   820  		ctx := newTestContext(*parallel, newMatcher(matchString, *match, "-test.run"))
   821  		t := &T{
   822  			common: common{
   823  				signal:  make(chan bool),
   824  				barrier: make(chan bool),
   825  				w:       os.Stdout,
   826  				chatty:  *chatty,
   827  			},
   828  			context: ctx,
   829  		}
   830  		tRunner(t, func(t *T) {
   831  			for _, test := range tests {
   832  				t.Run(test.Name, test.F)
   833  			}
   834  			// Run catching the signal rather than the tRunner as a separate
   835  			// goroutine to avoid adding a goroutine during the sequential
   836  			// phase as this pollutes the stacktrace output when aborting.
   837  			go func() { <-t.signal }()
   838  		})
   839  		ok = ok && !t.Failed()
   840  		ran = ran || t.ran
   841  	}
   842  	return ran, ok
   843  }
   844  
   845  // before runs before all testing.
   846  func before() {
   847  	if *memProfileRate > 0 {
   848  		runtime.MemProfileRate = *memProfileRate
   849  	}
   850  	if *cpuProfile != "" {
   851  		f, err := os.Create(toOutputDir(*cpuProfile))
   852  		if err != nil {
   853  			fmt.Fprintf(os.Stderr, "testing: %s", err)
   854  			return
   855  		}
   856  		if err := pprof.StartCPUProfile(f); err != nil {
   857  			fmt.Fprintf(os.Stderr, "testing: can't start cpu profile: %s", err)
   858  			f.Close()
   859  			return
   860  		}
   861  		// Could save f so after can call f.Close; not worth the effort.
   862  	}
   863  	if *traceFile != "" {
   864  		f, err := os.Create(toOutputDir(*traceFile))
   865  		if err != nil {
   866  			fmt.Fprintf(os.Stderr, "testing: %s", err)
   867  			return
   868  		}
   869  		if err := trace.Start(f); err != nil {
   870  			fmt.Fprintf(os.Stderr, "testing: can't start tracing: %s", err)
   871  			f.Close()
   872  			return
   873  		}
   874  		// Could save f so after can call f.Close; not worth the effort.
   875  	}
   876  	if *blockProfile != "" && *blockProfileRate >= 0 {
   877  		runtime.SetBlockProfileRate(*blockProfileRate)
   878  	}
   879  	if *mutexProfile != "" && *mutexProfileFraction >= 0 {
   880  		runtime.SetMutexProfileFraction(*mutexProfileFraction)
   881  	}
   882  	if *coverProfile != "" && cover.Mode == "" {
   883  		fmt.Fprintf(os.Stderr, "testing: cannot use -test.coverprofile because test binary was not built with coverage enabled\n")
   884  		os.Exit(2)
   885  	}
   886  }
   887  
   888  // after runs after all testing.
   889  func after() {
   890  	if *cpuProfile != "" {
   891  		pprof.StopCPUProfile() // flushes profile to disk
   892  	}
   893  	if *traceFile != "" {
   894  		trace.Stop() // flushes trace to disk
   895  	}
   896  	if *memProfile != "" {
   897  		f, err := os.Create(toOutputDir(*memProfile))
   898  		if err != nil {
   899  			fmt.Fprintf(os.Stderr, "testing: %s\n", err)
   900  			os.Exit(2)
   901  		}
   902  		runtime.GC() // materialize all statistics
   903  		if err = pprof.WriteHeapProfile(f); err != nil {
   904  			fmt.Fprintf(os.Stderr, "testing: can't write %s: %s\n", *memProfile, err)
   905  			os.Exit(2)
   906  		}
   907  		f.Close()
   908  	}
   909  	if *blockProfile != "" && *blockProfileRate >= 0 {
   910  		f, err := os.Create(toOutputDir(*blockProfile))
   911  		if err != nil {
   912  			fmt.Fprintf(os.Stderr, "testing: %s\n", err)
   913  			os.Exit(2)
   914  		}
   915  		if err = pprof.Lookup("block").WriteTo(f, 0); err != nil {
   916  			fmt.Fprintf(os.Stderr, "testing: can't write %s: %s\n", *blockProfile, err)
   917  			os.Exit(2)
   918  		}
   919  		f.Close()
   920  	}
   921  	if *mutexProfile != "" && *mutexProfileFraction >= 0 {
   922  		f, err := os.Create(toOutputDir(*mutexProfile))
   923  		if err != nil {
   924  			fmt.Fprintf(os.Stderr, "testing: %s\n", err)
   925  			os.Exit(2)
   926  		}
   927  		if err = pprof.Lookup("mutex").WriteTo(f, 0); err != nil {
   928  			fmt.Fprintf(os.Stderr, "testing: can't write %s: %s\n", *blockProfile, err)
   929  			os.Exit(2)
   930  		}
   931  		f.Close()
   932  	}
   933  	if cover.Mode != "" {
   934  		coverReport()
   935  	}
   936  }
   937  
   938  // toOutputDir returns the file name relocated, if required, to outputDir.
   939  // Simple implementation to avoid pulling in path/filepath.
   940  func toOutputDir(path string) string {
   941  	if *outputDir == "" || path == "" {
   942  		return path
   943  	}
   944  	if runtime.GOOS == "windows" {
   945  		// On Windows, it's clumsy, but we can be almost always correct
   946  		// by just looking for a drive letter and a colon.
   947  		// Absolute paths always have a drive letter (ignoring UNC).
   948  		// Problem: if path == "C:A" and outputdir == "C:\Go" it's unclear
   949  		// what to do, but even then path/filepath doesn't help.
   950  		// TODO: Worth doing better? Probably not, because we're here only
   951  		// under the management of go test.
   952  		if len(path) >= 2 {
   953  			letter, colon := path[0], path[1]
   954  			if ('a' <= letter && letter <= 'z' || 'A' <= letter && letter <= 'Z') && colon == ':' {
   955  				// If path starts with a drive letter we're stuck with it regardless.
   956  				return path
   957  			}
   958  		}
   959  	}
   960  	if os.IsPathSeparator(path[0]) {
   961  		return path
   962  	}
   963  	return fmt.Sprintf("%s%c%s", *outputDir, os.PathSeparator, path)
   964  }
   965  
   966  var timer *time.Timer
   967  
   968  // startAlarm starts an alarm if requested.
   969  func startAlarm() {
   970  	if *timeout > 0 {
   971  		timer = time.AfterFunc(*timeout, func() {
   972  			debug.SetTraceback("all")
   973  			panic(fmt.Sprintf("test timed out after %v", *timeout))
   974  		})
   975  	}
   976  }
   977  
   978  // stopAlarm turns off the alarm.
   979  func stopAlarm() {
   980  	if *timeout > 0 {
   981  		timer.Stop()
   982  	}
   983  }
   984  
   985  func parseCpuList() {
   986  	for _, val := range strings.Split(*cpuListStr, ",") {
   987  		val = strings.TrimSpace(val)
   988  		if val == "" {
   989  			continue
   990  		}
   991  		cpu, err := strconv.Atoi(val)
   992  		if err != nil || cpu <= 0 {
   993  			fmt.Fprintf(os.Stderr, "testing: invalid value %q for -test.cpu\n", val)
   994  			os.Exit(1)
   995  		}
   996  		for i := uint(0); i < *count; i++ {
   997  			cpuList = append(cpuList, cpu)
   998  		}
   999  	}
  1000  	if cpuList == nil {
  1001  		for i := uint(0); i < *count; i++ {
  1002  			cpuList = append(cpuList, runtime.GOMAXPROCS(-1))
  1003  		}
  1004  	}
  1005  }