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