github.com/mattn/go@v0.0.0-20171011075504-07f7db3ea99f/src/cmd/go/internal/test/test.go (about)

     1  // Copyright 2011 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 test
     6  
     7  import (
     8  	"bytes"
     9  	"errors"
    10  	"fmt"
    11  	"go/ast"
    12  	"go/build"
    13  	"go/doc"
    14  	"go/parser"
    15  	"go/token"
    16  	"os"
    17  	"os/exec"
    18  	"path"
    19  	"path/filepath"
    20  	"regexp"
    21  	"sort"
    22  	"strings"
    23  	"text/template"
    24  	"time"
    25  	"unicode"
    26  	"unicode/utf8"
    27  
    28  	"cmd/go/internal/base"
    29  	"cmd/go/internal/cfg"
    30  	"cmd/go/internal/load"
    31  	"cmd/go/internal/str"
    32  	"cmd/go/internal/work"
    33  )
    34  
    35  // Break init loop.
    36  func init() {
    37  	CmdTest.Run = runTest
    38  }
    39  
    40  const testUsage = "test [build/test flags] [packages] [build/test flags & test binary flags]"
    41  
    42  var CmdTest = &base.Command{
    43  	CustomFlags: true,
    44  	UsageLine:   testUsage,
    45  	Short:       "test packages",
    46  	Long: `
    47  'Go test' automates testing the packages named by the import paths.
    48  It prints a summary of the test results in the format:
    49  
    50  	ok   archive/tar   0.011s
    51  	FAIL archive/zip   0.022s
    52  	ok   compress/gzip 0.033s
    53  	...
    54  
    55  followed by detailed output for each failed package.
    56  
    57  'Go test' recompiles each package along with any files with names matching
    58  the file pattern "*_test.go".
    59  Files whose names begin with "_" (including "_test.go") or "." are ignored.
    60  These additional files can contain test functions, benchmark functions, and
    61  example functions. See 'go help testfunc' for more.
    62  Each listed package causes the execution of a separate test binary.
    63  
    64  Test files that declare a package with the suffix "_test" will be compiled as a
    65  separate package, and then linked and run with the main test binary.
    66  
    67  The go tool will ignore a directory named "testdata", making it available
    68  to hold ancillary data needed by the tests.
    69  
    70  By default, go test needs no arguments. It compiles and tests the package
    71  with source in the current directory, including tests, and runs the tests.
    72  
    73  The package is built in a temporary directory so it does not interfere with the
    74  non-test installation.
    75  
    76  ` + strings.TrimSpace(testFlag1) + ` See 'go help testflag' for details.
    77  
    78  For more about build flags, see 'go help build'.
    79  For more about specifying packages, see 'go help packages'.
    80  
    81  See also: go build, go vet.
    82  `,
    83  }
    84  
    85  const testFlag1 = `
    86  In addition to the build flags, the flags handled by 'go test' itself are:
    87  
    88  	-args
    89  	    Pass the remainder of the command line (everything after -args)
    90  	    to the test binary, uninterpreted and unchanged.
    91  	    Because this flag consumes the remainder of the command line,
    92  	    the package list (if present) must appear before this flag.
    93  
    94  	-c
    95  	    Compile the test binary to pkg.test but do not run it
    96  	    (where pkg is the last element of the package's import path).
    97  	    The file name can be changed with the -o flag.
    98  
    99  	-exec xprog
   100  	    Run the test binary using xprog. The behavior is the same as
   101  	    in 'go run'. See 'go help run' for details.
   102  
   103  	-i
   104  	    Install packages that are dependencies of the test.
   105  	    Do not run the test.
   106  
   107  	-o file
   108  	    Compile the test binary to the named file.
   109  	    The test still runs (unless -c or -i is specified).
   110  
   111  The test binary also accepts flags that control execution of the test; these
   112  flags are also accessible by 'go test'.
   113  `
   114  
   115  // Usage prints the usage message for 'go test -h' and exits.
   116  func Usage() {
   117  	os.Stderr.WriteString(testUsage + "\n\n" +
   118  		strings.TrimSpace(testFlag1) + "\n\n\t" +
   119  		strings.TrimSpace(testFlag2) + "\n")
   120  	os.Exit(2)
   121  }
   122  
   123  var HelpTestflag = &base.Command{
   124  	UsageLine: "testflag",
   125  	Short:     "description of testing flags",
   126  	Long: `
   127  The 'go test' command takes both flags that apply to 'go test' itself
   128  and flags that apply to the resulting test binary.
   129  
   130  Several of the flags control profiling and write an execution profile
   131  suitable for "go tool pprof"; run "go tool pprof -h" for more
   132  information. The --alloc_space, --alloc_objects, and --show_bytes
   133  options of pprof control how the information is presented.
   134  
   135  The following flags are recognized by the 'go test' command and
   136  control the execution of any test:
   137  
   138  	` + strings.TrimSpace(testFlag2) + `
   139  `,
   140  }
   141  
   142  const testFlag2 = `
   143  	-bench regexp
   144  	    Run only those benchmarks matching a regular expression.
   145  	    By default, no benchmarks are run. 
   146  	    To run all benchmarks, use '-bench .' or '-bench=.'.
   147  	    The regular expression is split by unbracketed slash (/)
   148  	    characters into a sequence of regular expressions, and each
   149  	    part of a benchmark's identifier must match the corresponding
   150  	    element in the sequence, if any. Possible parents of matches
   151  	    are run with b.N=1 to identify sub-benchmarks. For example,
   152  	    given -bench=X/Y, top-level benchmarks matching X are run
   153  	    with b.N=1 to find any sub-benchmarks matching Y, which are
   154  	    then run in full.
   155  
   156  	-benchtime t
   157  	    Run enough iterations of each benchmark to take t, specified
   158  	    as a time.Duration (for example, -benchtime 1h30s).
   159  	    The default is 1 second (1s).
   160  
   161  	-count n
   162  	    Run each test and benchmark n times (default 1).
   163  	    If -cpu is set, run n times for each GOMAXPROCS value.
   164  	    Examples are always run once.
   165  
   166  	-cover
   167  	    Enable coverage analysis.
   168  	    Note that because coverage works by annotating the source
   169  	    code before compilation, compilation and test failures with
   170  	    coverage enabled may report line numbers that don't correspond
   171  	    to the original sources.
   172  
   173  	-covermode set,count,atomic
   174  	    Set the mode for coverage analysis for the package[s]
   175  	    being tested. The default is "set" unless -race is enabled,
   176  	    in which case it is "atomic".
   177  	    The values:
   178  		set: bool: does this statement run?
   179  		count: int: how many times does this statement run?
   180  		atomic: int: count, but correct in multithreaded tests;
   181  			significantly more expensive.
   182  	    Sets -cover.
   183  
   184  	-coverpkg pkg1,pkg2,pkg3
   185  	    Apply coverage analysis in each test to the given list of packages.
   186  	    The default is for each test to analyze only the package being tested.
   187  	    Packages are specified as import paths.
   188  	    Sets -cover.
   189  
   190  	-cpu 1,2,4
   191  	    Specify a list of GOMAXPROCS values for which the tests or
   192  	    benchmarks should be executed. The default is the current value
   193  	    of GOMAXPROCS.
   194  
   195  	-list regexp
   196  	    List tests, benchmarks, or examples matching the regular expression.
   197  	    No tests, benchmarks or examples will be run. This will only
   198  	    list top-level tests. No subtest or subbenchmarks will be shown.
   199  
   200  	-parallel n
   201  	    Allow parallel execution of test functions that call t.Parallel.
   202  	    The value of this flag is the maximum number of tests to run
   203  	    simultaneously; by default, it is set to the value of GOMAXPROCS.
   204  	    Note that -parallel only applies within a single test binary.
   205  	    The 'go test' command may run tests for different packages
   206  	    in parallel as well, according to the setting of the -p flag
   207  	    (see 'go help build').
   208  
   209  	-run regexp
   210  	    Run only those tests and examples matching the regular expression.
   211  	    For tests, the regular expression is split by unbracketed slash (/)
   212  	    characters into a sequence of regular expressions, and each part
   213  	    of a test's identifier must match the corresponding element in
   214  	    the sequence, if any. Note that possible parents of matches are
   215  	    run too, so that -run=X/Y matches and runs and reports the result
   216  	    of all tests matching X, even those without sub-tests matching Y,
   217  	    because it must run them to look for those sub-tests.
   218  
   219  	-short
   220  	    Tell long-running tests to shorten their run time.
   221  	    It is off by default but set during all.bash so that installing
   222  	    the Go tree can run a sanity check but not spend time running
   223  	    exhaustive tests.
   224  
   225  	-timeout d
   226  	    If a test binary runs longer than duration d, panic.
   227  	    The default is 10 minutes (10m).
   228  
   229  	-v
   230  	    Verbose output: log all tests as they are run. Also print all
   231  	    text from Log and Logf calls even if the test succeeds.
   232  
   233  The following flags are also recognized by 'go test' and can be used to
   234  profile the tests during execution:
   235  
   236  	-benchmem
   237  	    Print memory allocation statistics for benchmarks.
   238  
   239  	-blockprofile block.out
   240  	    Write a goroutine blocking profile to the specified file
   241  	    when all tests are complete.
   242  	    Writes test binary as -c would.
   243  
   244  	-blockprofilerate n
   245  	    Control the detail provided in goroutine blocking profiles by
   246  	    calling runtime.SetBlockProfileRate with n.
   247  	    See 'go doc runtime.SetBlockProfileRate'.
   248  	    The profiler aims to sample, on average, one blocking event every
   249  	    n nanoseconds the program spends blocked. By default,
   250  	    if -test.blockprofile is set without this flag, all blocking events
   251  	    are recorded, equivalent to -test.blockprofilerate=1.
   252  
   253  	-coverprofile cover.out
   254  	    Write a coverage profile to the file after all tests have passed.
   255  	    Sets -cover.
   256  
   257  	-cpuprofile cpu.out
   258  	    Write a CPU profile to the specified file before exiting.
   259  	    Writes test binary as -c would.
   260  
   261  	-memprofile mem.out
   262  	    Write a memory profile to the file after all tests have passed.
   263  	    Writes test binary as -c would.
   264  
   265  	-memprofilerate n
   266  	    Enable more precise (and expensive) memory profiles by setting
   267  	    runtime.MemProfileRate. See 'go doc runtime.MemProfileRate'.
   268  	    To profile all memory allocations, use -test.memprofilerate=1
   269  	    and pass --alloc_space flag to the pprof tool.
   270  
   271  	-mutexprofile mutex.out
   272  	    Write a mutex contention profile to the specified file
   273  	    when all tests are complete.
   274  	    Writes test binary as -c would.
   275  
   276  	-mutexprofilefraction n
   277  	    Sample 1 in n stack traces of goroutines holding a
   278  	    contended mutex.
   279  
   280  	-outputdir directory
   281  	    Place output files from profiling in the specified directory,
   282  	    by default the directory in which "go test" is running.
   283  
   284  	-trace trace.out
   285  	    Write an execution trace to the specified file before exiting.
   286  
   287  Each of these flags is also recognized with an optional 'test.' prefix,
   288  as in -test.v. When invoking the generated test binary (the result of
   289  'go test -c') directly, however, the prefix is mandatory.
   290  
   291  The 'go test' command rewrites or removes recognized flags,
   292  as appropriate, both before and after the optional package list,
   293  before invoking the test binary.
   294  
   295  For instance, the command
   296  
   297  	go test -v -myflag testdata -cpuprofile=prof.out -x
   298  
   299  will compile the test binary and then run it as
   300  
   301  	pkg.test -test.v -myflag testdata -test.cpuprofile=prof.out
   302  
   303  (The -x flag is removed because it applies only to the go command's
   304  execution, not to the test itself.)
   305  
   306  The test flags that generate profiles (other than for coverage) also
   307  leave the test binary in pkg.test for use when analyzing the profiles.
   308  
   309  When 'go test' runs a test binary, it does so from within the
   310  corresponding package's source code directory. Depending on the test,
   311  it may be necessary to do the same when invoking a generated test
   312  binary directly.
   313  
   314  The command-line package list, if present, must appear before any
   315  flag not known to the go test command. Continuing the example above,
   316  the package list would have to appear before -myflag, but could appear
   317  on either side of -v.
   318  
   319  To keep an argument for a test binary from being interpreted as a
   320  known flag or a package name, use -args (see 'go help test') which
   321  passes the remainder of the command line through to the test binary
   322  uninterpreted and unaltered.
   323  
   324  For instance, the command
   325  
   326  	go test -v -args -x -v
   327  
   328  will compile the test binary and then run it as
   329  
   330  	pkg.test -test.v -x -v
   331  
   332  Similarly,
   333  
   334  	go test -args math
   335  
   336  will compile the test binary and then run it as
   337  
   338  	pkg.test math
   339  
   340  In the first example, the -x and the second -v are passed through to the
   341  test binary unchanged and with no effect on the go command itself.
   342  In the second example, the argument math is passed through to the test
   343  binary, instead of being interpreted as the package list.
   344  `
   345  
   346  var HelpTestfunc = &base.Command{
   347  	UsageLine: "testfunc",
   348  	Short:     "description of testing functions",
   349  	Long: `
   350  The 'go test' command expects to find test, benchmark, and example functions
   351  in the "*_test.go" files corresponding to the package under test.
   352  
   353  A test function is one named TestXXX (where XXX is any alphanumeric string
   354  not starting with a lower case letter) and should have the signature,
   355  
   356  	func TestXXX(t *testing.T) { ... }
   357  
   358  A benchmark function is one named BenchmarkXXX and should have the signature,
   359  
   360  	func BenchmarkXXX(b *testing.B) { ... }
   361  
   362  An example function is similar to a test function but, instead of using
   363  *testing.T to report success or failure, prints output to os.Stdout.
   364  If the last comment in the function starts with "Output:" then the output
   365  is compared exactly against the comment (see examples below). If the last
   366  comment begins with "Unordered output:" then the output is compared to the
   367  comment, however the order of the lines is ignored. An example with no such
   368  comment is compiled but not executed. An example with no text after
   369  "Output:" is compiled, executed, and expected to produce no output.
   370  
   371  Godoc displays the body of ExampleXXX to demonstrate the use
   372  of the function, constant, or variable XXX. An example of a method M with
   373  receiver type T or *T is named ExampleT_M. There may be multiple examples
   374  for a given function, constant, or variable, distinguished by a trailing _xxx,
   375  where xxx is a suffix not beginning with an upper case letter.
   376  
   377  Here is an example of an example:
   378  
   379  	func ExamplePrintln() {
   380  		Println("The output of\nthis example.")
   381  		// Output: The output of
   382  		// this example.
   383  	}
   384  
   385  Here is another example where the ordering of the output is ignored:
   386  
   387  	func ExamplePerm() {
   388  		for _, value := range Perm(4) {
   389  			fmt.Println(value)
   390  		}
   391  
   392  		// Unordered output: 4
   393  		// 2
   394  		// 1
   395  		// 3
   396  		// 0
   397  	}
   398  
   399  The entire test file is presented as the example when it contains a single
   400  example function, at least one other function, type, variable, or constant
   401  declaration, and no test or benchmark functions.
   402  
   403  See the documentation of the testing package for more information.
   404  `,
   405  }
   406  
   407  var (
   408  	testC            bool            // -c flag
   409  	testCover        bool            // -cover flag
   410  	testCoverMode    string          // -covermode flag
   411  	testCoverPaths   []string        // -coverpkg flag
   412  	testCoverPkgs    []*load.Package // -coverpkg flag
   413  	testO            string          // -o flag
   414  	testProfile      bool            // some profiling flag
   415  	testNeedBinary   bool            // profile needs to keep binary around
   416  	testV            bool            // -v flag
   417  	testTimeout      string          // -timeout flag
   418  	testArgs         []string
   419  	testBench        bool
   420  	testList         bool
   421  	testStreamOutput bool // show output as it is generated
   422  	testShowPass     bool // show passing output
   423  
   424  	testKillTimeout = 10 * time.Minute
   425  )
   426  
   427  var testMainDeps = []string{
   428  	// Dependencies for testmain.
   429  	"os",
   430  	"testing",
   431  	"testing/internal/testdeps",
   432  }
   433  
   434  func runTest(cmd *base.Command, args []string) {
   435  	var pkgArgs []string
   436  	pkgArgs, testArgs = testFlags(args)
   437  
   438  	work.FindExecCmd() // initialize cached result
   439  
   440  	work.InstrumentInit()
   441  	work.BuildModeInit()
   442  	pkgs := load.PackagesForBuild(pkgArgs)
   443  	if len(pkgs) == 0 {
   444  		base.Fatalf("no packages to test")
   445  	}
   446  
   447  	if testC && len(pkgs) != 1 {
   448  		base.Fatalf("cannot use -c flag with multiple packages")
   449  	}
   450  	if testO != "" && len(pkgs) != 1 {
   451  		base.Fatalf("cannot use -o flag with multiple packages")
   452  	}
   453  	if testProfile && len(pkgs) != 1 {
   454  		base.Fatalf("cannot use test profile flag with multiple packages")
   455  	}
   456  
   457  	// If a test timeout was given and is parseable, set our kill timeout
   458  	// to that timeout plus one minute. This is a backup alarm in case
   459  	// the test wedges with a goroutine spinning and its background
   460  	// timer does not get a chance to fire.
   461  	if dt, err := time.ParseDuration(testTimeout); err == nil && dt > 0 {
   462  		testKillTimeout = dt + 1*time.Minute
   463  	}
   464  
   465  	// show passing test output (after buffering) with -v flag.
   466  	// must buffer because tests are running in parallel, and
   467  	// otherwise the output will get mixed.
   468  	testShowPass = testV || testList
   469  
   470  	// stream test output (no buffering) when no package has
   471  	// been given on the command line (implicit current directory)
   472  	// or when benchmarking.
   473  	// Also stream if we're showing output anyway with a
   474  	// single package under test or if parallelism is set to 1.
   475  	// In these cases, streaming the output produces the same result
   476  	// as not streaming, just more immediately.
   477  	testStreamOutput = len(pkgArgs) == 0 || testBench ||
   478  		(testShowPass && (len(pkgs) == 1 || cfg.BuildP == 1))
   479  
   480  	// For 'go test -i -o x.test', we want to build x.test. Imply -c to make the logic easier.
   481  	if cfg.BuildI && testO != "" {
   482  		testC = true
   483  	}
   484  
   485  	var b work.Builder
   486  	b.Init()
   487  
   488  	if cfg.BuildI {
   489  		cfg.BuildV = testV
   490  
   491  		deps := make(map[string]bool)
   492  		for _, dep := range testMainDeps {
   493  			deps[dep] = true
   494  		}
   495  
   496  		for _, p := range pkgs {
   497  			// Dependencies for each test.
   498  			for _, path := range p.Imports {
   499  				deps[path] = true
   500  			}
   501  			for _, path := range p.Vendored(p.TestImports) {
   502  				deps[path] = true
   503  			}
   504  			for _, path := range p.Vendored(p.XTestImports) {
   505  				deps[path] = true
   506  			}
   507  		}
   508  
   509  		// translate C to runtime/cgo
   510  		if deps["C"] {
   511  			delete(deps, "C")
   512  			deps["runtime/cgo"] = true
   513  		}
   514  		// Ignore pseudo-packages.
   515  		delete(deps, "unsafe")
   516  
   517  		all := []string{}
   518  		for path := range deps {
   519  			if !build.IsLocalImport(path) {
   520  				all = append(all, path)
   521  			}
   522  		}
   523  		sort.Strings(all)
   524  
   525  		a := &work.Action{Mode: "go test -i"}
   526  		for _, p := range load.PackagesForBuild(all) {
   527  			a.Deps = append(a.Deps, b.Action(work.ModeInstall, work.ModeInstall, p))
   528  		}
   529  		b.Do(a)
   530  		if !testC || a.Failed {
   531  			return
   532  		}
   533  		b.Init()
   534  	}
   535  
   536  	var builds, runs, prints []*work.Action
   537  
   538  	if testCoverPaths != nil {
   539  		// Load packages that were asked about for coverage.
   540  		// packagesForBuild exits if the packages cannot be loaded.
   541  		testCoverPkgs = load.PackagesForBuild(testCoverPaths)
   542  
   543  		// Warn about -coverpkg arguments that are not actually used.
   544  		used := make(map[string]bool)
   545  		for _, p := range pkgs {
   546  			used[p.ImportPath] = true
   547  			for _, dep := range p.Deps {
   548  				used[dep] = true
   549  			}
   550  		}
   551  		for _, p := range testCoverPkgs {
   552  			if !used[p.ImportPath] {
   553  				fmt.Fprintf(os.Stderr, "warning: no packages being tested depend on %s\n", p.ImportPath)
   554  			}
   555  		}
   556  
   557  		// Mark all the coverage packages for rebuilding with coverage.
   558  		for _, p := range testCoverPkgs {
   559  			// There is nothing to cover in package unsafe; it comes from the compiler.
   560  			if p.ImportPath == "unsafe" {
   561  				continue
   562  			}
   563  			p.Stale = true // rebuild
   564  			p.StaleReason = "rebuild for coverage"
   565  			p.Internal.CoverMode = testCoverMode
   566  			var coverFiles []string
   567  			coverFiles = append(coverFiles, p.GoFiles...)
   568  			coverFiles = append(coverFiles, p.CgoFiles...)
   569  			coverFiles = append(coverFiles, p.TestGoFiles...)
   570  			p.Internal.CoverVars = declareCoverVars(p.ImportPath, coverFiles...)
   571  		}
   572  	}
   573  
   574  	// Prepare build + run + print actions for all packages being tested.
   575  	for _, p := range pkgs {
   576  		// sync/atomic import is inserted by the cover tool. See #18486
   577  		if testCover && testCoverMode == "atomic" {
   578  			ensureImport(p, "sync/atomic")
   579  		}
   580  
   581  		buildTest, runTest, printTest, err := builderTest(&b, p)
   582  		if err != nil {
   583  			str := err.Error()
   584  			if strings.HasPrefix(str, "\n") {
   585  				str = str[1:]
   586  			}
   587  			failed := fmt.Sprintf("FAIL\t%s [setup failed]\n", p.ImportPath)
   588  
   589  			if p.ImportPath != "" {
   590  				base.Errorf("# %s\n%s\n%s", p.ImportPath, str, failed)
   591  			} else {
   592  				base.Errorf("%s\n%s", str, failed)
   593  			}
   594  			continue
   595  		}
   596  		builds = append(builds, buildTest)
   597  		runs = append(runs, runTest)
   598  		prints = append(prints, printTest)
   599  	}
   600  
   601  	// Ultimately the goal is to print the output.
   602  	root := &work.Action{Mode: "go test", Deps: prints}
   603  
   604  	// Force the printing of results to happen in order,
   605  	// one at a time.
   606  	for i, a := range prints {
   607  		if i > 0 {
   608  			a.Deps = append(a.Deps, prints[i-1])
   609  		}
   610  	}
   611  
   612  	// Force benchmarks to run in serial.
   613  	if !testC && testBench {
   614  		// The first run must wait for all builds.
   615  		// Later runs must wait for the previous run's print.
   616  		for i, run := range runs {
   617  			if i == 0 {
   618  				run.Deps = append(run.Deps, builds...)
   619  			} else {
   620  				run.Deps = append(run.Deps, prints[i-1])
   621  			}
   622  		}
   623  	}
   624  
   625  	b.Do(root)
   626  }
   627  
   628  // ensures that package p imports the named package
   629  func ensureImport(p *load.Package, pkg string) {
   630  	for _, d := range p.Internal.Imports {
   631  		if d.Name == pkg {
   632  			return
   633  		}
   634  	}
   635  
   636  	a := load.LoadPackage(pkg, &load.ImportStack{})
   637  	if a.Error != nil {
   638  		base.Fatalf("load %s: %v", pkg, a.Error)
   639  	}
   640  	load.ComputeStale(a)
   641  
   642  	p.Internal.Imports = append(p.Internal.Imports, a)
   643  }
   644  
   645  var windowsBadWords = []string{
   646  	"install",
   647  	"patch",
   648  	"setup",
   649  	"update",
   650  }
   651  
   652  func builderTest(b *work.Builder, p *load.Package) (buildAction, runAction, printAction *work.Action, err error) {
   653  	if len(p.TestGoFiles)+len(p.XTestGoFiles) == 0 {
   654  		build := b.Action(work.ModeBuild, work.ModeBuild, p)
   655  		run := &work.Action{Mode: "test run", Package: p, Deps: []*work.Action{build}}
   656  		print := &work.Action{Mode: "test print", Func: builderNoTest, Package: p, Deps: []*work.Action{run}}
   657  		return build, run, print, nil
   658  	}
   659  
   660  	// Build Package structs describing:
   661  	//	ptest - package + test files
   662  	//	pxtest - package of external test files
   663  	//	pmain - pkg.test binary
   664  	var ptest, pxtest, pmain *load.Package
   665  
   666  	var imports, ximports []*load.Package
   667  	var stk load.ImportStack
   668  	stk.Push(p.ImportPath + " (test)")
   669  	for i, path := range p.TestImports {
   670  		p1 := load.LoadImport(path, p.Dir, p, &stk, p.Internal.Build.TestImportPos[path], load.UseVendor)
   671  		if p1.Error != nil {
   672  			return nil, nil, nil, p1.Error
   673  		}
   674  		if len(p1.DepsErrors) > 0 {
   675  			err := p1.DepsErrors[0]
   676  			err.Pos = "" // show full import stack
   677  			return nil, nil, nil, err
   678  		}
   679  		if str.Contains(p1.Deps, p.ImportPath) || p1.ImportPath == p.ImportPath {
   680  			// Same error that loadPackage returns (via reusePackage) in pkg.go.
   681  			// Can't change that code, because that code is only for loading the
   682  			// non-test copy of a package.
   683  			err := &load.PackageError{
   684  				ImportStack:   testImportStack(stk[0], p1, p.ImportPath),
   685  				Err:           "import cycle not allowed in test",
   686  				IsImportCycle: true,
   687  			}
   688  			return nil, nil, nil, err
   689  		}
   690  		p.TestImports[i] = p1.ImportPath
   691  		imports = append(imports, p1)
   692  	}
   693  	stk.Pop()
   694  	stk.Push(p.ImportPath + "_test")
   695  	pxtestNeedsPtest := false
   696  	for i, path := range p.XTestImports {
   697  		p1 := load.LoadImport(path, p.Dir, p, &stk, p.Internal.Build.XTestImportPos[path], load.UseVendor)
   698  		if p1.Error != nil {
   699  			return nil, nil, nil, p1.Error
   700  		}
   701  		if len(p1.DepsErrors) > 0 {
   702  			err := p1.DepsErrors[0]
   703  			err.Pos = "" // show full import stack
   704  			return nil, nil, nil, err
   705  		}
   706  		if p1.ImportPath == p.ImportPath {
   707  			pxtestNeedsPtest = true
   708  		} else {
   709  			ximports = append(ximports, p1)
   710  		}
   711  		p.XTestImports[i] = p1.ImportPath
   712  	}
   713  	stk.Pop()
   714  
   715  	// Use last element of import path, not package name.
   716  	// They differ when package name is "main".
   717  	// But if the import path is "command-line-arguments",
   718  	// like it is during 'go run', use the package name.
   719  	var elem string
   720  	if p.ImportPath == "command-line-arguments" {
   721  		elem = p.Name
   722  	} else {
   723  		_, elem = path.Split(p.ImportPath)
   724  	}
   725  	testBinary := elem + ".test"
   726  
   727  	// Should we apply coverage analysis locally,
   728  	// only for this package and only for this test?
   729  	// Yes, if -cover is on but -coverpkg has not specified
   730  	// a list of packages for global coverage.
   731  	localCover := testCover && testCoverPaths == nil
   732  
   733  	// Test package.
   734  	if len(p.TestGoFiles) > 0 || localCover || p.Name == "main" {
   735  		ptest = new(load.Package)
   736  		*ptest = *p
   737  		ptest.GoFiles = nil
   738  		ptest.GoFiles = append(ptest.GoFiles, p.GoFiles...)
   739  		ptest.GoFiles = append(ptest.GoFiles, p.TestGoFiles...)
   740  		ptest.Internal.Target = ""
   741  		ptest.Imports = str.StringList(p.Imports, p.TestImports)
   742  		ptest.Internal.Imports = append(append([]*load.Package{}, p.Internal.Imports...), imports...)
   743  		ptest.Internal.ForceLibrary = true
   744  		ptest.Stale = true
   745  		ptest.StaleReason = "rebuild for test"
   746  		ptest.Internal.Build = new(build.Package)
   747  		*ptest.Internal.Build = *p.Internal.Build
   748  		m := map[string][]token.Position{}
   749  		for k, v := range p.Internal.Build.ImportPos {
   750  			m[k] = append(m[k], v...)
   751  		}
   752  		for k, v := range p.Internal.Build.TestImportPos {
   753  			m[k] = append(m[k], v...)
   754  		}
   755  		ptest.Internal.Build.ImportPos = m
   756  
   757  		if localCover {
   758  			ptest.Internal.CoverMode = testCoverMode
   759  			var coverFiles []string
   760  			coverFiles = append(coverFiles, ptest.GoFiles...)
   761  			coverFiles = append(coverFiles, ptest.CgoFiles...)
   762  			ptest.Internal.CoverVars = declareCoverVars(ptest.ImportPath, coverFiles...)
   763  		}
   764  	} else {
   765  		ptest = p
   766  	}
   767  
   768  	// External test package.
   769  	if len(p.XTestGoFiles) > 0 {
   770  		pxtest = &load.Package{
   771  			PackagePublic: load.PackagePublic{
   772  				Name:       p.Name + "_test",
   773  				ImportPath: p.ImportPath + "_test",
   774  				Root:       p.Root,
   775  				Dir:        p.Dir,
   776  				GoFiles:    p.XTestGoFiles,
   777  				Imports:    p.XTestImports,
   778  				Stale:      true,
   779  			},
   780  			Internal: load.PackageInternal{
   781  				LocalPrefix: p.Internal.LocalPrefix,
   782  				Build: &build.Package{
   783  					ImportPos: p.Internal.Build.XTestImportPos,
   784  				},
   785  				Imports: ximports,
   786  			},
   787  		}
   788  		if pxtestNeedsPtest {
   789  			pxtest.Internal.Imports = append(pxtest.Internal.Imports, ptest)
   790  		}
   791  	}
   792  
   793  	testDir := b.NewObjdir()
   794  	if err := b.Mkdir(testDir); err != nil {
   795  		return nil, nil, nil, err
   796  	}
   797  
   798  	// Action for building pkg.test.
   799  	pmain = &load.Package{
   800  		PackagePublic: load.PackagePublic{
   801  			Name:       "main",
   802  			Dir:        testDir,
   803  			GoFiles:    []string{"_testmain.go"},
   804  			ImportPath: p.ImportPath + " (testmain)",
   805  			Root:       p.Root,
   806  			Stale:      true,
   807  		},
   808  		Internal: load.PackageInternal{
   809  			Build:     &build.Package{Name: "main"},
   810  			OmitDebug: !testC && !testNeedBinary,
   811  		},
   812  	}
   813  
   814  	// The generated main also imports testing, regexp, and os.
   815  	// Also the linker introduces implicit dependencies reported by LinkerDeps.
   816  	stk.Push("testmain")
   817  	deps := testMainDeps // cap==len, so safe for append
   818  	for _, d := range load.LinkerDeps(p) {
   819  		deps = append(deps, d)
   820  	}
   821  	for _, dep := range deps {
   822  		if dep == ptest.ImportPath {
   823  			pmain.Internal.Imports = append(pmain.Internal.Imports, ptest)
   824  		} else {
   825  			p1 := load.LoadImport(dep, "", nil, &stk, nil, 0)
   826  			if p1.Error != nil {
   827  				return nil, nil, nil, p1.Error
   828  			}
   829  			pmain.Internal.Imports = append(pmain.Internal.Imports, p1)
   830  		}
   831  	}
   832  
   833  	if testCoverPkgs != nil {
   834  		// Add imports, but avoid duplicates.
   835  		seen := map[*load.Package]bool{p: true, ptest: true}
   836  		for _, p1 := range pmain.Internal.Imports {
   837  			seen[p1] = true
   838  		}
   839  		for _, p1 := range testCoverPkgs {
   840  			if !seen[p1] {
   841  				seen[p1] = true
   842  				pmain.Internal.Imports = append(pmain.Internal.Imports, p1)
   843  			}
   844  		}
   845  	}
   846  
   847  	// Do initial scan for metadata needed for writing _testmain.go
   848  	// Use that metadata to update the list of imports for package main.
   849  	// The list of imports is used by recompileForTest and by the loop
   850  	// afterward that gathers t.Cover information.
   851  	t, err := loadTestFuncs(ptest)
   852  	if err != nil {
   853  		return nil, nil, nil, err
   854  	}
   855  	if len(ptest.GoFiles)+len(ptest.CgoFiles) > 0 {
   856  		pmain.Internal.Imports = append(pmain.Internal.Imports, ptest)
   857  		t.ImportTest = true
   858  	}
   859  	if pxtest != nil {
   860  		pmain.Internal.Imports = append(pmain.Internal.Imports, pxtest)
   861  		t.ImportXtest = true
   862  	}
   863  
   864  	if ptest != p && localCover {
   865  		// We have made modifications to the package p being tested
   866  		// and are rebuilding p (as ptest).
   867  		// Arrange to rebuild all packages q such that
   868  		// the test depends on q and q depends on p.
   869  		// This makes sure that q sees the modifications to p.
   870  		// Strictly speaking, the rebuild is only necessary if the
   871  		// modifications to p change its export metadata, but
   872  		// determining that is a bit tricky, so we rebuild always.
   873  		// TODO(rsc): Once we get export metadata changes
   874  		// handled properly, look into the expense of dropping
   875  		// "&& localCover" above.
   876  		//
   877  		// This will cause extra compilation, so for now we only do it
   878  		// when testCover is set. The conditions are more general, though,
   879  		// and we may find that we need to do it always in the future.
   880  		recompileForTest(pmain, p, ptest)
   881  	}
   882  
   883  	for _, cp := range pmain.Internal.Imports {
   884  		if len(cp.Internal.CoverVars) > 0 {
   885  			t.Cover = append(t.Cover, coverInfo{cp, cp.Internal.CoverVars})
   886  		}
   887  	}
   888  
   889  	if !cfg.BuildN {
   890  		// writeTestmain writes _testmain.go,
   891  		// using the test description gathered in t.
   892  		if err := writeTestmain(testDir+"_testmain.go", t); err != nil {
   893  			return nil, nil, nil, err
   894  		}
   895  	}
   896  
   897  	load.ComputeStale(pmain)
   898  
   899  	if ptest != p {
   900  		a := b.Action(work.ModeBuild, work.ModeBuild, ptest)
   901  		a.Link = false
   902  	}
   903  
   904  	a := b.Action(work.ModeBuild, work.ModeBuild, pmain)
   905  	a.Target = testDir + testBinary + cfg.ExeSuffix
   906  	if cfg.Goos == "windows" {
   907  		// There are many reserved words on Windows that,
   908  		// if used in the name of an executable, cause Windows
   909  		// to try to ask for extra permissions.
   910  		// The word list includes setup, install, update, and patch,
   911  		// but it does not appear to be defined anywhere.
   912  		// We have run into this trying to run the
   913  		// go.codereview/patch tests.
   914  		// For package names containing those words, use test.test.exe
   915  		// instead of pkgname.test.exe.
   916  		// Note that this file name is only used in the Go command's
   917  		// temporary directory. If the -c or other flags are
   918  		// given, the code below will still use pkgname.test.exe.
   919  		// There are two user-visible effects of this change.
   920  		// First, you can actually run 'go test' in directories that
   921  		// have names that Windows thinks are installer-like,
   922  		// without getting a dialog box asking for more permissions.
   923  		// Second, in the Windows process listing during go test,
   924  		// the test shows up as test.test.exe, not pkgname.test.exe.
   925  		// That second one is a drawback, but it seems a small
   926  		// price to pay for the test running at all.
   927  		// If maintaining the list of bad words is too onerous,
   928  		// we could just do this always on Windows.
   929  		for _, bad := range windowsBadWords {
   930  			if strings.Contains(testBinary, bad) {
   931  				a.Target = testDir + "test.test" + cfg.ExeSuffix
   932  				break
   933  			}
   934  		}
   935  	}
   936  	buildAction = a
   937  
   938  	if testC || testNeedBinary {
   939  		// -c or profiling flag: create action to copy binary to ./test.out.
   940  		target := filepath.Join(base.Cwd, testBinary+cfg.ExeSuffix)
   941  		if testO != "" {
   942  			target = testO
   943  			if !filepath.IsAbs(target) {
   944  				target = filepath.Join(base.Cwd, target)
   945  			}
   946  		}
   947  		buildAction = &work.Action{
   948  			Mode:    "test build",
   949  			Func:    work.BuildInstallFunc,
   950  			Deps:    []*work.Action{buildAction},
   951  			Package: pmain,
   952  			Target:  target,
   953  		}
   954  		runAction = buildAction // make sure runAction != nil even if not running test
   955  	}
   956  	if testC {
   957  		printAction = &work.Action{Mode: "test print (nop)", Package: p, Deps: []*work.Action{runAction}} // nop
   958  	} else {
   959  		// run test
   960  		runAction = &work.Action{
   961  			Mode:       "test run",
   962  			Func:       builderRunTest,
   963  			Deps:       []*work.Action{buildAction},
   964  			Package:    p,
   965  			IgnoreFail: true,
   966  		}
   967  		cleanAction := &work.Action{
   968  			Mode:    "test clean",
   969  			Func:    builderCleanTest,
   970  			Deps:    []*work.Action{runAction},
   971  			Package: p,
   972  			Objdir:  testDir,
   973  		}
   974  		printAction = &work.Action{
   975  			Mode:    "test print",
   976  			Func:    builderPrintTest,
   977  			Deps:    []*work.Action{cleanAction},
   978  			Package: p,
   979  		}
   980  	}
   981  
   982  	return buildAction, runAction, printAction, nil
   983  }
   984  
   985  func testImportStack(top string, p *load.Package, target string) []string {
   986  	stk := []string{top, p.ImportPath}
   987  Search:
   988  	for p.ImportPath != target {
   989  		for _, p1 := range p.Internal.Imports {
   990  			if p1.ImportPath == target || str.Contains(p1.Deps, target) {
   991  				stk = append(stk, p1.ImportPath)
   992  				p = p1
   993  				continue Search
   994  			}
   995  		}
   996  		// Can't happen, but in case it does...
   997  		stk = append(stk, "<lost path to cycle>")
   998  		break
   999  	}
  1000  	return stk
  1001  }
  1002  
  1003  func recompileForTest(pmain, preal, ptest *load.Package) {
  1004  	// The "test copy" of preal is ptest.
  1005  	// For each package that depends on preal, make a "test copy"
  1006  	// that depends on ptest. And so on, up the dependency tree.
  1007  	testCopy := map[*load.Package]*load.Package{preal: ptest}
  1008  	for _, p := range load.PackageList([]*load.Package{pmain}) {
  1009  		// Copy on write.
  1010  		didSplit := false
  1011  		split := func() {
  1012  			if didSplit {
  1013  				return
  1014  			}
  1015  			didSplit = true
  1016  			if testCopy[p] != nil {
  1017  				panic("recompileForTest loop")
  1018  			}
  1019  			p1 := new(load.Package)
  1020  			testCopy[p] = p1
  1021  			*p1 = *p
  1022  			p1.Internal.Imports = make([]*load.Package, len(p.Internal.Imports))
  1023  			copy(p1.Internal.Imports, p.Internal.Imports)
  1024  			p = p1
  1025  			p.Internal.Target = ""
  1026  			p.Stale = true
  1027  			p.StaleReason = "depends on package being tested"
  1028  		}
  1029  
  1030  		// Update p.Internal.Imports to use test copies.
  1031  		for i, imp := range p.Internal.Imports {
  1032  			if p1 := testCopy[imp]; p1 != nil && p1 != imp {
  1033  				split()
  1034  				p.Internal.Imports[i] = p1
  1035  			}
  1036  		}
  1037  	}
  1038  }
  1039  
  1040  var coverIndex = 0
  1041  
  1042  // isTestFile reports whether the source file is a set of tests and should therefore
  1043  // be excluded from coverage analysis.
  1044  func isTestFile(file string) bool {
  1045  	// We don't cover tests, only the code they test.
  1046  	return strings.HasSuffix(file, "_test.go")
  1047  }
  1048  
  1049  // declareCoverVars attaches the required cover variables names
  1050  // to the files, to be used when annotating the files.
  1051  func declareCoverVars(importPath string, files ...string) map[string]*load.CoverVar {
  1052  	coverVars := make(map[string]*load.CoverVar)
  1053  	for _, file := range files {
  1054  		if isTestFile(file) {
  1055  			continue
  1056  		}
  1057  		coverVars[file] = &load.CoverVar{
  1058  			File: filepath.Join(importPath, file),
  1059  			Var:  fmt.Sprintf("GoCover_%d", coverIndex),
  1060  		}
  1061  		coverIndex++
  1062  	}
  1063  	return coverVars
  1064  }
  1065  
  1066  var noTestsToRun = []byte("\ntesting: warning: no tests to run\n")
  1067  
  1068  // builderRunTest is the action for running a test binary.
  1069  func builderRunTest(b *work.Builder, a *work.Action) error {
  1070  	args := str.StringList(work.FindExecCmd(), a.Deps[0].Target, testArgs)
  1071  	a.TestOutput = new(bytes.Buffer)
  1072  
  1073  	if cfg.BuildN || cfg.BuildX {
  1074  		b.Showcmd("", "%s", strings.Join(args, " "))
  1075  		if cfg.BuildN {
  1076  			return nil
  1077  		}
  1078  	}
  1079  
  1080  	if a.Failed {
  1081  		// We were unable to build the binary.
  1082  		a.Failed = false
  1083  		fmt.Fprintf(a.TestOutput, "FAIL\t%s [build failed]\n", a.Package.ImportPath)
  1084  		base.SetExitStatus(1)
  1085  		return nil
  1086  	}
  1087  
  1088  	cmd := exec.Command(args[0], args[1:]...)
  1089  	cmd.Dir = a.Package.Dir
  1090  	cmd.Env = base.EnvForDir(cmd.Dir, cfg.OrigEnv)
  1091  	var buf bytes.Buffer
  1092  	if testStreamOutput {
  1093  		cmd.Stdout = os.Stdout
  1094  		cmd.Stderr = os.Stderr
  1095  	} else {
  1096  		cmd.Stdout = &buf
  1097  		cmd.Stderr = &buf
  1098  	}
  1099  
  1100  	// If there are any local SWIG dependencies, we want to load
  1101  	// the shared library from the build directory.
  1102  	if a.Package.UsesSwig() {
  1103  		env := cmd.Env
  1104  		found := false
  1105  		prefix := "LD_LIBRARY_PATH="
  1106  		for i, v := range env {
  1107  			if strings.HasPrefix(v, prefix) {
  1108  				env[i] = v + ":."
  1109  				found = true
  1110  				break
  1111  			}
  1112  		}
  1113  		if !found {
  1114  			env = append(env, "LD_LIBRARY_PATH=.")
  1115  		}
  1116  		cmd.Env = env
  1117  	}
  1118  
  1119  	t0 := time.Now()
  1120  	err := cmd.Start()
  1121  
  1122  	// This is a last-ditch deadline to detect and
  1123  	// stop wedged test binaries, to keep the builders
  1124  	// running.
  1125  	if err == nil {
  1126  		tick := time.NewTimer(testKillTimeout)
  1127  		base.StartSigHandlers()
  1128  		done := make(chan error)
  1129  		go func() {
  1130  			done <- cmd.Wait()
  1131  		}()
  1132  	Outer:
  1133  		select {
  1134  		case err = <-done:
  1135  			// ok
  1136  		case <-tick.C:
  1137  			if base.SignalTrace != nil {
  1138  				// Send a quit signal in the hope that the program will print
  1139  				// a stack trace and exit. Give it five seconds before resorting
  1140  				// to Kill.
  1141  				cmd.Process.Signal(base.SignalTrace)
  1142  				select {
  1143  				case err = <-done:
  1144  					fmt.Fprintf(&buf, "*** Test killed with %v: ran too long (%v).\n", base.SignalTrace, testKillTimeout)
  1145  					break Outer
  1146  				case <-time.After(5 * time.Second):
  1147  				}
  1148  			}
  1149  			cmd.Process.Kill()
  1150  			err = <-done
  1151  			fmt.Fprintf(&buf, "*** Test killed: ran too long (%v).\n", testKillTimeout)
  1152  		}
  1153  		tick.Stop()
  1154  	}
  1155  	out := buf.Bytes()
  1156  	t := fmt.Sprintf("%.3fs", time.Since(t0).Seconds())
  1157  	if err == nil {
  1158  		norun := ""
  1159  		if testShowPass {
  1160  			a.TestOutput.Write(out)
  1161  		}
  1162  		if bytes.HasPrefix(out, noTestsToRun[1:]) || bytes.Contains(out, noTestsToRun) {
  1163  			norun = " [no tests to run]"
  1164  		}
  1165  		fmt.Fprintf(a.TestOutput, "ok  \t%s\t%s%s%s\n", a.Package.ImportPath, t, coveragePercentage(out), norun)
  1166  		return nil
  1167  	}
  1168  
  1169  	base.SetExitStatus(1)
  1170  	if len(out) > 0 {
  1171  		a.TestOutput.Write(out)
  1172  		// assume printing the test binary's exit status is superfluous
  1173  	} else {
  1174  		fmt.Fprintf(a.TestOutput, "%s\n", err)
  1175  	}
  1176  	fmt.Fprintf(a.TestOutput, "FAIL\t%s\t%s\n", a.Package.ImportPath, t)
  1177  
  1178  	return nil
  1179  }
  1180  
  1181  // coveragePercentage returns the coverage results (if enabled) for the
  1182  // test. It uncovers the data by scanning the output from the test run.
  1183  func coveragePercentage(out []byte) string {
  1184  	if !testCover {
  1185  		return ""
  1186  	}
  1187  	// The string looks like
  1188  	//	test coverage for encoding/binary: 79.9% of statements
  1189  	// Extract the piece from the percentage to the end of the line.
  1190  	re := regexp.MustCompile(`coverage: (.*)\n`)
  1191  	matches := re.FindSubmatch(out)
  1192  	if matches == nil {
  1193  		// Probably running "go test -cover" not "go test -cover fmt".
  1194  		// The coverage output will appear in the output directly.
  1195  		return ""
  1196  	}
  1197  	return fmt.Sprintf("\tcoverage: %s", matches[1])
  1198  }
  1199  
  1200  // builderCleanTest is the action for cleaning up after a test.
  1201  func builderCleanTest(b *work.Builder, a *work.Action) error {
  1202  	if cfg.BuildWork {
  1203  		return nil
  1204  	}
  1205  	if cfg.BuildX {
  1206  		b.Showcmd("", "rm -r %s", a.Objdir)
  1207  	}
  1208  	os.RemoveAll(a.Objdir)
  1209  	return nil
  1210  }
  1211  
  1212  // builderPrintTest is the action for printing a test result.
  1213  func builderPrintTest(b *work.Builder, a *work.Action) error {
  1214  	clean := a.Deps[0]
  1215  	run := clean.Deps[0]
  1216  	os.Stdout.Write(run.TestOutput.Bytes())
  1217  	run.TestOutput = nil
  1218  	return nil
  1219  }
  1220  
  1221  // builderNoTest is the action for testing a package with no test files.
  1222  func builderNoTest(b *work.Builder, a *work.Action) error {
  1223  	fmt.Printf("?   \t%s\t[no test files]\n", a.Package.ImportPath)
  1224  	return nil
  1225  }
  1226  
  1227  // isTestFunc tells whether fn has the type of a testing function. arg
  1228  // specifies the parameter type we look for: B, M or T.
  1229  func isTestFunc(fn *ast.FuncDecl, arg string) bool {
  1230  	if fn.Type.Results != nil && len(fn.Type.Results.List) > 0 ||
  1231  		fn.Type.Params.List == nil ||
  1232  		len(fn.Type.Params.List) != 1 ||
  1233  		len(fn.Type.Params.List[0].Names) > 1 {
  1234  		return false
  1235  	}
  1236  	ptr, ok := fn.Type.Params.List[0].Type.(*ast.StarExpr)
  1237  	if !ok {
  1238  		return false
  1239  	}
  1240  	// We can't easily check that the type is *testing.M
  1241  	// because we don't know how testing has been imported,
  1242  	// but at least check that it's *M or *something.M.
  1243  	// Same applies for B and T.
  1244  	if name, ok := ptr.X.(*ast.Ident); ok && name.Name == arg {
  1245  		return true
  1246  	}
  1247  	if sel, ok := ptr.X.(*ast.SelectorExpr); ok && sel.Sel.Name == arg {
  1248  		return true
  1249  	}
  1250  	return false
  1251  }
  1252  
  1253  // isTest tells whether name looks like a test (or benchmark, according to prefix).
  1254  // It is a Test (say) if there is a character after Test that is not a lower-case letter.
  1255  // We don't want TesticularCancer.
  1256  func isTest(name, prefix string) bool {
  1257  	if !strings.HasPrefix(name, prefix) {
  1258  		return false
  1259  	}
  1260  	if len(name) == len(prefix) { // "Test" is ok
  1261  		return true
  1262  	}
  1263  	rune, _ := utf8.DecodeRuneInString(name[len(prefix):])
  1264  	return !unicode.IsLower(rune)
  1265  }
  1266  
  1267  type coverInfo struct {
  1268  	Package *load.Package
  1269  	Vars    map[string]*load.CoverVar
  1270  }
  1271  
  1272  // loadTestFuncs returns the testFuncs describing the tests that will be run.
  1273  func loadTestFuncs(ptest *load.Package) (*testFuncs, error) {
  1274  	t := &testFuncs{
  1275  		Package: ptest,
  1276  	}
  1277  	for _, file := range ptest.TestGoFiles {
  1278  		if err := t.load(filepath.Join(ptest.Dir, file), "_test", &t.ImportTest, &t.NeedTest); err != nil {
  1279  			return nil, err
  1280  		}
  1281  	}
  1282  	for _, file := range ptest.XTestGoFiles {
  1283  		if err := t.load(filepath.Join(ptest.Dir, file), "_xtest", &t.ImportXtest, &t.NeedXtest); err != nil {
  1284  			return nil, err
  1285  		}
  1286  	}
  1287  	return t, nil
  1288  }
  1289  
  1290  // writeTestmain writes the _testmain.go file for t to the file named out.
  1291  func writeTestmain(out string, t *testFuncs) error {
  1292  	f, err := os.Create(out)
  1293  	if err != nil {
  1294  		return err
  1295  	}
  1296  	defer f.Close()
  1297  
  1298  	if err := testmainTmpl.Execute(f, t); err != nil {
  1299  		return err
  1300  	}
  1301  
  1302  	return nil
  1303  }
  1304  
  1305  type testFuncs struct {
  1306  	Tests       []testFunc
  1307  	Benchmarks  []testFunc
  1308  	Examples    []testFunc
  1309  	TestMain    *testFunc
  1310  	Package     *load.Package
  1311  	ImportTest  bool
  1312  	NeedTest    bool
  1313  	ImportXtest bool
  1314  	NeedXtest   bool
  1315  	Cover       []coverInfo
  1316  }
  1317  
  1318  func (t *testFuncs) CoverMode() string {
  1319  	return testCoverMode
  1320  }
  1321  
  1322  func (t *testFuncs) CoverEnabled() bool {
  1323  	return testCover
  1324  }
  1325  
  1326  // ImportPath returns the import path of the package being tested, if it is within GOPATH.
  1327  // This is printed by the testing package when running benchmarks.
  1328  func (t *testFuncs) ImportPath() string {
  1329  	pkg := t.Package.ImportPath
  1330  	if strings.HasPrefix(pkg, "_/") {
  1331  		return ""
  1332  	}
  1333  	if pkg == "command-line-arguments" {
  1334  		return ""
  1335  	}
  1336  	return pkg
  1337  }
  1338  
  1339  // Covered returns a string describing which packages are being tested for coverage.
  1340  // If the covered package is the same as the tested package, it returns the empty string.
  1341  // Otherwise it is a comma-separated human-readable list of packages beginning with
  1342  // " in", ready for use in the coverage message.
  1343  func (t *testFuncs) Covered() string {
  1344  	if testCoverPaths == nil {
  1345  		return ""
  1346  	}
  1347  	return " in " + strings.Join(testCoverPaths, ", ")
  1348  }
  1349  
  1350  // Tested returns the name of the package being tested.
  1351  func (t *testFuncs) Tested() string {
  1352  	return t.Package.Name
  1353  }
  1354  
  1355  type testFunc struct {
  1356  	Package   string // imported package name (_test or _xtest)
  1357  	Name      string // function name
  1358  	Output    string // output, for examples
  1359  	Unordered bool   // output is allowed to be unordered.
  1360  }
  1361  
  1362  var testFileSet = token.NewFileSet()
  1363  
  1364  func (t *testFuncs) load(filename, pkg string, doImport, seen *bool) error {
  1365  	f, err := parser.ParseFile(testFileSet, filename, nil, parser.ParseComments)
  1366  	if err != nil {
  1367  		return base.ExpandScanner(err)
  1368  	}
  1369  	for _, d := range f.Decls {
  1370  		n, ok := d.(*ast.FuncDecl)
  1371  		if !ok {
  1372  			continue
  1373  		}
  1374  		if n.Recv != nil {
  1375  			continue
  1376  		}
  1377  		name := n.Name.String()
  1378  		switch {
  1379  		case name == "TestMain" && isTestFunc(n, "M"):
  1380  			if t.TestMain != nil {
  1381  				return errors.New("multiple definitions of TestMain")
  1382  			}
  1383  			t.TestMain = &testFunc{pkg, name, "", false}
  1384  			*doImport, *seen = true, true
  1385  		case isTest(name, "Test"):
  1386  			err := checkTestFunc(n, "T")
  1387  			if err != nil {
  1388  				return err
  1389  			}
  1390  			t.Tests = append(t.Tests, testFunc{pkg, name, "", false})
  1391  			*doImport, *seen = true, true
  1392  		case isTest(name, "Benchmark"):
  1393  			err := checkTestFunc(n, "B")
  1394  			if err != nil {
  1395  				return err
  1396  			}
  1397  			t.Benchmarks = append(t.Benchmarks, testFunc{pkg, name, "", false})
  1398  			*doImport, *seen = true, true
  1399  		}
  1400  	}
  1401  	ex := doc.Examples(f)
  1402  	sort.Slice(ex, func(i, j int) bool { return ex[i].Order < ex[j].Order })
  1403  	for _, e := range ex {
  1404  		*doImport = true // import test file whether executed or not
  1405  		if e.Output == "" && !e.EmptyOutput {
  1406  			// Don't run examples with no output.
  1407  			continue
  1408  		}
  1409  		t.Examples = append(t.Examples, testFunc{pkg, "Example" + e.Name, e.Output, e.Unordered})
  1410  		*seen = true
  1411  	}
  1412  	return nil
  1413  }
  1414  
  1415  func checkTestFunc(fn *ast.FuncDecl, arg string) error {
  1416  	if !isTestFunc(fn, arg) {
  1417  		name := fn.Name.String()
  1418  		pos := testFileSet.Position(fn.Pos())
  1419  		return fmt.Errorf("%s: wrong signature for %s, must be: func %s(%s *testing.%s)", pos, name, name, strings.ToLower(arg), arg)
  1420  	}
  1421  	return nil
  1422  }
  1423  
  1424  var testmainTmpl = template.Must(template.New("main").Parse(`
  1425  package main
  1426  
  1427  import (
  1428  {{if not .TestMain}}
  1429  	"os"
  1430  {{end}}
  1431  	"testing"
  1432  	"testing/internal/testdeps"
  1433  
  1434  {{if .ImportTest}}
  1435  	{{if .NeedTest}}_test{{else}}_{{end}} {{.Package.ImportPath | printf "%q"}}
  1436  {{end}}
  1437  {{if .ImportXtest}}
  1438  	{{if .NeedXtest}}_xtest{{else}}_{{end}} {{.Package.ImportPath | printf "%s_test" | printf "%q"}}
  1439  {{end}}
  1440  {{range $i, $p := .Cover}}
  1441  	_cover{{$i}} {{$p.Package.ImportPath | printf "%q"}}
  1442  {{end}}
  1443  )
  1444  
  1445  var tests = []testing.InternalTest{
  1446  {{range .Tests}}
  1447  	{"{{.Name}}", {{.Package}}.{{.Name}}},
  1448  {{end}}
  1449  }
  1450  
  1451  var benchmarks = []testing.InternalBenchmark{
  1452  {{range .Benchmarks}}
  1453  	{"{{.Name}}", {{.Package}}.{{.Name}}},
  1454  {{end}}
  1455  }
  1456  
  1457  var examples = []testing.InternalExample{
  1458  {{range .Examples}}
  1459  	{"{{.Name}}", {{.Package}}.{{.Name}}, {{.Output | printf "%q"}}, {{.Unordered}}},
  1460  {{end}}
  1461  }
  1462  
  1463  func init() {
  1464  	testdeps.ImportPath = {{.ImportPath | printf "%q"}}
  1465  }
  1466  
  1467  {{if .CoverEnabled}}
  1468  
  1469  // Only updated by init functions, so no need for atomicity.
  1470  var (
  1471  	coverCounters = make(map[string][]uint32)
  1472  	coverBlocks = make(map[string][]testing.CoverBlock)
  1473  )
  1474  
  1475  func init() {
  1476  	{{range $i, $p := .Cover}}
  1477  	{{range $file, $cover := $p.Vars}}
  1478  	coverRegisterFile({{printf "%q" $cover.File}}, _cover{{$i}}.{{$cover.Var}}.Count[:], _cover{{$i}}.{{$cover.Var}}.Pos[:], _cover{{$i}}.{{$cover.Var}}.NumStmt[:])
  1479  	{{end}}
  1480  	{{end}}
  1481  }
  1482  
  1483  func coverRegisterFile(fileName string, counter []uint32, pos []uint32, numStmts []uint16) {
  1484  	if 3*len(counter) != len(pos) || len(counter) != len(numStmts) {
  1485  		panic("coverage: mismatched sizes")
  1486  	}
  1487  	if coverCounters[fileName] != nil {
  1488  		// Already registered.
  1489  		return
  1490  	}
  1491  	coverCounters[fileName] = counter
  1492  	block := make([]testing.CoverBlock, len(counter))
  1493  	for i := range counter {
  1494  		block[i] = testing.CoverBlock{
  1495  			Line0: pos[3*i+0],
  1496  			Col0: uint16(pos[3*i+2]),
  1497  			Line1: pos[3*i+1],
  1498  			Col1: uint16(pos[3*i+2]>>16),
  1499  			Stmts: numStmts[i],
  1500  		}
  1501  	}
  1502  	coverBlocks[fileName] = block
  1503  }
  1504  {{end}}
  1505  
  1506  func main() {
  1507  {{if .CoverEnabled}}
  1508  	testing.RegisterCover(testing.Cover{
  1509  		Mode: {{printf "%q" .CoverMode}},
  1510  		Counters: coverCounters,
  1511  		Blocks: coverBlocks,
  1512  		CoveredPackages: {{printf "%q" .Covered}},
  1513  	})
  1514  {{end}}
  1515  	m := testing.MainStart(testdeps.TestDeps{}, tests, benchmarks, examples)
  1516  {{with .TestMain}}
  1517  	{{.Package}}.{{.Name}}(m)
  1518  {{else}}
  1519  	os.Exit(m.Run())
  1520  {{end}}
  1521  }
  1522  
  1523  `))