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

View as plain text