github.com/ader1990/go@v0.0.0-20140630135419-8c24447fa791/src/cmd/go/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 main
     6  
     7  import (
     8  	"bytes"
     9  	"fmt"
    10  	"go/ast"
    11  	"go/build"
    12  	"go/doc"
    13  	"go/parser"
    14  	"go/token"
    15  	"log"
    16  	"os"
    17  	"os/exec"
    18  	"path"
    19  	"path/filepath"
    20  	"regexp"
    21  	"runtime"
    22  	"sort"
    23  	"strings"
    24  	"text/template"
    25  	"time"
    26  	"unicode"
    27  	"unicode/utf8"
    28  )
    29  
    30  // Break init loop.
    31  func init() {
    32  	cmdTest.Run = runTest
    33  }
    34  
    35  var cmdTest = &Command{
    36  	CustomFlags: true,
    37  	UsageLine:   "test [-c] [-i] [build and test flags] [packages] [flags for test binary]",
    38  	Short:       "test packages",
    39  	Long: `
    40  'Go test' automates testing the packages named by the import paths.
    41  It prints a summary of the test results in the format:
    42  
    43  	ok   archive/tar   0.011s
    44  	FAIL archive/zip   0.022s
    45  	ok   compress/gzip 0.033s
    46  	...
    47  
    48  followed by detailed output for each failed package.
    49  
    50  'Go test' recompiles each package along with any files with names matching
    51  the file pattern "*_test.go". 
    52  Files whose names begin with "_" (including "_test.go") or "." are ignored.
    53  These additional files can contain test functions, benchmark functions, and
    54  example functions.  See 'go help testfunc' for more.
    55  Each listed package causes the execution of a separate test binary.
    56  
    57  Test files that declare a package with the suffix "_test" will be compiled as a
    58  separate package, and then linked and run with the main test binary.
    59  
    60  By default, go test needs no arguments.  It compiles and tests the package
    61  with source in the current directory, including tests, and runs the tests.
    62  
    63  The package is built in a temporary directory so it does not interfere with the
    64  non-test installation.
    65  
    66  In addition to the build flags, the flags handled by 'go test' itself are:
    67  
    68  	-c  Compile the test binary to pkg.test but do not run it.
    69  	    (Where pkg is the last element of the package's import path.)
    70  
    71  	-i
    72  	    Install packages that are dependencies of the test.
    73  	    Do not run the test.
    74  
    75  	-exec xprog
    76  	    Run the test binary using xprog. The behavior is the same as
    77  	    in 'go run'. See 'go help run' for details.
    78  
    79  The test binary also accepts flags that control execution of the test; these
    80  flags are also accessible by 'go test'.  See 'go help testflag' for details.
    81  
    82  If the test binary needs any other flags, they should be presented after the
    83  package names. The go tool treats as a flag the first argument that begins with
    84  a minus sign that it does not recognize itself; that argument and all subsequent
    85  arguments are passed as arguments to the test binary.
    86  
    87  For more about build flags, see 'go help build'.
    88  For more about specifying packages, see 'go help packages'.
    89  
    90  See also: go build, go vet.
    91  `,
    92  }
    93  
    94  var helpTestflag = &Command{
    95  	UsageLine: "testflag",
    96  	Short:     "description of testing flags",
    97  	Long: `
    98  The 'go test' command takes both flags that apply to 'go test' itself
    99  and flags that apply to the resulting test binary.
   100  
   101  Several of the flags control profiling and write an execution profile
   102  suitable for "go tool pprof"; run "go tool pprof help" for more
   103  information.  The --alloc_space, --alloc_objects, and --show_bytes
   104  options of pprof control how the information is presented.
   105  
   106  The following flags are recognized by the 'go test' command and
   107  control the execution of any test:
   108  
   109  	-bench regexp
   110  	    Run benchmarks matching the regular expression.
   111  	    By default, no benchmarks run. To run all benchmarks,
   112  	    use '-bench .' or '-bench=.'.
   113  
   114  	-benchmem
   115  	    Print memory allocation statistics for benchmarks.
   116  
   117  	-benchtime t
   118  	    Run enough iterations of each benchmark to take t, specified
   119  	    as a time.Duration (for example, -benchtime 1h30s).
   120  	    The default is 1 second (1s).
   121  
   122  	-blockprofile block.out
   123  	    Write a goroutine blocking profile to the specified file
   124  	    when all tests are complete.
   125  
   126  	-blockprofilerate n
   127  	    Control the detail provided in goroutine blocking profiles by
   128  	    calling runtime.SetBlockProfileRate with n.
   129  	    See 'godoc runtime SetBlockProfileRate'.
   130  	    The profiler aims to sample, on average, one blocking event every
   131  	    n nanoseconds the program spends blocked.  By default,
   132  	    if -test.blockprofile is set without this flag, all blocking events
   133  	    are recorded, equivalent to -test.blockprofilerate=1.
   134  
   135  	-cover
   136  	    Enable coverage analysis.
   137  
   138  	-covermode set,count,atomic
   139  	    Set the mode for coverage analysis for the package[s]
   140  	    being tested. The default is "set" unless -race is enabled,
   141  	    in which case it is "atomic".
   142  	    The values:
   143  		set: bool: does this statement run?
   144  		count: int: how many times does this statement run?
   145  		atomic: int: count, but correct in multithreaded tests;
   146  			significantly more expensive.
   147  	    Sets -cover.
   148  
   149  	-coverpkg pkg1,pkg2,pkg3
   150  	    Apply coverage analysis in each test to the given list of packages.
   151  	    The default is for each test to analyze only the package being tested.
   152  	    Packages are specified as import paths.
   153  	    Sets -cover.
   154  
   155  	-coverprofile cover.out
   156  	    Write a coverage profile to the specified file after all tests
   157  	    have passed.
   158  	    Sets -cover.
   159  
   160  	-cpu 1,2,4
   161  	    Specify a list of GOMAXPROCS values for which the tests or
   162  	    benchmarks should be executed.  The default is the current value
   163  	    of GOMAXPROCS.
   164  
   165  	-cpuprofile cpu.out
   166  	    Write a CPU profile to the specified file before exiting.
   167  
   168  	-memprofile mem.out
   169  	    Write a memory profile to the specified file after all tests
   170  	    have passed.
   171  
   172  	-memprofilerate n
   173  	    Enable more precise (and expensive) memory profiles by setting
   174  	    runtime.MemProfileRate.  See 'godoc runtime MemProfileRate'.
   175  	    To profile all memory allocations, use -test.memprofilerate=1
   176  	    and pass --alloc_space flag to the pprof tool.
   177  
   178  	-outputdir directory
   179  	    Place output files from profiling in the specified directory,
   180  	    by default the directory in which "go test" is running.
   181  
   182  	-parallel n
   183  	    Allow parallel execution of test functions that call t.Parallel.
   184  	    The value of this flag is the maximum number of tests to run
   185  	    simultaneously; by default, it is set to the value of GOMAXPROCS.
   186  
   187  	-run regexp
   188  	    Run only those tests and examples matching the regular
   189  	    expression.
   190  
   191  	-short
   192  	    Tell long-running tests to shorten their run time.
   193  	    It is off by default but set during all.bash so that installing
   194  	    the Go tree can run a sanity check but not spend time running
   195  	    exhaustive tests.
   196  
   197  	-timeout t
   198  	    If a test runs longer than t, panic.
   199  
   200  	-v
   201  	    Verbose output: log all tests as they are run. Also print all
   202  	    text from Log and Logf calls even if the test succeeds.
   203  
   204  The test binary, called pkg.test where pkg is the name of the
   205  directory containing the package sources, can be invoked directly
   206  after building it with 'go test -c'. When invoking the test binary
   207  directly, each of the standard flag names must be prefixed with 'test.',
   208  as in -test.run=TestMyFunc or -test.v.
   209  
   210  When running 'go test', flags not listed above are passed through
   211  unaltered. For instance, the command
   212  
   213  	go test -x -v -cpuprofile=prof.out -dir=testdata -update
   214  
   215  will compile the test binary and then run it as
   216  
   217  	pkg.test -test.v -test.cpuprofile=prof.out -dir=testdata -update
   218  
   219  The test flags that generate profiles (other than for coverage) also
   220  leave the test binary in pkg.test for use when analyzing the profiles.
   221  
   222  Flags not recognized by 'go test' must be placed after any specified packages.
   223  `,
   224  }
   225  
   226  var helpTestfunc = &Command{
   227  	UsageLine: "testfunc",
   228  	Short:     "description of testing functions",
   229  	Long: `
   230  The 'go test' command expects to find test, benchmark, and example functions
   231  in the "*_test.go" files corresponding to the package under test.
   232  
   233  A test function is one named TestXXX (where XXX is any alphanumeric string
   234  not starting with a lower case letter) and should have the signature,
   235  
   236  	func TestXXX(t *testing.T) { ... }
   237  
   238  A benchmark function is one named BenchmarkXXX and should have the signature,
   239  
   240  	func BenchmarkXXX(b *testing.B) { ... }
   241  
   242  An example function is similar to a test function but, instead of using
   243  *testing.T to report success or failure, prints output to os.Stdout.
   244  That output is compared against the function's "Output:" comment, which
   245  must be the last comment in the function body (see example below). An
   246  example with no such comment, or with no text after "Output:" is compiled
   247  but not executed.
   248  
   249  Godoc displays the body of ExampleXXX to demonstrate the use
   250  of the function, constant, or variable XXX.  An example of a method M with
   251  receiver type T or *T is named ExampleT_M.  There may be multiple examples
   252  for a given function, constant, or variable, distinguished by a trailing _xxx,
   253  where xxx is a suffix not beginning with an upper case letter.
   254  
   255  Here is an example of an example:
   256  
   257  	func ExamplePrintln() {
   258  		Println("The output of\nthis example.")
   259  		// Output: The output of
   260  		// this example.
   261  	}
   262  
   263  The entire test file is presented as the example when it contains a single
   264  example function, at least one other function, type, variable, or constant
   265  declaration, and no test or benchmark functions.
   266  
   267  See the documentation of the testing package for more information.
   268  `,
   269  }
   270  
   271  var (
   272  	testC            bool       // -c flag
   273  	testCover        bool       // -cover flag
   274  	testCoverMode    string     // -covermode flag
   275  	testCoverPaths   []string   // -coverpkg flag
   276  	testCoverPkgs    []*Package // -coverpkg flag
   277  	testProfile      bool       // some profiling flag
   278  	testNeedBinary   bool       // profile needs to keep binary around
   279  	testV            bool       // -v flag
   280  	testFiles        []string   // -file flag(s)  TODO: not respected
   281  	testTimeout      string     // -timeout flag
   282  	testArgs         []string
   283  	testBench        bool
   284  	testStreamOutput bool // show output as it is generated
   285  	testShowPass     bool // show passing output
   286  
   287  	testKillTimeout = 10 * time.Minute
   288  )
   289  
   290  var testMainDeps = map[string]bool{
   291  	// Dependencies for testmain.
   292  	"testing": true,
   293  	"regexp":  true,
   294  }
   295  
   296  func runTest(cmd *Command, args []string) {
   297  	var pkgArgs []string
   298  	pkgArgs, testArgs = testFlags(args)
   299  
   300  	findExecCmd() // initialize cached result
   301  
   302  	raceInit()
   303  	pkgs := packagesForBuild(pkgArgs)
   304  	if len(pkgs) == 0 {
   305  		fatalf("no packages to test")
   306  	}
   307  
   308  	if testC && len(pkgs) != 1 {
   309  		fatalf("cannot use -c flag with multiple packages")
   310  	}
   311  	if testProfile && len(pkgs) != 1 {
   312  		fatalf("cannot use test profile flag with multiple packages")
   313  	}
   314  
   315  	// If a test timeout was given and is parseable, set our kill timeout
   316  	// to that timeout plus one minute.  This is a backup alarm in case
   317  	// the test wedges with a goroutine spinning and its background
   318  	// timer does not get a chance to fire.
   319  	if dt, err := time.ParseDuration(testTimeout); err == nil && dt > 0 {
   320  		testKillTimeout = dt + 1*time.Minute
   321  	}
   322  
   323  	// show passing test output (after buffering) with -v flag.
   324  	// must buffer because tests are running in parallel, and
   325  	// otherwise the output will get mixed.
   326  	testShowPass = testV
   327  
   328  	// stream test output (no buffering) when no package has
   329  	// been given on the command line (implicit current directory)
   330  	// or when benchmarking.
   331  	// Also stream if we're showing output anyway with a
   332  	// single package under test.  In that case, streaming the
   333  	// output produces the same result as not streaming,
   334  	// just more immediately.
   335  	testStreamOutput = len(pkgArgs) == 0 || testBench ||
   336  		(len(pkgs) <= 1 && testShowPass)
   337  
   338  	var b builder
   339  	b.init()
   340  
   341  	if buildI {
   342  		buildV = testV
   343  
   344  		deps := make(map[string]bool)
   345  		for dep := range testMainDeps {
   346  			deps[dep] = true
   347  		}
   348  
   349  		for _, p := range pkgs {
   350  			// Dependencies for each test.
   351  			for _, path := range p.Imports {
   352  				deps[path] = true
   353  			}
   354  			for _, path := range p.TestImports {
   355  				deps[path] = true
   356  			}
   357  			for _, path := range p.XTestImports {
   358  				deps[path] = true
   359  			}
   360  		}
   361  
   362  		// translate C to runtime/cgo
   363  		if deps["C"] {
   364  			delete(deps, "C")
   365  			deps["runtime/cgo"] = true
   366  			if buildContext.GOOS == runtime.GOOS && buildContext.GOARCH == runtime.GOARCH {
   367  				deps["cmd/cgo"] = true
   368  			}
   369  		}
   370  		// Ignore pseudo-packages.
   371  		delete(deps, "unsafe")
   372  
   373  		all := []string{}
   374  		for path := range deps {
   375  			if !build.IsLocalImport(path) {
   376  				all = append(all, path)
   377  			}
   378  		}
   379  		sort.Strings(all)
   380  
   381  		a := &action{}
   382  		for _, p := range packagesForBuild(all) {
   383  			a.deps = append(a.deps, b.action(modeInstall, modeInstall, p))
   384  		}
   385  		b.do(a)
   386  		if !testC || a.failed {
   387  			return
   388  		}
   389  		b.init()
   390  	}
   391  
   392  	var builds, runs, prints []*action
   393  
   394  	if testCoverPaths != nil {
   395  		// Load packages that were asked about for coverage.
   396  		// packagesForBuild exits if the packages cannot be loaded.
   397  		testCoverPkgs = packagesForBuild(testCoverPaths)
   398  
   399  		// Warn about -coverpkg arguments that are not actually used.
   400  		used := make(map[string]bool)
   401  		for _, p := range pkgs {
   402  			used[p.ImportPath] = true
   403  			for _, dep := range p.Deps {
   404  				used[dep] = true
   405  			}
   406  		}
   407  		for _, p := range testCoverPkgs {
   408  			if !used[p.ImportPath] {
   409  				log.Printf("warning: no packages being tested depend on %s", p.ImportPath)
   410  			}
   411  		}
   412  
   413  		// Mark all the coverage packages for rebuilding with coverage.
   414  		for _, p := range testCoverPkgs {
   415  			p.Stale = true // rebuild
   416  			p.fake = true  // do not warn about rebuild
   417  			p.coverMode = testCoverMode
   418  			var coverFiles []string
   419  			coverFiles = append(coverFiles, p.GoFiles...)
   420  			coverFiles = append(coverFiles, p.CgoFiles...)
   421  			coverFiles = append(coverFiles, p.TestGoFiles...)
   422  			p.coverVars = declareCoverVars(p.ImportPath, coverFiles...)
   423  		}
   424  	}
   425  
   426  	// Prepare build + run + print actions for all packages being tested.
   427  	for _, p := range pkgs {
   428  		buildTest, runTest, printTest, err := b.test(p)
   429  		if err != nil {
   430  			str := err.Error()
   431  			if strings.HasPrefix(str, "\n") {
   432  				str = str[1:]
   433  			}
   434  			failed := fmt.Sprintf("FAIL\t%s [setup failed]\n", p.ImportPath)
   435  
   436  			if p.ImportPath != "" {
   437  				errorf("# %s\n%s\n%s", p.ImportPath, str, failed)
   438  			} else {
   439  				errorf("%s\n%s", str, failed)
   440  			}
   441  			continue
   442  		}
   443  		builds = append(builds, buildTest)
   444  		runs = append(runs, runTest)
   445  		prints = append(prints, printTest)
   446  	}
   447  
   448  	// Ultimately the goal is to print the output.
   449  	root := &action{deps: prints}
   450  
   451  	// Force the printing of results to happen in order,
   452  	// one at a time.
   453  	for i, a := range prints {
   454  		if i > 0 {
   455  			a.deps = append(a.deps, prints[i-1])
   456  		}
   457  	}
   458  
   459  	// Force benchmarks to run in serial.
   460  	if !testC && testBench {
   461  		// The first run must wait for all builds.
   462  		// Later runs must wait for the previous run's print.
   463  		for i, run := range runs {
   464  			if i == 0 {
   465  				run.deps = append(run.deps, builds...)
   466  			} else {
   467  				run.deps = append(run.deps, prints[i-1])
   468  			}
   469  		}
   470  	}
   471  
   472  	// If we are building any out-of-date packages other
   473  	// than those under test, warn.
   474  	okBuild := map[*Package]bool{}
   475  	for _, p := range pkgs {
   476  		okBuild[p] = true
   477  	}
   478  	warned := false
   479  	for _, a := range actionList(root) {
   480  		if a.p == nil || okBuild[a.p] {
   481  			continue
   482  		}
   483  		okBuild[a.p] = true // warn at most once
   484  
   485  		// Don't warn about packages being rebuilt because of
   486  		// things like coverage analysis.
   487  		for _, p1 := range a.p.imports {
   488  			if p1.fake {
   489  				a.p.fake = true
   490  			}
   491  		}
   492  
   493  		if a.f != nil && !okBuild[a.p] && !a.p.fake && !a.p.local {
   494  			if !warned {
   495  				fmt.Fprintf(os.Stderr, "warning: building out-of-date packages:\n")
   496  				warned = true
   497  			}
   498  			fmt.Fprintf(os.Stderr, "\t%s\n", a.p.ImportPath)
   499  		}
   500  	}
   501  	if warned {
   502  		args := strings.Join(pkgArgs, " ")
   503  		if args != "" {
   504  			args = " " + args
   505  		}
   506  		extraOpts := ""
   507  		if buildRace {
   508  			extraOpts = "-race "
   509  		}
   510  		fmt.Fprintf(os.Stderr, "installing these packages with 'go test %s-i%s' will speed future tests.\n\n", extraOpts, args)
   511  	}
   512  
   513  	b.do(root)
   514  }
   515  
   516  func contains(x []string, s string) bool {
   517  	for _, t := range x {
   518  		if t == s {
   519  			return true
   520  		}
   521  	}
   522  	return false
   523  }
   524  
   525  func (b *builder) test(p *Package) (buildAction, runAction, printAction *action, err error) {
   526  	if len(p.TestGoFiles)+len(p.XTestGoFiles) == 0 {
   527  		build := b.action(modeBuild, modeBuild, p)
   528  		run := &action{p: p, deps: []*action{build}}
   529  		print := &action{f: (*builder).notest, p: p, deps: []*action{run}}
   530  		return build, run, print, nil
   531  	}
   532  
   533  	// Build Package structs describing:
   534  	//	ptest - package + test files
   535  	//	pxtest - package of external test files
   536  	//	pmain - pkg.test binary
   537  	var ptest, pxtest, pmain *Package
   538  
   539  	var imports, ximports []*Package
   540  	var stk importStack
   541  	stk.push(p.ImportPath + " (test)")
   542  	for _, path := range p.TestImports {
   543  		p1 := loadImport(path, p.Dir, &stk, p.build.TestImportPos[path])
   544  		if p1.Error != nil {
   545  			return nil, nil, nil, p1.Error
   546  		}
   547  		if contains(p1.Deps, p.ImportPath) {
   548  			// Same error that loadPackage returns (via reusePackage) in pkg.go.
   549  			// Can't change that code, because that code is only for loading the
   550  			// non-test copy of a package.
   551  			err := &PackageError{
   552  				ImportStack:   testImportStack(stk[0], p1, p.ImportPath),
   553  				Err:           "import cycle not allowed in test",
   554  				isImportCycle: true,
   555  			}
   556  			return nil, nil, nil, err
   557  		}
   558  		imports = append(imports, p1)
   559  	}
   560  	stk.pop()
   561  	stk.push(p.ImportPath + "_test")
   562  	pxtestNeedsPtest := false
   563  	for _, path := range p.XTestImports {
   564  		if path == p.ImportPath {
   565  			pxtestNeedsPtest = true
   566  			continue
   567  		}
   568  		p1 := loadImport(path, p.Dir, &stk, p.build.XTestImportPos[path])
   569  		if p1.Error != nil {
   570  			return nil, nil, nil, p1.Error
   571  		}
   572  		ximports = append(ximports, p1)
   573  	}
   574  	stk.pop()
   575  
   576  	// Use last element of import path, not package name.
   577  	// They differ when package name is "main".
   578  	// But if the import path is "command-line-arguments",
   579  	// like it is during 'go run', use the package name.
   580  	var elem string
   581  	if p.ImportPath == "command-line-arguments" {
   582  		elem = p.Name
   583  	} else {
   584  		_, elem = path.Split(p.ImportPath)
   585  	}
   586  	testBinary := elem + ".test"
   587  
   588  	// The ptest package needs to be importable under the
   589  	// same import path that p has, but we cannot put it in
   590  	// the usual place in the temporary tree, because then
   591  	// other tests will see it as the real package.
   592  	// Instead we make a _test directory under the import path
   593  	// and then repeat the import path there.  We tell the
   594  	// compiler and linker to look in that _test directory first.
   595  	//
   596  	// That is, if the package under test is unicode/utf8,
   597  	// then the normal place to write the package archive is
   598  	// $WORK/unicode/utf8.a, but we write the test package archive to
   599  	// $WORK/unicode/utf8/_test/unicode/utf8.a.
   600  	// We write the external test package archive to
   601  	// $WORK/unicode/utf8/_test/unicode/utf8_test.a.
   602  	testDir := filepath.Join(b.work, filepath.FromSlash(p.ImportPath+"/_test"))
   603  	ptestObj := buildToolchain.pkgpath(testDir, p)
   604  
   605  	// Create the directory for the .a files.
   606  	ptestDir, _ := filepath.Split(ptestObj)
   607  	if err := b.mkdir(ptestDir); err != nil {
   608  		return nil, nil, nil, err
   609  	}
   610  
   611  	// Should we apply coverage analysis locally,
   612  	// only for this package and only for this test?
   613  	// Yes, if -cover is on but -coverpkg has not specified
   614  	// a list of packages for global coverage.
   615  	localCover := testCover && testCoverPaths == nil
   616  
   617  	// Test package.
   618  	if len(p.TestGoFiles) > 0 || localCover || p.Name == "main" {
   619  		ptest = new(Package)
   620  		*ptest = *p
   621  		ptest.GoFiles = nil
   622  		ptest.GoFiles = append(ptest.GoFiles, p.GoFiles...)
   623  		ptest.GoFiles = append(ptest.GoFiles, p.TestGoFiles...)
   624  		ptest.target = ""
   625  		ptest.Imports = stringList(p.Imports, p.TestImports)
   626  		ptest.imports = append(append([]*Package{}, p.imports...), imports...)
   627  		ptest.pkgdir = testDir
   628  		ptest.fake = true
   629  		ptest.forceLibrary = true
   630  		ptest.Stale = true
   631  		ptest.build = new(build.Package)
   632  		*ptest.build = *p.build
   633  		m := map[string][]token.Position{}
   634  		for k, v := range p.build.ImportPos {
   635  			m[k] = append(m[k], v...)
   636  		}
   637  		for k, v := range p.build.TestImportPos {
   638  			m[k] = append(m[k], v...)
   639  		}
   640  		ptest.build.ImportPos = m
   641  
   642  		if localCover {
   643  			ptest.coverMode = testCoverMode
   644  			var coverFiles []string
   645  			coverFiles = append(coverFiles, ptest.GoFiles...)
   646  			coverFiles = append(coverFiles, ptest.CgoFiles...)
   647  			ptest.coverVars = declareCoverVars(ptest.ImportPath, coverFiles...)
   648  		}
   649  	} else {
   650  		ptest = p
   651  	}
   652  
   653  	// External test package.
   654  	if len(p.XTestGoFiles) > 0 {
   655  		pxtest = &Package{
   656  			Name:        p.Name + "_test",
   657  			ImportPath:  p.ImportPath + "_test",
   658  			localPrefix: p.localPrefix,
   659  			Root:        p.Root,
   660  			Dir:         p.Dir,
   661  			GoFiles:     p.XTestGoFiles,
   662  			Imports:     p.XTestImports,
   663  			build: &build.Package{
   664  				ImportPos: p.build.XTestImportPos,
   665  			},
   666  			imports: ximports,
   667  			pkgdir:  testDir,
   668  			fake:    true,
   669  			Stale:   true,
   670  		}
   671  		if pxtestNeedsPtest {
   672  			pxtest.imports = append(pxtest.imports, ptest)
   673  		}
   674  	}
   675  
   676  	// Action for building pkg.test.
   677  	pmain = &Package{
   678  		Name:       "main",
   679  		Dir:        testDir,
   680  		GoFiles:    []string{"_testmain.go"},
   681  		ImportPath: "testmain",
   682  		Root:       p.Root,
   683  		build:      &build.Package{Name: "main"},
   684  		pkgdir:     testDir,
   685  		fake:       true,
   686  		Stale:      true,
   687  		omitDWARF:  !testC && !testNeedBinary,
   688  	}
   689  
   690  	// The generated main also imports testing and regexp.
   691  	stk.push("testmain")
   692  	for dep := range testMainDeps {
   693  		if dep == ptest.ImportPath {
   694  			pmain.imports = append(pmain.imports, ptest)
   695  		} else {
   696  			p1 := loadImport(dep, "", &stk, nil)
   697  			if p1.Error != nil {
   698  				return nil, nil, nil, p1.Error
   699  			}
   700  			pmain.imports = append(pmain.imports, p1)
   701  		}
   702  	}
   703  
   704  	if testCoverPkgs != nil {
   705  		// Add imports, but avoid duplicates.
   706  		seen := map[*Package]bool{p: true, ptest: true}
   707  		for _, p1 := range pmain.imports {
   708  			seen[p1] = true
   709  		}
   710  		for _, p1 := range testCoverPkgs {
   711  			if !seen[p1] {
   712  				seen[p1] = true
   713  				pmain.imports = append(pmain.imports, p1)
   714  			}
   715  		}
   716  	}
   717  
   718  	// Do initial scan for metadata needed for writing _testmain.go
   719  	// Use that metadata to update the list of imports for package main.
   720  	// The list of imports is used by recompileForTest and by the loop
   721  	// afterward that gathers t.Cover information.
   722  	t, err := loadTestFuncs(ptest)
   723  	if err != nil {
   724  		return nil, nil, nil, err
   725  	}
   726  	if t.NeedTest || ptest.coverMode != "" {
   727  		pmain.imports = append(pmain.imports, ptest)
   728  	}
   729  	if t.NeedXtest {
   730  		pmain.imports = append(pmain.imports, pxtest)
   731  	}
   732  
   733  	if ptest != p && localCover {
   734  		// We have made modifications to the package p being tested
   735  		// and are rebuilding p (as ptest), writing it to the testDir tree.
   736  		// Arrange to rebuild, writing to that same tree, all packages q
   737  		// such that the test depends on q, and q depends on p.
   738  		// This makes sure that q sees the modifications to p.
   739  		// Strictly speaking, the rebuild is only necessary if the
   740  		// modifications to p change its export metadata, but
   741  		// determining that is a bit tricky, so we rebuild always.
   742  		//
   743  		// This will cause extra compilation, so for now we only do it
   744  		// when testCover is set. The conditions are more general, though,
   745  		// and we may find that we need to do it always in the future.
   746  		recompileForTest(pmain, p, ptest, testDir)
   747  	}
   748  
   749  	for _, cp := range pmain.imports {
   750  		if len(cp.coverVars) > 0 {
   751  			t.Cover = append(t.Cover, coverInfo{cp, cp.coverVars})
   752  		}
   753  	}
   754  
   755  	// writeTestmain writes _testmain.go. This must happen after recompileForTest,
   756  	// because recompileForTest modifies XXX.
   757  	if err := writeTestmain(filepath.Join(testDir, "_testmain.go"), t); err != nil {
   758  		return nil, nil, nil, err
   759  	}
   760  
   761  	computeStale(pmain)
   762  
   763  	if ptest != p {
   764  		a := b.action(modeBuild, modeBuild, ptest)
   765  		a.objdir = testDir + string(filepath.Separator) + "_obj_test" + string(filepath.Separator)
   766  		a.objpkg = ptestObj
   767  		a.target = ptestObj
   768  		a.link = false
   769  	}
   770  
   771  	if pxtest != nil {
   772  		a := b.action(modeBuild, modeBuild, pxtest)
   773  		a.objdir = testDir + string(filepath.Separator) + "_obj_xtest" + string(filepath.Separator)
   774  		a.objpkg = buildToolchain.pkgpath(testDir, pxtest)
   775  		a.target = a.objpkg
   776  	}
   777  
   778  	a := b.action(modeBuild, modeBuild, pmain)
   779  	a.objdir = testDir + string(filepath.Separator)
   780  	a.objpkg = filepath.Join(testDir, "main.a")
   781  	a.target = filepath.Join(testDir, testBinary) + exeSuffix
   782  	pmainAction := a
   783  
   784  	if testC || testNeedBinary {
   785  		// -c or profiling flag: create action to copy binary to ./test.out.
   786  		runAction = &action{
   787  			f:      (*builder).install,
   788  			deps:   []*action{pmainAction},
   789  			p:      pmain,
   790  			target: filepath.Join(cwd, testBinary+exeSuffix),
   791  		}
   792  		pmainAction = runAction // in case we are running the test
   793  	}
   794  	if testC {
   795  		printAction = &action{p: p, deps: []*action{runAction}} // nop
   796  	} else {
   797  		// run test
   798  		runAction = &action{
   799  			f:          (*builder).runTest,
   800  			deps:       []*action{pmainAction},
   801  			p:          p,
   802  			ignoreFail: true,
   803  		}
   804  		cleanAction := &action{
   805  			f:    (*builder).cleanTest,
   806  			deps: []*action{runAction},
   807  			p:    p,
   808  		}
   809  		printAction = &action{
   810  			f:    (*builder).printTest,
   811  			deps: []*action{cleanAction},
   812  			p:    p,
   813  		}
   814  	}
   815  
   816  	return pmainAction, runAction, printAction, nil
   817  }
   818  
   819  func testImportStack(top string, p *Package, target string) []string {
   820  	stk := []string{top, p.ImportPath}
   821  Search:
   822  	for p.ImportPath != target {
   823  		for _, p1 := range p.imports {
   824  			if p1.ImportPath == target || contains(p1.Deps, target) {
   825  				stk = append(stk, p1.ImportPath)
   826  				p = p1
   827  				continue Search
   828  			}
   829  		}
   830  		// Can't happen, but in case it does...
   831  		stk = append(stk, "<lost path to cycle>")
   832  		break
   833  	}
   834  	return stk
   835  }
   836  
   837  func recompileForTest(pmain, preal, ptest *Package, testDir string) {
   838  	// The "test copy" of preal is ptest.
   839  	// For each package that depends on preal, make a "test copy"
   840  	// that depends on ptest. And so on, up the dependency tree.
   841  	testCopy := map[*Package]*Package{preal: ptest}
   842  	for _, p := range packageList([]*Package{pmain}) {
   843  		// Copy on write.
   844  		didSplit := false
   845  		split := func() {
   846  			if didSplit {
   847  				return
   848  			}
   849  			didSplit = true
   850  			if p.pkgdir != testDir {
   851  				p1 := new(Package)
   852  				testCopy[p] = p1
   853  				*p1 = *p
   854  				p1.imports = make([]*Package, len(p.imports))
   855  				copy(p1.imports, p.imports)
   856  				p = p1
   857  				p.pkgdir = testDir
   858  				p.target = ""
   859  				p.fake = true
   860  				p.Stale = true
   861  			}
   862  		}
   863  
   864  		// Update p.deps and p.imports to use at test copies.
   865  		for i, dep := range p.deps {
   866  			if p1 := testCopy[dep]; p1 != nil && p1 != dep {
   867  				split()
   868  				p.deps[i] = p1
   869  			}
   870  		}
   871  		for i, imp := range p.imports {
   872  			if p1 := testCopy[imp]; p1 != nil && p1 != imp {
   873  				split()
   874  				p.imports[i] = p1
   875  			}
   876  		}
   877  	}
   878  }
   879  
   880  var coverIndex = 0
   881  
   882  // isTestFile reports whether the source file is a set of tests and should therefore
   883  // be excluded from coverage analysis.
   884  func isTestFile(file string) bool {
   885  	// We don't cover tests, only the code they test.
   886  	return strings.HasSuffix(file, "_test.go")
   887  }
   888  
   889  // declareCoverVars attaches the required cover variables names
   890  // to the files, to be used when annotating the files.
   891  func declareCoverVars(importPath string, files ...string) map[string]*CoverVar {
   892  	coverVars := make(map[string]*CoverVar)
   893  	for _, file := range files {
   894  		if isTestFile(file) {
   895  			continue
   896  		}
   897  		coverVars[file] = &CoverVar{
   898  			File: filepath.Join(importPath, file),
   899  			Var:  fmt.Sprintf("GoCover_%d", coverIndex),
   900  		}
   901  		coverIndex++
   902  	}
   903  	return coverVars
   904  }
   905  
   906  // runTest is the action for running a test binary.
   907  func (b *builder) runTest(a *action) error {
   908  	args := stringList(findExecCmd(), a.deps[0].target, testArgs)
   909  	a.testOutput = new(bytes.Buffer)
   910  
   911  	if buildN || buildX {
   912  		b.showcmd("", "%s", strings.Join(args, " "))
   913  		if buildN {
   914  			return nil
   915  		}
   916  	}
   917  
   918  	if a.failed {
   919  		// We were unable to build the binary.
   920  		a.failed = false
   921  		fmt.Fprintf(a.testOutput, "FAIL\t%s [build failed]\n", a.p.ImportPath)
   922  		setExitStatus(1)
   923  		return nil
   924  	}
   925  
   926  	cmd := exec.Command(args[0], args[1:]...)
   927  	cmd.Dir = a.p.Dir
   928  	cmd.Env = envForDir(cmd.Dir)
   929  	var buf bytes.Buffer
   930  	if testStreamOutput {
   931  		cmd.Stdout = os.Stdout
   932  		cmd.Stderr = os.Stderr
   933  	} else {
   934  		cmd.Stdout = &buf
   935  		cmd.Stderr = &buf
   936  	}
   937  
   938  	// If there are any local SWIG dependencies, we want to load
   939  	// the shared library from the build directory.
   940  	if a.p.usesSwig() {
   941  		env := cmd.Env
   942  		found := false
   943  		prefix := "LD_LIBRARY_PATH="
   944  		for i, v := range env {
   945  			if strings.HasPrefix(v, prefix) {
   946  				env[i] = v + ":."
   947  				found = true
   948  				break
   949  			}
   950  		}
   951  		if !found {
   952  			env = append(env, "LD_LIBRARY_PATH=.")
   953  		}
   954  		cmd.Env = env
   955  	}
   956  
   957  	t0 := time.Now()
   958  	err := cmd.Start()
   959  
   960  	// This is a last-ditch deadline to detect and
   961  	// stop wedged test binaries, to keep the builders
   962  	// running.
   963  	if err == nil {
   964  		tick := time.NewTimer(testKillTimeout)
   965  		startSigHandlers()
   966  		done := make(chan error)
   967  		go func() {
   968  			done <- cmd.Wait()
   969  		}()
   970  	Outer:
   971  		select {
   972  		case err = <-done:
   973  			// ok
   974  		case <-tick.C:
   975  			if signalTrace != nil {
   976  				// Send a quit signal in the hope that the program will print
   977  				// a stack trace and exit. Give it five seconds before resorting
   978  				// to Kill.
   979  				cmd.Process.Signal(signalTrace)
   980  				select {
   981  				case err = <-done:
   982  					fmt.Fprintf(&buf, "*** Test killed with %v: ran too long (%v).\n", signalTrace, testKillTimeout)
   983  					break Outer
   984  				case <-time.After(5 * time.Second):
   985  				}
   986  			}
   987  			cmd.Process.Kill()
   988  			err = <-done
   989  			fmt.Fprintf(&buf, "*** Test killed: ran too long (%v).\n", testKillTimeout)
   990  		}
   991  		tick.Stop()
   992  	}
   993  	out := buf.Bytes()
   994  	t := fmt.Sprintf("%.3fs", time.Since(t0).Seconds())
   995  	if err == nil {
   996  		if testShowPass {
   997  			a.testOutput.Write(out)
   998  		}
   999  		fmt.Fprintf(a.testOutput, "ok  \t%s\t%s%s\n", a.p.ImportPath, t, coveragePercentage(out))
  1000  		return nil
  1001  	}
  1002  
  1003  	setExitStatus(1)
  1004  	if len(out) > 0 {
  1005  		a.testOutput.Write(out)
  1006  		// assume printing the test binary's exit status is superfluous
  1007  	} else {
  1008  		fmt.Fprintf(a.testOutput, "%s\n", err)
  1009  	}
  1010  	fmt.Fprintf(a.testOutput, "FAIL\t%s\t%s\n", a.p.ImportPath, t)
  1011  
  1012  	return nil
  1013  }
  1014  
  1015  // coveragePercentage returns the coverage results (if enabled) for the
  1016  // test. It uncovers the data by scanning the output from the test run.
  1017  func coveragePercentage(out []byte) string {
  1018  	if !testCover {
  1019  		return ""
  1020  	}
  1021  	// The string looks like
  1022  	//	test coverage for encoding/binary: 79.9% of statements
  1023  	// Extract the piece from the percentage to the end of the line.
  1024  	re := regexp.MustCompile(`coverage: (.*)\n`)
  1025  	matches := re.FindSubmatch(out)
  1026  	if matches == nil {
  1027  		// Probably running "go test -cover" not "go test -cover fmt".
  1028  		// The coverage output will appear in the output directly.
  1029  		return ""
  1030  	}
  1031  	return fmt.Sprintf("\tcoverage: %s", matches[1])
  1032  }
  1033  
  1034  // cleanTest is the action for cleaning up after a test.
  1035  func (b *builder) cleanTest(a *action) error {
  1036  	if buildWork {
  1037  		return nil
  1038  	}
  1039  	run := a.deps[0]
  1040  	testDir := filepath.Join(b.work, filepath.FromSlash(run.p.ImportPath+"/_test"))
  1041  	os.RemoveAll(testDir)
  1042  	return nil
  1043  }
  1044  
  1045  // printTest is the action for printing a test result.
  1046  func (b *builder) printTest(a *action) error {
  1047  	clean := a.deps[0]
  1048  	run := clean.deps[0]
  1049  	os.Stdout.Write(run.testOutput.Bytes())
  1050  	run.testOutput = nil
  1051  	return nil
  1052  }
  1053  
  1054  // notest is the action for testing a package with no test files.
  1055  func (b *builder) notest(a *action) error {
  1056  	fmt.Printf("?   \t%s\t[no test files]\n", a.p.ImportPath)
  1057  	return nil
  1058  }
  1059  
  1060  // isTest tells whether name looks like a test (or benchmark, according to prefix).
  1061  // It is a Test (say) if there is a character after Test that is not a lower-case letter.
  1062  // We don't want TesticularCancer.
  1063  func isTest(name, prefix string) bool {
  1064  	if !strings.HasPrefix(name, prefix) {
  1065  		return false
  1066  	}
  1067  	if len(name) == len(prefix) { // "Test" is ok
  1068  		return true
  1069  	}
  1070  	rune, _ := utf8.DecodeRuneInString(name[len(prefix):])
  1071  	return !unicode.IsLower(rune)
  1072  }
  1073  
  1074  type coverInfo struct {
  1075  	Package *Package
  1076  	Vars    map[string]*CoverVar
  1077  }
  1078  
  1079  // loadTestFuncs returns the testFuncs describing the tests that will be run.
  1080  func loadTestFuncs(ptest *Package) (*testFuncs, error) {
  1081  	t := &testFuncs{
  1082  		Package: ptest,
  1083  	}
  1084  	for _, file := range ptest.TestGoFiles {
  1085  		if err := t.load(filepath.Join(ptest.Dir, file), "_test", &t.NeedTest); err != nil {
  1086  			return nil, err
  1087  		}
  1088  	}
  1089  	for _, file := range ptest.XTestGoFiles {
  1090  		if err := t.load(filepath.Join(ptest.Dir, file), "_xtest", &t.NeedXtest); err != nil {
  1091  			return nil, err
  1092  		}
  1093  	}
  1094  	return t, nil
  1095  }
  1096  
  1097  // writeTestmain writes the _testmain.go file for t to the file named out.
  1098  func writeTestmain(out string, t *testFuncs) error {
  1099  	f, err := os.Create(out)
  1100  	if err != nil {
  1101  		return err
  1102  	}
  1103  	defer f.Close()
  1104  
  1105  	if err := testmainTmpl.Execute(f, t); err != nil {
  1106  		return err
  1107  	}
  1108  
  1109  	return nil
  1110  }
  1111  
  1112  type testFuncs struct {
  1113  	Tests      []testFunc
  1114  	Benchmarks []testFunc
  1115  	Examples   []testFunc
  1116  	Package    *Package
  1117  	NeedTest   bool
  1118  	NeedXtest  bool
  1119  	Cover      []coverInfo
  1120  }
  1121  
  1122  func (t *testFuncs) CoverMode() string {
  1123  	return testCoverMode
  1124  }
  1125  
  1126  func (t *testFuncs) CoverEnabled() bool {
  1127  	return testCover
  1128  }
  1129  
  1130  // Covered returns a string describing which packages are being tested for coverage.
  1131  // If the covered package is the same as the tested package, it returns the empty string.
  1132  // Otherwise it is a comma-separated human-readable list of packages beginning with
  1133  // " in", ready for use in the coverage message.
  1134  func (t *testFuncs) Covered() string {
  1135  	if testCoverPaths == nil {
  1136  		return ""
  1137  	}
  1138  	return " in " + strings.Join(testCoverPaths, ", ")
  1139  }
  1140  
  1141  // Tested returns the name of the package being tested.
  1142  func (t *testFuncs) Tested() string {
  1143  	return t.Package.Name
  1144  }
  1145  
  1146  type testFunc struct {
  1147  	Package string // imported package name (_test or _xtest)
  1148  	Name    string // function name
  1149  	Output  string // output, for examples
  1150  }
  1151  
  1152  var testFileSet = token.NewFileSet()
  1153  
  1154  func (t *testFuncs) load(filename, pkg string, seen *bool) error {
  1155  	f, err := parser.ParseFile(testFileSet, filename, nil, parser.ParseComments)
  1156  	if err != nil {
  1157  		return expandScanner(err)
  1158  	}
  1159  	for _, d := range f.Decls {
  1160  		n, ok := d.(*ast.FuncDecl)
  1161  		if !ok {
  1162  			continue
  1163  		}
  1164  		if n.Recv != nil {
  1165  			continue
  1166  		}
  1167  		name := n.Name.String()
  1168  		switch {
  1169  		case isTest(name, "Test"):
  1170  			t.Tests = append(t.Tests, testFunc{pkg, name, ""})
  1171  			*seen = true
  1172  		case isTest(name, "Benchmark"):
  1173  			t.Benchmarks = append(t.Benchmarks, testFunc{pkg, name, ""})
  1174  			*seen = true
  1175  		}
  1176  	}
  1177  	ex := doc.Examples(f)
  1178  	sort.Sort(byOrder(ex))
  1179  	for _, e := range ex {
  1180  		if e.Output == "" && !e.EmptyOutput {
  1181  			// Don't run examples with no output.
  1182  			continue
  1183  		}
  1184  		t.Examples = append(t.Examples, testFunc{pkg, "Example" + e.Name, e.Output})
  1185  		*seen = true
  1186  	}
  1187  	return nil
  1188  }
  1189  
  1190  type byOrder []*doc.Example
  1191  
  1192  func (x byOrder) Len() int           { return len(x) }
  1193  func (x byOrder) Swap(i, j int)      { x[i], x[j] = x[j], x[i] }
  1194  func (x byOrder) Less(i, j int) bool { return x[i].Order < x[j].Order }
  1195  
  1196  var testmainTmpl = template.Must(template.New("main").Parse(`
  1197  package main
  1198  
  1199  import (
  1200  	"regexp"
  1201  	"testing"
  1202  
  1203  {{if .NeedTest}}
  1204  	_test {{.Package.ImportPath | printf "%q"}}
  1205  {{end}}
  1206  {{if .NeedXtest}}
  1207  	_xtest {{.Package.ImportPath | printf "%s_test" | printf "%q"}}
  1208  {{end}}
  1209  {{range $i, $p := .Cover}}
  1210  	_cover{{$i}} {{$p.Package.ImportPath | printf "%q"}}
  1211  {{end}}
  1212  )
  1213  
  1214  var tests = []testing.InternalTest{
  1215  {{range .Tests}}
  1216  	{"{{.Name}}", {{.Package}}.{{.Name}}},
  1217  {{end}}
  1218  }
  1219  
  1220  var benchmarks = []testing.InternalBenchmark{
  1221  {{range .Benchmarks}}
  1222  	{"{{.Name}}", {{.Package}}.{{.Name}}},
  1223  {{end}}
  1224  }
  1225  
  1226  var examples = []testing.InternalExample{
  1227  {{range .Examples}}
  1228  	{"{{.Name}}", {{.Package}}.{{.Name}}, {{.Output | printf "%q"}}},
  1229  {{end}}
  1230  }
  1231  
  1232  var matchPat string
  1233  var matchRe *regexp.Regexp
  1234  
  1235  func matchString(pat, str string) (result bool, err error) {
  1236  	if matchRe == nil || matchPat != pat {
  1237  		matchPat = pat
  1238  		matchRe, err = regexp.Compile(matchPat)
  1239  		if err != nil {
  1240  			return
  1241  		}
  1242  	}
  1243  	return matchRe.MatchString(str), nil
  1244  }
  1245  
  1246  {{if .CoverEnabled}}
  1247  
  1248  // Only updated by init functions, so no need for atomicity.
  1249  var (
  1250  	coverCounters = make(map[string][]uint32)
  1251  	coverBlocks = make(map[string][]testing.CoverBlock)
  1252  )
  1253  
  1254  func init() {
  1255  	{{range $i, $p := .Cover}}
  1256  	{{range $file, $cover := $p.Vars}}
  1257  	coverRegisterFile({{printf "%q" $cover.File}}, _cover{{$i}}.{{$cover.Var}}.Count[:], _cover{{$i}}.{{$cover.Var}}.Pos[:], _cover{{$i}}.{{$cover.Var}}.NumStmt[:])
  1258  	{{end}}
  1259  	{{end}}
  1260  }
  1261  
  1262  func coverRegisterFile(fileName string, counter []uint32, pos []uint32, numStmts []uint16) {
  1263  	if 3*len(counter) != len(pos) || len(counter) != len(numStmts) {
  1264  		panic("coverage: mismatched sizes")
  1265  	}
  1266  	if coverCounters[fileName] != nil {
  1267  		// Already registered.
  1268  		return
  1269  	}
  1270  	coverCounters[fileName] = counter
  1271  	block := make([]testing.CoverBlock, len(counter))
  1272  	for i := range counter {
  1273  		block[i] = testing.CoverBlock{
  1274  			Line0: pos[3*i+0],
  1275  			Col0: uint16(pos[3*i+2]),
  1276  			Line1: pos[3*i+1],
  1277  			Col1: uint16(pos[3*i+2]>>16),
  1278  			Stmts: numStmts[i],
  1279  		}
  1280  	}
  1281  	coverBlocks[fileName] = block
  1282  }
  1283  {{end}}
  1284  
  1285  func main() {
  1286  {{if .CoverEnabled}}
  1287  	testing.RegisterCover(testing.Cover{
  1288  		Mode: {{printf "%q" .CoverMode}},
  1289  		Counters: coverCounters,
  1290  		Blocks: coverBlocks,
  1291  		CoveredPackages: {{printf "%q" .Covered}},
  1292  	})
  1293  {{end}}
  1294  	testing.Main(matchString, tests, benchmarks, examples)
  1295  }
  1296  
  1297  `))