Black Lives Matter. Support the Equal Justice Initiative.

Source file src/testing/testing.go

Documentation: testing

     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 BenchmarkRandInt(b *testing.B) {
    41  //         for i := 0; i < b.N; i++ {
    42  //             rand.Int()
    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  //     BenchmarkRandInt-8   	68453040	        17.8 ns/op
    50  // means that the loop ran 68453040 times at a speed of 17.8 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(5) {
   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. m.Run will return an exit
   221  // code that may be passed to os.Exit. If TestMain returns, the test wrapper
   222  // will pass the result of m.Run to os.Exit itself.
   223  //
   224  // When TestMain is called, flag.Parse has not been run. If TestMain depends on
   225  // command-line flags, including those of the testing package, it should call
   226  // flag.Parse explicitly. Command line flags are always parsed by the time test
   227  // or benchmark functions run.
   228  //
   229  // A simple implementation of TestMain is:
   230  //
   231  //	func TestMain(m *testing.M) {
   232  //		// call flag.Parse() here if TestMain uses flags
   233  //		os.Exit(m.Run())
   234  //	}
   235  //
   236  package testing
   237  
   238  import (
   239  	"bytes"
   240  	"errors"
   241  	"flag"
   242  	"fmt"
   243  	"internal/race"
   244  	"io"
   245  	"io/ioutil"
   246  	"os"
   247  	"runtime"
   248  	"runtime/debug"
   249  	"runtime/trace"
   250  	"strconv"
   251  	"strings"
   252  	"sync"
   253  	"sync/atomic"
   254  	"time"
   255  )
   256  
   257  var initRan bool
   258  
   259  // Init registers testing flags. These flags are automatically registered by
   260  // the "go test" command before running test functions, so Init is only needed
   261  // when calling functions such as Benchmark without using "go test".
   262  //
   263  // Init has no effect if it was already called.
   264  func Init() {
   265  	if initRan {
   266  		return
   267  	}
   268  	initRan = true
   269  	// The short flag requests that tests run more quickly, but its functionality
   270  	// is provided by test writers themselves. The testing package is just its
   271  	// home. The all.bash installation script sets it to make installation more
   272  	// efficient, but by default the flag is off so a plain "go test" will do a
   273  	// full test of the package.
   274  	short = flag.Bool("test.short", false, "run smaller test suite to save time")
   275  
   276  	// The failfast flag requests that test execution stop after the first test failure.
   277  	failFast = flag.Bool("test.failfast", false, "do not start new tests after the first test failure")
   278  
   279  	// The directory in which to create profile files and the like. When run from
   280  	// "go test", the binary always runs in the source directory for the package;
   281  	// this flag lets "go test" tell the binary to write the files in the directory where
   282  	// the "go test" command is run.
   283  	outputDir = flag.String("test.outputdir", "", "write profiles to `dir`")
   284  	// Report as tests are run; default is silent for success.
   285  	chatty = flag.Bool("test.v", false, "verbose: print additional output")
   286  	count = flag.Uint("test.count", 1, "run tests and benchmarks `n` times")
   287  	coverProfile = flag.String("test.coverprofile", "", "write a coverage profile to `file`")
   288  	matchList = flag.String("test.list", "", "list tests, examples, and benchmarks matching `regexp` then exit")
   289  	match = flag.String("test.run", "", "run only tests and examples matching `regexp`")
   290  	memProfile = flag.String("test.memprofile", "", "write an allocation profile to `file`")
   291  	memProfileRate = flag.Int("test.memprofilerate", 0, "set memory allocation profiling `rate` (see runtime.MemProfileRate)")
   292  	cpuProfile = flag.String("test.cpuprofile", "", "write a cpu profile to `file`")
   293  	blockProfile = flag.String("test.blockprofile", "", "write a goroutine blocking profile to `file`")
   294  	blockProfileRate = flag.Int("test.blockprofilerate", 1, "set blocking profile `rate` (see runtime.SetBlockProfileRate)")
   295  	mutexProfile = flag.String("test.mutexprofile", "", "write a mutex contention profile to the named file after execution")
   296  	mutexProfileFraction = flag.Int("test.mutexprofilefraction", 1, "if >= 0, calls runtime.SetMutexProfileFraction()")
   297  	traceFile = flag.String("test.trace", "", "write an execution trace to `file`")
   298  	timeout = flag.Duration("test.timeout", 0, "panic test binary after duration `d` (default 0, timeout disabled)")
   299  	cpuListStr = flag.String("test.cpu", "", "comma-separated `list` of cpu counts to run each test with")
   300  	parallel = flag.Int("test.parallel", runtime.GOMAXPROCS(0), "run at most `n` tests in parallel")
   301  	testlog = flag.String("test.testlogfile", "", "write test action log to `file` (for use only by cmd/go)")
   302  
   303  	initBenchmarkFlags()
   304  }
   305  
   306  var (
   307  	// Flags, registered during Init.
   308  	short                *bool
   309  	failFast             *bool
   310  	outputDir            *string
   311  	chatty               *bool
   312  	count                *uint
   313  	coverProfile         *string
   314  	matchList            *string
   315  	match                *string
   316  	memProfile           *string
   317  	memProfileRate       *int
   318  	cpuProfile           *string
   319  	blockProfile         *string
   320  	blockProfileRate     *int
   321  	mutexProfile         *string
   322  	mutexProfileFraction *int
   323  	traceFile            *string
   324  	timeout              *time.Duration
   325  	cpuListStr           *string
   326  	parallel             *int
   327  	testlog              *string
   328  	printer              *testPrinter
   329  
   330  	haveExamples bool // are there examples?
   331  
   332  	cpuList     []int
   333  	testlogFile *os.File
   334  
   335  	numFailed uint32 // number of test failures
   336  )
   337  
   338  type testPrinter struct {
   339  	chatty bool
   340  
   341  	lastNameMu sync.Mutex // guards lastName
   342  	lastName   string     // last printed test name in chatty mode
   343  }
   344  
   345  func newTestPrinter(chatty bool) *testPrinter {
   346  	return &testPrinter{
   347  		chatty: chatty,
   348  	}
   349  }
   350  
   351  func (p *testPrinter) Print(testName, out string) {
   352  	p.Fprint(os.Stdout, testName, out)
   353  }
   354  
   355  func (p *testPrinter) Fprint(w io.Writer, testName, out string) {
   356  	p.lastNameMu.Lock()
   357  	defer p.lastNameMu.Unlock()
   358  
   359  	if !p.chatty ||
   360  		strings.HasPrefix(out, "--- PASS: ") ||
   361  		strings.HasPrefix(out, "--- FAIL: ") ||
   362  		strings.HasPrefix(out, "--- SKIP: ") ||
   363  		strings.HasPrefix(out, "=== RUN   ") ||
   364  		strings.HasPrefix(out, "=== CONT  ") ||
   365  		strings.HasPrefix(out, "=== PAUSE ") {
   366  		// If we're buffering test output (!p.chatty), we don't really care which
   367  		// test is emitting which line so long as they are serialized.
   368  		//
   369  		// If the message already implies an association with a specific new test,
   370  		// we don't need to check what the old test name was or log an extra CONT
   371  		// line for it. (We're updating it anyway, and the current message already
   372  		// includes the test name.)
   373  		p.lastName = testName
   374  		fmt.Fprint(w, out)
   375  		return
   376  	}
   377  
   378  	if p.lastName == "" {
   379  		p.lastName = testName
   380  	} else if p.lastName != testName {
   381  		// Always printed as-is, with 0 decoration or indentation. So, we skip
   382  		// printing to w.
   383  		fmt.Printf("=== CONT  %s\n", testName)
   384  		p.lastName = testName
   385  	}
   386  	fmt.Fprint(w, out)
   387  }
   388  
   389  // The maximum number of stack frames to go through when skipping helper functions for
   390  // the purpose of decorating log messages.
   391  const maxStackLen = 50
   392  
   393  // common holds the elements common between T and B and
   394  // captures common methods such as Errorf.
   395  type common struct {
   396  	mu          sync.RWMutex        // guards this group of fields
   397  	output      []byte              // Output generated by test or benchmark.
   398  	w           io.Writer           // For flushToParent.
   399  	ran         bool                // Test or benchmark (or one of its subtests) was executed.
   400  	failed      bool                // Test or benchmark has failed.
   401  	skipped     bool                // Test of benchmark has been skipped.
   402  	done        bool                // Test is finished and all subtests have completed.
   403  	helpers     map[string]struct{} // functions to be skipped when writing file/line info
   404  	cleanup     func()              // optional function to be called at the end of the test
   405  	cleanupName string              // Name of the cleanup function.
   406  	cleanupPc   []uintptr           // The stack trace at the point where Cleanup was called.
   407  
   408  	chatty     bool   // A copy of the chatty flag.
   409  	bench      bool   // Whether the current test is a benchmark.
   410  	finished   bool   // Test function has completed.
   411  	hasSub     int32  // Written atomically.
   412  	raceErrors int    // Number of races detected during test.
   413  	runner     string // Function name of tRunner running the test.
   414  
   415  	parent   *common
   416  	level    int       // Nesting depth of test or benchmark.
   417  	creator  []uintptr // If level > 0, the stack trace at the point where the parent called t.Run.
   418  	name     string    // Name of test or benchmark.
   419  	start    time.Time // Time test or benchmark started
   420  	duration time.Duration
   421  	barrier  chan bool // To signal parallel subtests they may start.
   422  	signal   chan bool // To signal a test is done.
   423  	sub      []*T      // Queue of subtests to be run in parallel.
   424  
   425  	tempDirOnce sync.Once
   426  	tempDir     string
   427  	tempDirErr  error
   428  	tempDirSeq  int32
   429  }
   430  
   431  // Short reports whether the -test.short flag is set.
   432  func Short() bool {
   433  	if short == nil {
   434  		panic("testing: Short called before Init")
   435  	}
   436  	// Catch code that calls this from TestMain without first calling flag.Parse.
   437  	if !flag.Parsed() {
   438  		panic("testing: Short called before Parse")
   439  	}
   440  
   441  	return *short
   442  }
   443  
   444  // CoverMode reports what the test coverage mode is set to. The
   445  // values are "set", "count", or "atomic". The return value will be
   446  // empty if test coverage is not enabled.
   447  func CoverMode() string {
   448  	return cover.Mode
   449  }
   450  
   451  // Verbose reports whether the -test.v flag is set.
   452  func Verbose() bool {
   453  	// Same as in Short.
   454  	if chatty == nil {
   455  		panic("testing: Verbose called before Init")
   456  	}
   457  	if !flag.Parsed() {
   458  		panic("testing: Verbose called before Parse")
   459  	}
   460  	return *chatty
   461  }
   462  
   463  // frameSkip searches, starting after skip frames, for the first caller frame
   464  // in a function not marked as a helper and returns that frame.
   465  // The search stops if it finds a tRunner function that
   466  // was the entry point into the test and the test is not a subtest.
   467  // This function must be called with c.mu held.
   468  func (c *common) frameSkip(skip int) runtime.Frame {
   469  	// If the search continues into the parent test, we'll have to hold
   470  	// its mu temporarily. If we then return, we need to unlock it.
   471  	shouldUnlock := false
   472  	defer func() {
   473  		if shouldUnlock {
   474  			c.mu.Unlock()
   475  		}
   476  	}()
   477  	var pc [maxStackLen]uintptr
   478  	// Skip two extra frames to account for this function
   479  	// and runtime.Callers itself.
   480  	n := runtime.Callers(skip+2, pc[:])
   481  	if n == 0 {
   482  		panic("testing: zero callers found")
   483  	}
   484  	frames := runtime.CallersFrames(pc[:n])
   485  	var firstFrame, prevFrame, frame runtime.Frame
   486  	for more := true; more; prevFrame = frame {
   487  		frame, more = frames.Next()
   488  		if frame.Function == c.cleanupName {
   489  			frames = runtime.CallersFrames(c.cleanupPc)
   490  			continue
   491  		}
   492  		if firstFrame.PC == 0 {
   493  			firstFrame = frame
   494  		}
   495  		if frame.Function == c.runner {
   496  			// We've gone up all the way to the tRunner calling
   497  			// the test function (so the user must have
   498  			// called tb.Helper from inside that test function).
   499  			// If this is a top-level test, only skip up to the test function itself.
   500  			// If we're in a subtest, continue searching in the parent test,
   501  			// starting from the point of the call to Run which created this subtest.
   502  			if c.level > 1 {
   503  				frames = runtime.CallersFrames(c.creator)
   504  				parent := c.parent
   505  				// We're no longer looking at the current c after this point,
   506  				// so we should unlock its mu, unless it's the original receiver,
   507  				// in which case our caller doesn't expect us to do that.
   508  				if shouldUnlock {
   509  					c.mu.Unlock()
   510  				}
   511  				c = parent
   512  				// Remember to unlock c.mu when we no longer need it, either
   513  				// because we went up another nesting level, or because we
   514  				// returned.
   515  				shouldUnlock = true
   516  				c.mu.Lock()
   517  				continue
   518  			}
   519  			return prevFrame
   520  		}
   521  		if _, ok := c.helpers[frame.Function]; !ok {
   522  			// Found a frame that wasn't inside a helper function.
   523  			return frame
   524  		}
   525  	}
   526  	return firstFrame
   527  }
   528  
   529  // decorate prefixes the string with the file and line of the call site
   530  // and inserts the final newline if needed and indentation spaces for formatting.
   531  // This function must be called with c.mu held.
   532  func (c *common) decorate(s string, skip int) string {
   533  	frame := c.frameSkip(skip)
   534  	file := frame.File
   535  	line := frame.Line
   536  	if file != "" {
   537  		// Truncate file name at last file name separator.
   538  		if index := strings.LastIndex(file, "/"); index >= 0 {
   539  			file = file[index+1:]
   540  		} else if index = strings.LastIndex(file, "\\"); index >= 0 {
   541  			file = file[index+1:]
   542  		}
   543  	} else {
   544  		file = "???"
   545  	}
   546  	if line == 0 {
   547  		line = 1
   548  	}
   549  	buf := new(strings.Builder)
   550  	// Every line is indented at least 4 spaces.
   551  	buf.WriteString("    ")
   552  	fmt.Fprintf(buf, "%s:%d: ", file, line)
   553  	lines := strings.Split(s, "\n")
   554  	if l := len(lines); l > 1 && lines[l-1] == "" {
   555  		lines = lines[:l-1]
   556  	}
   557  	for i, line := range lines {
   558  		if i > 0 {
   559  			// Second and subsequent lines are indented an additional 4 spaces.
   560  			buf.WriteString("\n        ")
   561  		}
   562  		buf.WriteString(line)
   563  	}
   564  	buf.WriteByte('\n')
   565  	return buf.String()
   566  }
   567  
   568  // flushToParent writes c.output to the parent after first writing the header
   569  // with the given format and arguments.
   570  func (c *common) flushToParent(testName, format string, args ...interface{}) {
   571  	p := c.parent
   572  	p.mu.Lock()
   573  	defer p.mu.Unlock()
   574  
   575  	printer.Fprint(p.w, testName, fmt.Sprintf(format, args...))
   576  
   577  	c.mu.Lock()
   578  	defer c.mu.Unlock()
   579  	io.Copy(p.w, bytes.NewReader(c.output))
   580  	c.output = c.output[:0]
   581  }
   582  
   583  type indenter struct {
   584  	c *common
   585  }
   586  
   587  func (w indenter) Write(b []byte) (n int, err error) {
   588  	n = len(b)
   589  	for len(b) > 0 {
   590  		end := bytes.IndexByte(b, '\n')
   591  		if end == -1 {
   592  			end = len(b)
   593  		} else {
   594  			end++
   595  		}
   596  		// An indent of 4 spaces will neatly align the dashes with the status
   597  		// indicator of the parent.
   598  		const indent = "    "
   599  		w.c.output = append(w.c.output, indent...)
   600  		w.c.output = append(w.c.output, b[:end]...)
   601  		b = b[end:]
   602  	}
   603  	return
   604  }
   605  
   606  // fmtDuration returns a string representing d in the form "87.00s".
   607  func fmtDuration(d time.Duration) string {
   608  	return fmt.Sprintf("%.2fs", d.Seconds())
   609  }
   610  
   611  // TB is the interface common to T and B.
   612  type TB interface {
   613  	Cleanup(func())
   614  	Error(args ...interface{})
   615  	Errorf(format string, args ...interface{})
   616  	Fail()
   617  	FailNow()
   618  	Failed() bool
   619  	Fatal(args ...interface{})
   620  	Fatalf(format string, args ...interface{})
   621  	Helper()
   622  	Log(args ...interface{})
   623  	Logf(format string, args ...interface{})
   624  	Name() string
   625  	Skip(args ...interface{})
   626  	SkipNow()
   627  	Skipf(format string, args ...interface{})
   628  	Skipped() bool
   629  	TempDir() string
   630  
   631  	// A private method to prevent users implementing the
   632  	// interface and so future additions to it will not
   633  	// violate Go 1 compatibility.
   634  	private()
   635  }
   636  
   637  var _ TB = (*T)(nil)
   638  var _ TB = (*B)(nil)
   639  
   640  // T is a type passed to Test functions to manage test state and support formatted test logs.
   641  //
   642  // A test ends when its Test function returns or calls any of the methods
   643  // FailNow, Fatal, Fatalf, SkipNow, Skip, or Skipf. Those methods, as well as
   644  // the Parallel method, must be called only from the goroutine running the
   645  // Test function.
   646  //
   647  // The other reporting methods, such as the variations of Log and Error,
   648  // may be called simultaneously from multiple goroutines.
   649  type T struct {
   650  	common
   651  	isParallel bool
   652  	context    *testContext // For running tests and subtests.
   653  }
   654  
   655  func (c *common) private() {}
   656  
   657  // Name returns the name of the running test or benchmark.
   658  func (c *common) Name() string {
   659  	return c.name
   660  }
   661  
   662  func (c *common) setRan() {
   663  	if c.parent != nil {
   664  		c.parent.setRan()
   665  	}
   666  	c.mu.Lock()
   667  	defer c.mu.Unlock()
   668  	c.ran = true
   669  }
   670  
   671  // Fail marks the function as having failed but continues execution.
   672  func (c *common) Fail() {
   673  	if c.parent != nil {
   674  		c.parent.Fail()
   675  	}
   676  	c.mu.Lock()
   677  	defer c.mu.Unlock()
   678  	// c.done needs to be locked to synchronize checks to c.done in parent tests.
   679  	if c.done {
   680  		panic("Fail in goroutine after " + c.name + " has completed")
   681  	}
   682  	c.failed = true
   683  }
   684  
   685  // Failed reports whether the function has failed.
   686  func (c *common) Failed() bool {
   687  	c.mu.RLock()
   688  	failed := c.failed
   689  	c.mu.RUnlock()
   690  	return failed || c.raceErrors+race.Errors() > 0
   691  }
   692  
   693  // FailNow marks the function as having failed and stops its execution
   694  // by calling runtime.Goexit (which then runs all deferred calls in the
   695  // current goroutine).
   696  // Execution will continue at the next test or benchmark.
   697  // FailNow must be called from the goroutine running the
   698  // test or benchmark function, not from other goroutines
   699  // created during the test. Calling FailNow does not stop
   700  // those other goroutines.
   701  func (c *common) FailNow() {
   702  	c.Fail()
   703  
   704  	// Calling runtime.Goexit will exit the goroutine, which
   705  	// will run the deferred functions in this goroutine,
   706  	// which will eventually run the deferred lines in tRunner,
   707  	// which will signal to the test loop that this test is done.
   708  	//
   709  	// A previous version of this code said:
   710  	//
   711  	//	c.duration = ...
   712  	//	c.signal <- c.self
   713  	//	runtime.Goexit()
   714  	//
   715  	// This previous version duplicated code (those lines are in
   716  	// tRunner no matter what), but worse the goroutine teardown
   717  	// implicit in runtime.Goexit was not guaranteed to complete
   718  	// before the test exited. If a test deferred an important cleanup
   719  	// function (like removing temporary files), there was no guarantee
   720  	// it would run on a test failure. Because we send on c.signal during
   721  	// a top-of-stack deferred function now, we know that the send
   722  	// only happens after any other stacked defers have completed.
   723  	c.finished = true
   724  	runtime.Goexit()
   725  }
   726  
   727  // log generates the output. It's always at the same stack depth.
   728  func (c *common) log(s string) {
   729  	c.logDepth(s, 3) // logDepth + log + public function
   730  }
   731  
   732  // logDepth generates the output at an arbitrary stack depth.
   733  func (c *common) logDepth(s string, depth int) {
   734  	c.mu.Lock()
   735  	defer c.mu.Unlock()
   736  	if c.done {
   737  		// This test has already finished. Try and log this message
   738  		// with our parent. If we don't have a parent, panic.
   739  		for parent := c.parent; parent != nil; parent = parent.parent {
   740  			parent.mu.Lock()
   741  			defer parent.mu.Unlock()
   742  			if !parent.done {
   743  				parent.output = append(parent.output, parent.decorate(s, depth+1)...)
   744  				return
   745  			}
   746  		}
   747  		panic("Log in goroutine after " + c.name + " has completed")
   748  	} else {
   749  		if c.chatty {
   750  			if c.bench {
   751  				// Benchmarks don't print === CONT, so we should skip the test
   752  				// printer and just print straight to stdout.
   753  				fmt.Print(c.decorate(s, depth+1))
   754  			} else {
   755  				printer.Print(c.name, c.decorate(s, depth+1))
   756  			}
   757  
   758  			return
   759  		}
   760  		c.output = append(c.output, c.decorate(s, depth+1)...)
   761  	}
   762  }
   763  
   764  // Log formats its arguments using default formatting, analogous to Println,
   765  // and records the text in the error log. For tests, the text will be printed only if
   766  // the test fails or the -test.v flag is set. For benchmarks, the text is always
   767  // printed to avoid having performance depend on the value of the -test.v flag.
   768  func (c *common) Log(args ...interface{}) { c.log(fmt.Sprintln(args...)) }
   769  
   770  // Logf formats its arguments according to the format, analogous to Printf, and
   771  // records the text in the error log. A final newline is added if not provided. For
   772  // tests, the text will be printed only if the test fails or the -test.v flag is
   773  // set. For benchmarks, the text is always printed to avoid having performance
   774  // depend on the value of the -test.v flag.
   775  func (c *common) Logf(format string, args ...interface{}) { c.log(fmt.Sprintf(format, args...)) }
   776  
   777  // Error is equivalent to Log followed by Fail.
   778  func (c *common) Error(args ...interface{}) {
   779  	c.log(fmt.Sprintln(args...))
   780  	c.Fail()
   781  }
   782  
   783  // Errorf is equivalent to Logf followed by Fail.
   784  func (c *common) Errorf(format string, args ...interface{}) {
   785  	c.log(fmt.Sprintf(format, args...))
   786  	c.Fail()
   787  }
   788  
   789  // Fatal is equivalent to Log followed by FailNow.
   790  func (c *common) Fatal(args ...interface{}) {
   791  	c.log(fmt.Sprintln(args...))
   792  	c.FailNow()
   793  }
   794  
   795  // Fatalf is equivalent to Logf followed by FailNow.
   796  func (c *common) Fatalf(format string, args ...interface{}) {
   797  	c.log(fmt.Sprintf(format, args...))
   798  	c.FailNow()
   799  }
   800  
   801  // Skip is equivalent to Log followed by SkipNow.
   802  func (c *common) Skip(args ...interface{}) {
   803  	c.log(fmt.Sprintln(args...))
   804  	c.SkipNow()
   805  }
   806  
   807  // Skipf is equivalent to Logf followed by SkipNow.
   808  func (c *common) Skipf(format string, args ...interface{}) {
   809  	c.log(fmt.Sprintf(format, args...))
   810  	c.SkipNow()
   811  }
   812  
   813  // SkipNow marks the test as having been skipped and stops its execution
   814  // by calling runtime.Goexit.
   815  // If a test fails (see Error, Errorf, Fail) and is then skipped,
   816  // it is still considered to have failed.
   817  // Execution will continue at the next test or benchmark. See also FailNow.
   818  // SkipNow must be called from the goroutine running the test, not from
   819  // other goroutines created during the test. Calling SkipNow does not stop
   820  // those other goroutines.
   821  func (c *common) SkipNow() {
   822  	c.skip()
   823  	c.finished = true
   824  	runtime.Goexit()
   825  }
   826  
   827  func (c *common) skip() {
   828  	c.mu.Lock()
   829  	defer c.mu.Unlock()
   830  	c.skipped = true
   831  }
   832  
   833  // Skipped reports whether the test was skipped.
   834  func (c *common) Skipped() bool {
   835  	c.mu.RLock()
   836  	defer c.mu.RUnlock()
   837  	return c.skipped
   838  }
   839  
   840  // Helper marks the calling function as a test helper function.
   841  // When printing file and line information, that function will be skipped.
   842  // Helper may be called simultaneously from multiple goroutines.
   843  func (c *common) Helper() {
   844  	c.mu.Lock()
   845  	defer c.mu.Unlock()
   846  	if c.helpers == nil {
   847  		c.helpers = make(map[string]struct{})
   848  	}
   849  	c.helpers[callerName(1)] = struct{}{}
   850  }
   851  
   852  // Cleanup registers a function to be called when the test and all its
   853  // subtests complete. Cleanup functions will be called in last added,
   854  // first called order.
   855  func (c *common) Cleanup(f func()) {
   856  	c.mu.Lock()
   857  	defer c.mu.Unlock()
   858  	oldCleanup := c.cleanup
   859  	oldCleanupPc := c.cleanupPc
   860  	c.cleanup = func() {
   861  		if oldCleanup != nil {
   862  			defer func() {
   863  				c.mu.Lock()
   864  				c.cleanupPc = oldCleanupPc
   865  				c.mu.Unlock()
   866  				oldCleanup()
   867  			}()
   868  		}
   869  		c.mu.Lock()
   870  		c.cleanupName = callerName(0)
   871  		c.mu.Unlock()
   872  		f()
   873  	}
   874  	var pc [maxStackLen]uintptr
   875  	// Skip two extra frames to account for this function and runtime.Callers itself.
   876  	n := runtime.Callers(2, pc[:])
   877  	c.cleanupPc = pc[:n]
   878  }
   879  
   880  var tempDirReplacer struct {
   881  	sync.Once
   882  	r *strings.Replacer
   883  }
   884  
   885  // TempDir returns a temporary directory for the test to use.
   886  // The directory is automatically removed by Cleanup when the test and
   887  // all its subtests complete.
   888  // Each subsequent call to t.TempDir returns a unique directory;
   889  // if the directory creation fails, TempDir terminates the test by calling Fatal.
   890  func (c *common) TempDir() string {
   891  	// Use a single parent directory for all the temporary directories
   892  	// created by a test, each numbered sequentially.
   893  	c.tempDirOnce.Do(func() {
   894  		c.Helper()
   895  
   896  		// ioutil.TempDir doesn't like path separators in its pattern,
   897  		// so mangle the name to accommodate subtests.
   898  		tempDirReplacer.Do(func() {
   899  			tempDirReplacer.r = strings.NewReplacer("/", "_", "\\", "_", ":", "_")
   900  		})
   901  		pattern := tempDirReplacer.r.Replace(c.Name())
   902  
   903  		c.tempDir, c.tempDirErr = ioutil.TempDir("", pattern)
   904  		if c.tempDirErr == nil {
   905  			c.Cleanup(func() {
   906  				if err := os.RemoveAll(c.tempDir); err != nil {
   907  					c.Errorf("TempDir RemoveAll cleanup: %v", err)
   908  				}
   909  			})
   910  		}
   911  	})
   912  	if c.tempDirErr != nil {
   913  		c.Fatalf("TempDir: %v", c.tempDirErr)
   914  	}
   915  	seq := atomic.AddInt32(&c.tempDirSeq, 1)
   916  	dir := fmt.Sprintf("%s%c%03d", c.tempDir, os.PathSeparator, seq)
   917  	if err := os.Mkdir(dir, 0777); err != nil {
   918  		c.Fatalf("TempDir: %v", err)
   919  	}
   920  	return dir
   921  }
   922  
   923  // panicHanding is an argument to runCleanup.
   924  type panicHandling int
   925  
   926  const (
   927  	normalPanic panicHandling = iota
   928  	recoverAndReturnPanic
   929  )
   930  
   931  // runCleanup is called at the end of the test.
   932  // If catchPanic is true, this will catch panics, and return the recovered
   933  // value if any.
   934  func (c *common) runCleanup(ph panicHandling) (panicVal interface{}) {
   935  	c.mu.Lock()
   936  	cleanup := c.cleanup
   937  	c.cleanup = nil
   938  	c.mu.Unlock()
   939  	if cleanup == nil {
   940  		return nil
   941  	}
   942  
   943  	if ph == recoverAndReturnPanic {
   944  		defer func() {
   945  			panicVal = recover()
   946  		}()
   947  	}
   948  
   949  	cleanup()
   950  	return nil
   951  }
   952  
   953  // callerName gives the function name (qualified with a package path)
   954  // for the caller after skip frames (where 0 means the current function).
   955  func callerName(skip int) string {
   956  	// Make room for the skip PC.
   957  	var pc [1]uintptr
   958  	n := runtime.Callers(skip+2, pc[:]) // skip + runtime.Callers + callerName
   959  	if n == 0 {
   960  		panic("testing: zero callers found")
   961  	}
   962  	frames := runtime.CallersFrames(pc[:n])
   963  	frame, _ := frames.Next()
   964  	return frame.Function
   965  }
   966  
   967  // Parallel signals that this test is to be run in parallel with (and only with)
   968  // other parallel tests. When a test is run multiple times due to use of
   969  // -test.count or -test.cpu, multiple instances of a single test never run in
   970  // parallel with each other.
   971  func (t *T) Parallel() {
   972  	if t.isParallel {
   973  		panic("testing: t.Parallel called multiple times")
   974  	}
   975  	t.isParallel = true
   976  
   977  	// We don't want to include the time we spend waiting for serial tests
   978  	// in the test duration. Record the elapsed time thus far and reset the
   979  	// timer afterwards.
   980  	t.duration += time.Since(t.start)
   981  
   982  	// Add to the list of tests to be released by the parent.
   983  	t.parent.sub = append(t.parent.sub, t)
   984  	t.raceErrors += race.Errors()
   985  
   986  	if t.chatty {
   987  		// Print directly to root's io.Writer so there is no delay.
   988  		root := t.parent
   989  		for ; root.parent != nil; root = root.parent {
   990  		}
   991  		root.mu.Lock()
   992  		// Unfortunately, even though PAUSE indicates that the named test is *no
   993  		// longer* running, cmd/test2json interprets it as changing the active test
   994  		// for the purpose of log parsing. We could fix cmd/test2json, but that
   995  		// won't fix existing deployments of third-party tools that already shell
   996  		// out to older builds of cmd/test2json — so merely fixing cmd/test2json
   997  		// isn't enough for now.
   998  		printer.Fprint(root.w, t.name, fmt.Sprintf("=== PAUSE %s\n", t.name))
   999  		root.mu.Unlock()
  1000  	}
  1001  
  1002  	t.signal <- true   // Release calling test.
  1003  	<-t.parent.barrier // Wait for the parent test to complete.
  1004  	t.context.waitParallel()
  1005  
  1006  	if t.chatty {
  1007  		// Print directly to root's io.Writer so there is no delay.
  1008  		root := t.parent
  1009  		for ; root.parent != nil; root = root.parent {
  1010  		}
  1011  		root.mu.Lock()
  1012  		printer.Fprint(root.w, t.name, fmt.Sprintf("=== CONT  %s\n", t.name))
  1013  		root.mu.Unlock()
  1014  	}
  1015  
  1016  	t.start = time.Now()
  1017  	t.raceErrors += -race.Errors()
  1018  }
  1019  
  1020  // InternalTest is an internal type but exported because it is cross-package;
  1021  // it is part of the implementation of the "go test" command.
  1022  type InternalTest struct {
  1023  	Name string
  1024  	F    func(*T)
  1025  }
  1026  
  1027  var errNilPanicOrGoexit = errors.New("test executed panic(nil) or runtime.Goexit")
  1028  
  1029  func tRunner(t *T, fn func(t *T)) {
  1030  	t.runner = callerName(0)
  1031  
  1032  	// When this goroutine is done, either because fn(t)
  1033  	// returned normally or because a test failure triggered
  1034  	// a call to runtime.Goexit, record the duration and send
  1035  	// a signal saying that the test is done.
  1036  	defer func() {
  1037  		if t.Failed() {
  1038  			atomic.AddUint32(&numFailed, 1)
  1039  		}
  1040  
  1041  		if t.raceErrors+race.Errors() > 0 {
  1042  			t.Errorf("race detected during execution of test")
  1043  		}
  1044  
  1045  		// If the test panicked, print any test output before dying.
  1046  		err := recover()
  1047  		signal := true
  1048  		if !t.finished && err == nil {
  1049  			err = errNilPanicOrGoexit
  1050  			for p := t.parent; p != nil; p = p.parent {
  1051  				if p.finished {
  1052  					t.Errorf("%v: subtest may have called FailNow on a parent test", err)
  1053  					err = nil
  1054  					signal = false
  1055  					break
  1056  				}
  1057  			}
  1058  		}
  1059  
  1060  		doPanic := func(err interface{}) {
  1061  			t.Fail()
  1062  			if r := t.runCleanup(recoverAndReturnPanic); r != nil {
  1063  				t.Logf("cleanup panicked with %v", r)
  1064  			}
  1065  			// Flush the output log up to the root before dying.
  1066  			for root := &t.common; root.parent != nil; root = root.parent {
  1067  				root.mu.Lock()
  1068  				root.duration += time.Since(root.start)
  1069  				d := root.duration
  1070  				root.mu.Unlock()
  1071  				root.flushToParent(root.name, "--- FAIL: %s (%s)\n", root.name, fmtDuration(d))
  1072  				if r := root.parent.runCleanup(recoverAndReturnPanic); r != nil {
  1073  					fmt.Fprintf(root.parent.w, "cleanup panicked with %v", r)
  1074  				}
  1075  			}
  1076  			panic(err)
  1077  		}
  1078  		if err != nil {
  1079  			doPanic(err)
  1080  		}
  1081  
  1082  		t.duration += time.Since(t.start)
  1083  
  1084  		if len(t.sub) > 0 {
  1085  			// Run parallel subtests.
  1086  			// Decrease the running count for this test.
  1087  			t.context.release()
  1088  			// Release the parallel subtests.
  1089  			close(t.barrier)
  1090  			// Wait for subtests to complete.
  1091  			for _, sub := range t.sub {
  1092  				<-sub.signal
  1093  			}
  1094  			cleanupStart := time.Now()
  1095  			err := t.runCleanup(recoverAndReturnPanic)
  1096  			t.duration += time.Since(cleanupStart)
  1097  			if err != nil {
  1098  				doPanic(err)
  1099  			}
  1100  			if !t.isParallel {
  1101  				// Reacquire the count for sequential tests. See comment in Run.
  1102  				t.context.waitParallel()
  1103  			}
  1104  		} else if t.isParallel {
  1105  			// Only release the count for this test if it was run as a parallel
  1106  			// test. See comment in Run method.
  1107  			t.context.release()
  1108  		}
  1109  		t.report() // Report after all subtests have finished.
  1110  
  1111  		// Do not lock t.done to allow race detector to detect race in case
  1112  		// the user does not appropriately synchronizes a goroutine.
  1113  		t.done = true
  1114  		if t.parent != nil && atomic.LoadInt32(&t.hasSub) == 0 {
  1115  			t.setRan()
  1116  		}
  1117  		t.signal <- signal
  1118  	}()
  1119  	defer func() {
  1120  		if len(t.sub) == 0 {
  1121  			t.runCleanup(normalPanic)
  1122  		}
  1123  	}()
  1124  
  1125  	t.start = time.Now()
  1126  	t.raceErrors = -race.Errors()
  1127  	fn(t)
  1128  
  1129  	// code beyond here will not be executed when FailNow is invoked
  1130  	t.finished = true
  1131  }
  1132  
  1133  // Run runs f as a subtest of t called name. It runs f in a separate goroutine
  1134  // and blocks until f returns or calls t.Parallel to become a parallel test.
  1135  // Run reports whether f succeeded (or at least did not fail before calling t.Parallel).
  1136  //
  1137  // Run may be called simultaneously from multiple goroutines, but all such calls
  1138  // must return before the outer test function for t returns.
  1139  func (t *T) Run(name string, f func(t *T)) bool {
  1140  	atomic.StoreInt32(&t.hasSub, 1)
  1141  	testName, ok, _ := t.context.match.fullName(&t.common, name)
  1142  	if !ok || shouldFailFast() {
  1143  		return true
  1144  	}
  1145  	// Record the stack trace at the point of this call so that if the subtest
  1146  	// function - which runs in a separate stack - is marked as a helper, we can
  1147  	// continue walking the stack into the parent test.
  1148  	var pc [maxStackLen]uintptr
  1149  	n := runtime.Callers(2, pc[:])
  1150  	t = &T{
  1151  		common: common{
  1152  			barrier: make(chan bool),
  1153  			signal:  make(chan bool),
  1154  			name:    testName,
  1155  			parent:  &t.common,
  1156  			level:   t.level + 1,
  1157  			creator: pc[:n],
  1158  			chatty:  t.chatty,
  1159  		},
  1160  		context: t.context,
  1161  	}
  1162  	t.w = indenter{&t.common}
  1163  
  1164  	if t.chatty {
  1165  		// Print directly to root's io.Writer so there is no delay.
  1166  		root := t.parent
  1167  		for ; root.parent != nil; root = root.parent {
  1168  		}
  1169  		root.mu.Lock()
  1170  		printer.Fprint(root.w, t.name, fmt.Sprintf("=== RUN   %s\n", t.name))
  1171  		root.mu.Unlock()
  1172  	}
  1173  	// Instead of reducing the running count of this test before calling the
  1174  	// tRunner and increasing it afterwards, we rely on tRunner keeping the
  1175  	// count correct. This ensures that a sequence of sequential tests runs
  1176  	// without being preempted, even when their parent is a parallel test. This
  1177  	// may especially reduce surprises if *parallel == 1.
  1178  	go tRunner(t, f)
  1179  	if !<-t.signal {
  1180  		// At this point, it is likely that FailNow was called on one of the
  1181  		// parent tests by one of the subtests. Continue aborting up the chain.
  1182  		runtime.Goexit()
  1183  	}
  1184  	return !t.failed
  1185  }
  1186  
  1187  // Deadline reports the time at which the test binary will have
  1188  // exceeded the timeout specified by the -timeout flag.
  1189  //
  1190  // The ok result is false if the -timeout flag indicates “no timeout” (0).
  1191  func (t *T) Deadline() (deadline time.Time, ok bool) {
  1192  	deadline = t.context.deadline
  1193  	return deadline, !deadline.IsZero()
  1194  }
  1195  
  1196  // testContext holds all fields that are common to all tests. This includes
  1197  // synchronization primitives to run at most *parallel tests.
  1198  type testContext struct {
  1199  	match    *matcher
  1200  	deadline time.Time
  1201  
  1202  	mu sync.Mutex
  1203  
  1204  	// Channel used to signal tests that are ready to be run in parallel.
  1205  	startParallel chan bool
  1206  
  1207  	// running is the number of tests currently running in parallel.
  1208  	// This does not include tests that are waiting for subtests to complete.
  1209  	running int
  1210  
  1211  	// numWaiting is the number tests waiting to be run in parallel.
  1212  	numWaiting int
  1213  
  1214  	// maxParallel is a copy of the parallel flag.
  1215  	maxParallel int
  1216  }
  1217  
  1218  func newTestContext(maxParallel int, m *matcher) *testContext {
  1219  	return &testContext{
  1220  		match:         m,
  1221  		startParallel: make(chan bool),
  1222  		maxParallel:   maxParallel,
  1223  		running:       1, // Set the count to 1 for the main (sequential) test.
  1224  	}
  1225  }
  1226  
  1227  func (c *testContext) waitParallel() {
  1228  	c.mu.Lock()
  1229  	if c.running < c.maxParallel {
  1230  		c.running++
  1231  		c.mu.Unlock()
  1232  		return
  1233  	}
  1234  	c.numWaiting++
  1235  	c.mu.Unlock()
  1236  	<-c.startParallel
  1237  }
  1238  
  1239  func (c *testContext) release() {
  1240  	c.mu.Lock()
  1241  	if c.numWaiting == 0 {
  1242  		c.running--
  1243  		c.mu.Unlock()
  1244  		return
  1245  	}
  1246  	c.numWaiting--
  1247  	c.mu.Unlock()
  1248  	c.startParallel <- true // Pick a waiting test to be run.
  1249  }
  1250  
  1251  // No one should be using func Main anymore.
  1252  // See the doc comment on func Main and use MainStart instead.
  1253  var errMain = errors.New("testing: unexpected use of func Main")
  1254  
  1255  type matchStringOnly func(pat, str string) (bool, error)
  1256  
  1257  func (f matchStringOnly) MatchString(pat, str string) (bool, error)   { return f(pat, str) }
  1258  func (f matchStringOnly) StartCPUProfile(w io.Writer) error           { return errMain }
  1259  func (f matchStringOnly) StopCPUProfile()                             {}
  1260  func (f matchStringOnly) WriteProfileTo(string, io.Writer, int) error { return errMain }
  1261  func (f matchStringOnly) ImportPath() string                          { return "" }
  1262  func (f matchStringOnly) StartTestLog(io.Writer)                      {}
  1263  func (f matchStringOnly) StopTestLog() error                          { return errMain }
  1264  
  1265  // Main is an internal function, part of the implementation of the "go test" command.
  1266  // It was exported because it is cross-package and predates "internal" packages.
  1267  // It is no longer used by "go test" but preserved, as much as possible, for other
  1268  // systems that simulate "go test" using Main, but Main sometimes cannot be updated as
  1269  // new functionality is added to the testing package.
  1270  // Systems simulating "go test" should be updated to use MainStart.
  1271  func Main(matchString func(pat, str string) (bool, error), tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample) {
  1272  	os.Exit(MainStart(matchStringOnly(matchString), tests, benchmarks, examples).Run())
  1273  }
  1274  
  1275  // M is a type passed to a TestMain function to run the actual tests.
  1276  type M struct {
  1277  	deps       testDeps
  1278  	tests      []InternalTest
  1279  	benchmarks []InternalBenchmark
  1280  	examples   []InternalExample
  1281  
  1282  	timer     *time.Timer
  1283  	afterOnce sync.Once
  1284  
  1285  	numRun int
  1286  
  1287  	// value to pass to os.Exit, the outer test func main
  1288  	// harness calls os.Exit with this code. See #34129.
  1289  	exitCode int
  1290  }
  1291  
  1292  // testDeps is an internal interface of functionality that is
  1293  // passed into this package by a test's generated main package.
  1294  // The canonical implementation of this interface is
  1295  // testing/internal/testdeps's TestDeps.
  1296  type testDeps interface {
  1297  	ImportPath() string
  1298  	MatchString(pat, str string) (bool, error)
  1299  	StartCPUProfile(io.Writer) error
  1300  	StopCPUProfile()
  1301  	StartTestLog(io.Writer)
  1302  	StopTestLog() error
  1303  	WriteProfileTo(string, io.Writer, int) error
  1304  }
  1305  
  1306  // MainStart is meant for use by tests generated by 'go test'.
  1307  // It is not meant to be called directly and is not subject to the Go 1 compatibility document.
  1308  // It may change signature from release to release.
  1309  func MainStart(deps testDeps, tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample) *M {
  1310  	Init()
  1311  	return &M{
  1312  		deps:       deps,
  1313  		tests:      tests,
  1314  		benchmarks: benchmarks,
  1315  		examples:   examples,
  1316  	}
  1317  }
  1318  
  1319  // Run runs the tests. It returns an exit code to pass to os.Exit.
  1320  func (m *M) Run() (code int) {
  1321  	defer func() {
  1322  		code = m.exitCode
  1323  	}()
  1324  
  1325  	// Count the number of calls to m.Run.
  1326  	// We only ever expected 1, but we didn't enforce that,
  1327  	// and now there are tests in the wild that call m.Run multiple times.
  1328  	// Sigh. golang.org/issue/23129.
  1329  	m.numRun++
  1330  
  1331  	// TestMain may have already called flag.Parse.
  1332  	if !flag.Parsed() {
  1333  		flag.Parse()
  1334  	}
  1335  
  1336  	printer = newTestPrinter(Verbose())
  1337  
  1338  	if *parallel < 1 {
  1339  		fmt.Fprintln(os.Stderr, "testing: -parallel can only be given a positive integer")
  1340  		flag.Usage()
  1341  		m.exitCode = 2
  1342  		return
  1343  	}
  1344  
  1345  	if len(*matchList) != 0 {
  1346  		listTests(m.deps.MatchString, m.tests, m.benchmarks, m.examples)
  1347  		m.exitCode = 0
  1348  		return
  1349  	}
  1350  
  1351  	parseCpuList()
  1352  
  1353  	m.before()
  1354  	defer m.after()
  1355  	deadline := m.startAlarm()
  1356  	haveExamples = len(m.examples) > 0
  1357  	testRan, testOk := runTests(m.deps.MatchString, m.tests, deadline)
  1358  	exampleRan, exampleOk := runExamples(m.deps.MatchString, m.examples)
  1359  	m.stopAlarm()
  1360  	if !testRan && !exampleRan && *matchBenchmarks == "" {
  1361  		fmt.Fprintln(os.Stderr, "testing: warning: no tests to run")
  1362  	}
  1363  	if !testOk || !exampleOk || !runBenchmarks(m.deps.ImportPath(), m.deps.MatchString, m.benchmarks) || race.Errors() > 0 {
  1364  		fmt.Println("FAIL")
  1365  		m.exitCode = 1
  1366  		return
  1367  	}
  1368  
  1369  	fmt.Println("PASS")
  1370  	m.exitCode = 0
  1371  	return
  1372  }
  1373  
  1374  func (t *T) report() {
  1375  	if t.parent == nil {
  1376  		return
  1377  	}
  1378  	dstr := fmtDuration(t.duration)
  1379  	format := "--- %s: %s (%s)\n"
  1380  	if t.Failed() {
  1381  		t.flushToParent(t.name, format, "FAIL", t.name, dstr)
  1382  	} else if t.chatty {
  1383  		if t.Skipped() {
  1384  			t.flushToParent(t.name, format, "SKIP", t.name, dstr)
  1385  		} else {
  1386  			t.flushToParent(t.name, format, "PASS", t.name, dstr)
  1387  		}
  1388  	}
  1389  }
  1390  
  1391  func listTests(matchString func(pat, str string) (bool, error), tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample) {
  1392  	if _, err := matchString(*matchList, "non-empty"); err != nil {
  1393  		fmt.Fprintf(os.Stderr, "testing: invalid regexp in -test.list (%q): %s\n", *matchList, err)
  1394  		os.Exit(1)
  1395  	}
  1396  
  1397  	for _, test := range tests {
  1398  		if ok, _ := matchString(*matchList, test.Name); ok {
  1399  			fmt.Println(test.Name)
  1400  		}
  1401  	}
  1402  	for _, bench := range benchmarks {
  1403  		if ok, _ := matchString(*matchList, bench.Name); ok {
  1404  			fmt.Println(bench.Name)
  1405  		}
  1406  	}
  1407  	for _, example := range examples {
  1408  		if ok, _ := matchString(*matchList, example.Name); ok {
  1409  			fmt.Println(example.Name)
  1410  		}
  1411  	}
  1412  }
  1413  
  1414  // RunTests is an internal function but exported because it is cross-package;
  1415  // it is part of the implementation of the "go test" command.
  1416  func RunTests(matchString func(pat, str string) (bool, error), tests []InternalTest) (ok bool) {
  1417  	var deadline time.Time
  1418  	if *timeout > 0 {
  1419  		deadline = time.Now().Add(*timeout)
  1420  	}
  1421  	ran, ok := runTests(matchString, tests, deadline)
  1422  	if !ran && !haveExamples {
  1423  		fmt.Fprintln(os.Stderr, "testing: warning: no tests to run")
  1424  	}
  1425  	return ok
  1426  }
  1427  
  1428  func runTests(matchString func(pat, str string) (bool, error), tests []InternalTest, deadline time.Time) (ran, ok bool) {
  1429  	ok = true
  1430  	for _, procs := range cpuList {
  1431  		runtime.GOMAXPROCS(procs)
  1432  		for i := uint(0); i < *count; i++ {
  1433  			if shouldFailFast() {
  1434  				break
  1435  			}
  1436  			ctx := newTestContext(*parallel, newMatcher(matchString, *match, "-test.run"))
  1437  			ctx.deadline = deadline
  1438  			t := &T{
  1439  				common: common{
  1440  					signal:  make(chan bool),
  1441  					barrier: make(chan bool),
  1442  					w:       os.Stdout,
  1443  					chatty:  *chatty,
  1444  				},
  1445  				context: ctx,
  1446  			}
  1447  			tRunner(t, func(t *T) {
  1448  				for _, test := range tests {
  1449  					t.Run(test.Name, test.F)
  1450  				}
  1451  				// Run catching the signal rather than the tRunner as a separate
  1452  				// goroutine to avoid adding a goroutine during the sequential
  1453  				// phase as this pollutes the stacktrace output when aborting.
  1454  				go func() { <-t.signal }()
  1455  			})
  1456  			ok = ok && !t.Failed()
  1457  			ran = ran || t.ran
  1458  		}
  1459  	}
  1460  	return ran, ok
  1461  }
  1462  
  1463  // before runs before all testing.
  1464  func (m *M) before() {
  1465  	if *memProfileRate > 0 {
  1466  		runtime.MemProfileRate = *memProfileRate
  1467  	}
  1468  	if *cpuProfile != "" {
  1469  		f, err := os.Create(toOutputDir(*cpuProfile))
  1470  		if err != nil {
  1471  			fmt.Fprintf(os.Stderr, "testing: %s\n", err)
  1472  			return
  1473  		}
  1474  		if err := m.deps.StartCPUProfile(f); err != nil {
  1475  			fmt.Fprintf(os.Stderr, "testing: can't start cpu profile: %s\n", err)
  1476  			f.Close()
  1477  			return
  1478  		}
  1479  		// Could save f so after can call f.Close; not worth the effort.
  1480  	}
  1481  	if *traceFile != "" {
  1482  		f, err := os.Create(toOutputDir(*traceFile))
  1483  		if err != nil {
  1484  			fmt.Fprintf(os.Stderr, "testing: %s\n", err)
  1485  			return
  1486  		}
  1487  		if err := trace.Start(f); err != nil {
  1488  			fmt.Fprintf(os.Stderr, "testing: can't start tracing: %s\n", err)
  1489  			f.Close()
  1490  			return
  1491  		}
  1492  		// Could save f so after can call f.Close; not worth the effort.
  1493  	}
  1494  	if *blockProfile != "" && *blockProfileRate >= 0 {
  1495  		runtime.SetBlockProfileRate(*blockProfileRate)
  1496  	}
  1497  	if *mutexProfile != "" && *mutexProfileFraction >= 0 {
  1498  		runtime.SetMutexProfileFraction(*mutexProfileFraction)
  1499  	}
  1500  	if *coverProfile != "" && cover.Mode == "" {
  1501  		fmt.Fprintf(os.Stderr, "testing: cannot use -test.coverprofile because test binary was not built with coverage enabled\n")
  1502  		os.Exit(2)
  1503  	}
  1504  	if *testlog != "" {
  1505  		// Note: Not using toOutputDir.
  1506  		// This file is for use by cmd/go, not users.
  1507  		var f *os.File
  1508  		var err error
  1509  		if m.numRun == 1 {
  1510  			f, err = os.Create(*testlog)
  1511  		} else {
  1512  			f, err = os.OpenFile(*testlog, os.O_WRONLY, 0)
  1513  			if err == nil {
  1514  				f.Seek(0, io.SeekEnd)
  1515  			}
  1516  		}
  1517  		if err != nil {
  1518  			fmt.Fprintf(os.Stderr, "testing: %s\n", err)
  1519  			os.Exit(2)
  1520  		}
  1521  		m.deps.StartTestLog(f)
  1522  		testlogFile = f
  1523  	}
  1524  }
  1525  
  1526  // after runs after all testing.
  1527  func (m *M) after() {
  1528  	m.afterOnce.Do(func() {
  1529  		m.writeProfiles()
  1530  	})
  1531  }
  1532  
  1533  func (m *M) writeProfiles() {
  1534  	if *testlog != "" {
  1535  		if err := m.deps.StopTestLog(); err != nil {
  1536  			fmt.Fprintf(os.Stderr, "testing: can't write %s: %s\n", *testlog, err)
  1537  			os.Exit(2)
  1538  		}
  1539  		if err := testlogFile.Close(); err != nil {
  1540  			fmt.Fprintf(os.Stderr, "testing: can't write %s: %s\n", *testlog, err)
  1541  			os.Exit(2)
  1542  		}
  1543  	}
  1544  	if *cpuProfile != "" {
  1545  		m.deps.StopCPUProfile() // flushes profile to disk
  1546  	}
  1547  	if *traceFile != "" {
  1548  		trace.Stop() // flushes trace to disk
  1549  	}
  1550  	if *memProfile != "" {
  1551  		f, err := os.Create(toOutputDir(*memProfile))
  1552  		if err != nil {
  1553  			fmt.Fprintf(os.Stderr, "testing: %s\n", err)
  1554  			os.Exit(2)
  1555  		}
  1556  		runtime.GC() // materialize all statistics
  1557  		if err = m.deps.WriteProfileTo("allocs", f, 0); err != nil {
  1558  			fmt.Fprintf(os.Stderr, "testing: can't write %s: %s\n", *memProfile, err)
  1559  			os.Exit(2)
  1560  		}
  1561  		f.Close()
  1562  	}
  1563  	if *blockProfile != "" && *blockProfileRate >= 0 {
  1564  		f, err := os.Create(toOutputDir(*blockProfile))
  1565  		if err != nil {
  1566  			fmt.Fprintf(os.Stderr, "testing: %s\n", err)
  1567  			os.Exit(2)
  1568  		}
  1569  		if err = m.deps.WriteProfileTo("block", f, 0); err != nil {
  1570  			fmt.Fprintf(os.Stderr, "testing: can't write %s: %s\n", *blockProfile, err)
  1571  			os.Exit(2)
  1572  		}
  1573  		f.Close()
  1574  	}
  1575  	if *mutexProfile != "" && *mutexProfileFraction >= 0 {
  1576  		f, err := os.Create(toOutputDir(*mutexProfile))
  1577  		if err != nil {
  1578  			fmt.Fprintf(os.Stderr, "testing: %s\n", err)
  1579  			os.Exit(2)
  1580  		}
  1581  		if err = m.deps.WriteProfileTo("mutex", f, 0); err != nil {
  1582  			fmt.Fprintf(os.Stderr, "testing: can't write %s: %s\n", *mutexProfile, err)
  1583  			os.Exit(2)
  1584  		}
  1585  		f.Close()
  1586  	}
  1587  	if cover.Mode != "" {
  1588  		coverReport()
  1589  	}
  1590  }
  1591  
  1592  // toOutputDir returns the file name relocated, if required, to outputDir.
  1593  // Simple implementation to avoid pulling in path/filepath.
  1594  func toOutputDir(path string) string {
  1595  	if *outputDir == "" || path == "" {
  1596  		return path
  1597  	}
  1598  	// On Windows, it's clumsy, but we can be almost always correct
  1599  	// by just looking for a drive letter and a colon.
  1600  	// Absolute paths always have a drive letter (ignoring UNC).
  1601  	// Problem: if path == "C:A" and outputdir == "C:\Go" it's unclear
  1602  	// what to do, but even then path/filepath doesn't help.
  1603  	// TODO: Worth doing better? Probably not, because we're here only
  1604  	// under the management of go test.
  1605  	if runtime.GOOS == "windows" && len(path) >= 2 {
  1606  		letter, colon := path[0], path[1]
  1607  		if ('a' <= letter && letter <= 'z' || 'A' <= letter && letter <= 'Z') && colon == ':' {
  1608  			// If path starts with a drive letter we're stuck with it regardless.
  1609  			return path
  1610  		}
  1611  	}
  1612  	if os.IsPathSeparator(path[0]) {
  1613  		return path
  1614  	}
  1615  	return fmt.Sprintf("%s%c%s", *outputDir, os.PathSeparator, path)
  1616  }
  1617  
  1618  // startAlarm starts an alarm if requested.
  1619  func (m *M) startAlarm() time.Time {
  1620  	if *timeout <= 0 {
  1621  		return time.Time{}
  1622  	}
  1623  
  1624  	deadline := time.Now().Add(*timeout)
  1625  	m.timer = time.AfterFunc(*timeout, func() {
  1626  		m.after()
  1627  		debug.SetTraceback("all")
  1628  		panic(fmt.Sprintf("test timed out after %v", *timeout))
  1629  	})
  1630  	return deadline
  1631  }
  1632  
  1633  // stopAlarm turns off the alarm.
  1634  func (m *M) stopAlarm() {
  1635  	if *timeout > 0 {
  1636  		m.timer.Stop()
  1637  	}
  1638  }
  1639  
  1640  func parseCpuList() {
  1641  	for _, val := range strings.Split(*cpuListStr, ",") {
  1642  		val = strings.TrimSpace(val)
  1643  		if val == "" {
  1644  			continue
  1645  		}
  1646  		cpu, err := strconv.Atoi(val)
  1647  		if err != nil || cpu <= 0 {
  1648  			fmt.Fprintf(os.Stderr, "testing: invalid value %q for -test.cpu\n", val)
  1649  			os.Exit(1)
  1650  		}
  1651  		cpuList = append(cpuList, cpu)
  1652  	}
  1653  	if cpuList == nil {
  1654  		cpuList = append(cpuList, runtime.GOMAXPROCS(-1))
  1655  	}
  1656  }
  1657  
  1658  func shouldFailFast() bool {
  1659  	return *failFast && atomic.LoadUint32(&numFailed) > 0
  1660  }
  1661  

View as plain text