Source file src/cmd/go/internal/load/test.go

     1  // Copyright 2018 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 load
     6  
     7  import (
     8  	"bytes"
     9  	"context"
    10  	"errors"
    11  	"fmt"
    12  	"go/ast"
    13  	"go/build"
    14  	"go/doc"
    15  	"go/parser"
    16  	"go/token"
    17  	"internal/lazytemplate"
    18  	"maps"
    19  	"path/filepath"
    20  	"slices"
    21  	"sort"
    22  	"strings"
    23  	"unicode"
    24  	"unicode/utf8"
    25  
    26  	"cmd/go/internal/fsys"
    27  	"cmd/go/internal/str"
    28  	"cmd/go/internal/trace"
    29  )
    30  
    31  var TestMainDeps = []string{
    32  	// Dependencies for testmain.
    33  	"os",
    34  	"reflect",
    35  	"testing",
    36  	"testing/internal/testdeps",
    37  }
    38  
    39  type TestCover struct {
    40  	Mode  string
    41  	Local bool
    42  	Pkgs  []*Package
    43  	Paths []string
    44  }
    45  
    46  // TestPackagesFor is like TestPackagesAndErrors but it returns
    47  // the package containing an error if the test packages or
    48  // their dependencies have errors.
    49  // Only test packages without errors are returned.
    50  func TestPackagesFor(ctx context.Context, opts PackageOpts, p *Package, cover *TestCover) (pmain, ptest, pxtest, perr *Package) {
    51  	pmain, ptest, pxtest = TestPackagesAndErrors(ctx, nil, opts, p, cover)
    52  	for _, p1 := range []*Package{ptest, pxtest, pmain} {
    53  		if p1 == nil {
    54  			// pxtest may be nil
    55  			continue
    56  		}
    57  		if p1.Error != nil {
    58  			perr = p1
    59  			break
    60  		}
    61  		if p1.Incomplete {
    62  			ps := PackageList([]*Package{p1})
    63  			for _, p := range ps {
    64  				if p.Error != nil {
    65  					perr = p
    66  					break
    67  				}
    68  			}
    69  			break
    70  		}
    71  	}
    72  	if pmain.Error != nil || pmain.Incomplete {
    73  		pmain = nil
    74  	}
    75  	if ptest.Error != nil || ptest.Incomplete {
    76  		ptest = nil
    77  	}
    78  	if pxtest != nil && (pxtest.Error != nil || pxtest.Incomplete) {
    79  		pxtest = nil
    80  	}
    81  	return pmain, ptest, pxtest, perr
    82  }
    83  
    84  // TestPackagesAndErrors returns three packages:
    85  //   - pmain, the package main corresponding to the test binary (running tests in ptest and pxtest).
    86  //   - ptest, the package p compiled with added "package p" test files.
    87  //   - pxtest, the result of compiling any "package p_test" (external) test files.
    88  //
    89  // If the package has no "package p_test" test files, pxtest will be nil.
    90  // If the non-test compilation of package p can be reused
    91  // (for example, if there are no "package p" test files and
    92  // package p need not be instrumented for coverage or any other reason),
    93  // then the returned ptest == p.
    94  //
    95  // If done is non-nil, TestPackagesAndErrors will finish filling out the returned
    96  // package structs in a goroutine and call done once finished. The members of the
    97  // returned packages should not be accessed until done is called.
    98  //
    99  // The caller is expected to have checked that len(p.TestGoFiles)+len(p.XTestGoFiles) > 0,
   100  // or else there's no point in any of this.
   101  func TestPackagesAndErrors(ctx context.Context, done func(), opts PackageOpts, p *Package, cover *TestCover) (pmain, ptest, pxtest *Package) {
   102  	ctx, span := trace.StartSpan(ctx, "load.TestPackagesAndErrors")
   103  	defer span.Done()
   104  
   105  	pre := newPreload()
   106  	defer pre.flush()
   107  	allImports := append([]string{}, p.TestImports...)
   108  	allImports = append(allImports, p.XTestImports...)
   109  	pre.preloadImports(ctx, opts, allImports, p.Internal.Build)
   110  
   111  	var ptestErr, pxtestErr *PackageError
   112  	var imports, ximports []*Package
   113  	var stk ImportStack
   114  	var testEmbed, xtestEmbed map[string][]string
   115  	var incomplete bool
   116  	stk.Push(ImportInfo{Pkg: p.ImportPath + " (test)"})
   117  	rawTestImports := str.StringList(p.TestImports)
   118  	for i, path := range p.TestImports {
   119  		p1, err := loadImport(ctx, opts, pre, path, p.Dir, p, &stk, p.Internal.Build.TestImportPos[path], ResolveImport)
   120  		if err != nil && ptestErr == nil {
   121  			ptestErr = err
   122  			incomplete = true
   123  		}
   124  		if p1.Incomplete {
   125  			incomplete = true
   126  		}
   127  		p.TestImports[i] = p1.ImportPath
   128  		imports = append(imports, p1)
   129  	}
   130  	var err error
   131  	p.TestEmbedFiles, testEmbed, err = resolveEmbed(p.Dir, p.TestEmbedPatterns)
   132  	if err != nil {
   133  		ptestErr = &PackageError{
   134  			ImportStack: stk.Copy(),
   135  			Err:         err,
   136  		}
   137  		incomplete = true
   138  		embedErr := err.(*EmbedError)
   139  		ptestErr.setPos(p.Internal.Build.TestEmbedPatternPos[embedErr.Pattern])
   140  	}
   141  	stk.Pop()
   142  
   143  	stk.Push(ImportInfo{Pkg: p.ImportPath + "_test"})
   144  	pxtestNeedsPtest := false
   145  	var pxtestIncomplete bool
   146  	rawXTestImports := str.StringList(p.XTestImports)
   147  	for i, path := range p.XTestImports {
   148  		p1, err := loadImport(ctx, opts, pre, path, p.Dir, p, &stk, p.Internal.Build.XTestImportPos[path], ResolveImport)
   149  		if err != nil && pxtestErr == nil {
   150  			pxtestErr = err
   151  		}
   152  		if p1.Incomplete {
   153  			pxtestIncomplete = true
   154  		}
   155  		if p1.ImportPath == p.ImportPath {
   156  			pxtestNeedsPtest = true
   157  		} else {
   158  			ximports = append(ximports, p1)
   159  		}
   160  		p.XTestImports[i] = p1.ImportPath
   161  	}
   162  	p.XTestEmbedFiles, xtestEmbed, err = resolveEmbed(p.Dir, p.XTestEmbedPatterns)
   163  	if err != nil && pxtestErr == nil {
   164  		pxtestErr = &PackageError{
   165  			ImportStack: stk.Copy(),
   166  			Err:         err,
   167  		}
   168  		embedErr := err.(*EmbedError)
   169  		pxtestErr.setPos(p.Internal.Build.XTestEmbedPatternPos[embedErr.Pattern])
   170  	}
   171  	pxtestIncomplete = pxtestIncomplete || pxtestErr != nil
   172  	stk.Pop()
   173  
   174  	// Test package.
   175  	if len(p.TestGoFiles) > 0 || p.Name == "main" || cover != nil && cover.Local {
   176  		ptest = new(Package)
   177  		*ptest = *p
   178  		if ptest.Error == nil {
   179  			ptest.Error = ptestErr
   180  		}
   181  		ptest.Incomplete = ptest.Incomplete || incomplete
   182  		ptest.ForTest = p.ImportPath
   183  		ptest.GoFiles = nil
   184  		ptest.GoFiles = append(ptest.GoFiles, p.GoFiles...)
   185  		ptest.GoFiles = append(ptest.GoFiles, p.TestGoFiles...)
   186  		ptest.Target = ""
   187  		// Note: The preparation of the vet config requires that common
   188  		// indexes in ptest.Imports and ptest.Internal.RawImports
   189  		// all line up (but RawImports can be shorter than the others).
   190  		// That is, for 0 ≤ i < len(RawImports),
   191  		// RawImports[i] is the import string in the program text, and
   192  		// Imports[i] is the expanded import string (vendoring applied or relative path expanded away).
   193  		// Any implicitly added imports appear in Imports and Internal.Imports
   194  		// but not RawImports (because they were not in the source code).
   195  		// We insert TestImports, imports, and rawTestImports at the start of
   196  		// these lists to preserve the alignment.
   197  		// Note that p.Internal.Imports may not be aligned with p.Imports/p.Internal.RawImports,
   198  		// but we insert at the beginning there too just for consistency.
   199  		ptest.Imports = str.StringList(p.TestImports, p.Imports)
   200  		ptest.Internal.Imports = append(imports, p.Internal.Imports...)
   201  		ptest.Internal.RawImports = str.StringList(rawTestImports, p.Internal.RawImports)
   202  		ptest.Internal.ForceLibrary = true
   203  		ptest.Internal.BuildInfo = nil
   204  		ptest.Internal.Build = new(build.Package)
   205  		*ptest.Internal.Build = *p.Internal.Build
   206  		m := map[string][]token.Position{}
   207  		for k, v := range p.Internal.Build.ImportPos {
   208  			m[k] = append(m[k], v...)
   209  		}
   210  		for k, v := range p.Internal.Build.TestImportPos {
   211  			m[k] = append(m[k], v...)
   212  		}
   213  		ptest.Internal.Build.ImportPos = m
   214  		if testEmbed == nil && len(p.Internal.Embed) > 0 {
   215  			testEmbed = map[string][]string{}
   216  		}
   217  		maps.Copy(testEmbed, p.Internal.Embed)
   218  		ptest.Internal.Embed = testEmbed
   219  		ptest.EmbedFiles = str.StringList(p.EmbedFiles, p.TestEmbedFiles)
   220  		ptest.Internal.OrigImportPath = p.Internal.OrigImportPath
   221  		ptest.Internal.PGOProfile = p.Internal.PGOProfile
   222  		ptest.Internal.Build.Directives = append(slices.Clip(p.Internal.Build.Directives), p.Internal.Build.TestDirectives...)
   223  	} else {
   224  		ptest = p
   225  	}
   226  
   227  	// External test package.
   228  	if len(p.XTestGoFiles) > 0 {
   229  		pxtest = &Package{
   230  			PackagePublic: PackagePublic{
   231  				Name:       p.Name + "_test",
   232  				ImportPath: p.ImportPath + "_test",
   233  				Root:       p.Root,
   234  				Dir:        p.Dir,
   235  				Goroot:     p.Goroot,
   236  				GoFiles:    p.XTestGoFiles,
   237  				Imports:    p.XTestImports,
   238  				ForTest:    p.ImportPath,
   239  				Module:     p.Module,
   240  				Error:      pxtestErr,
   241  				Incomplete: pxtestIncomplete,
   242  				EmbedFiles: p.XTestEmbedFiles,
   243  			},
   244  			Internal: PackageInternal{
   245  				LocalPrefix: p.Internal.LocalPrefix,
   246  				Build: &build.Package{
   247  					ImportPos:  p.Internal.Build.XTestImportPos,
   248  					Directives: p.Internal.Build.XTestDirectives,
   249  				},
   250  				Imports:    ximports,
   251  				RawImports: rawXTestImports,
   252  
   253  				Asmflags:       p.Internal.Asmflags,
   254  				Gcflags:        p.Internal.Gcflags,
   255  				Ldflags:        p.Internal.Ldflags,
   256  				Gccgoflags:     p.Internal.Gccgoflags,
   257  				Embed:          xtestEmbed,
   258  				OrigImportPath: p.Internal.OrigImportPath,
   259  				PGOProfile:     p.Internal.PGOProfile,
   260  			},
   261  		}
   262  		if pxtestNeedsPtest {
   263  			pxtest.Internal.Imports = append(pxtest.Internal.Imports, ptest)
   264  		}
   265  	}
   266  
   267  	// Arrange for testing.Testing to report true.
   268  	ldflags := append(p.Internal.Ldflags, "-X", "testing.testBinary=1")
   269  	gccgoflags := append(p.Internal.Gccgoflags, "-Wl,--defsym,testing.gccgoTestBinary=1")
   270  
   271  	// Build main package.
   272  	pmain = &Package{
   273  		PackagePublic: PackagePublic{
   274  			Name:       "main",
   275  			Dir:        p.Dir,
   276  			GoFiles:    []string{"_testmain.go"},
   277  			ImportPath: p.ImportPath + ".test",
   278  			Root:       p.Root,
   279  			Imports:    str.StringList(TestMainDeps),
   280  			Module:     p.Module,
   281  		},
   282  		Internal: PackageInternal{
   283  			Build:          &build.Package{Name: "main"},
   284  			BuildInfo:      p.Internal.BuildInfo,
   285  			Asmflags:       p.Internal.Asmflags,
   286  			Gcflags:        p.Internal.Gcflags,
   287  			Ldflags:        ldflags,
   288  			Gccgoflags:     gccgoflags,
   289  			OrigImportPath: p.Internal.OrigImportPath,
   290  			PGOProfile:     p.Internal.PGOProfile,
   291  		},
   292  	}
   293  
   294  	pb := p.Internal.Build
   295  	pmain.DefaultGODEBUG = defaultGODEBUG(pmain, pb.Directives, pb.TestDirectives, pb.XTestDirectives)
   296  	if pmain.Internal.BuildInfo == nil || pmain.DefaultGODEBUG != p.DefaultGODEBUG {
   297  		// Either we didn't generate build info for the package under test (because it wasn't package main), or
   298  		// the DefaultGODEBUG used to build the test main package is different from the DefaultGODEBUG
   299  		// used to build the package under test. If we didn't set build info for the package under test
   300  		// pmain won't have buildinfo set (since we copy it from the package under test). If the default GODEBUG
   301  		// used for the package under test is different from that of the test main, the BuildInfo assigned above from the package
   302  		// under test incorrect for the test main package. Either set or correct pmain's build info.
   303  		pmain.setBuildInfo(ctx, opts.AutoVCS)
   304  	}
   305  
   306  	// The generated main also imports testing, regexp, and os.
   307  	// Also the linker introduces implicit dependencies reported by LinkerDeps.
   308  	stk.Push(ImportInfo{Pkg: "testmain"})
   309  	deps := TestMainDeps // cap==len, so safe for append
   310  	if cover != nil {
   311  		deps = append(deps, "internal/coverage/cfile")
   312  	}
   313  	ldDeps, err := LinkerDeps(p)
   314  	if err != nil && pmain.Error == nil {
   315  		pmain.Error = &PackageError{Err: err}
   316  	}
   317  	for _, d := range ldDeps {
   318  		deps = append(deps, d)
   319  	}
   320  	for _, dep := range deps {
   321  		if dep == ptest.ImportPath {
   322  			pmain.Internal.Imports = append(pmain.Internal.Imports, ptest)
   323  		} else {
   324  			p1, err := loadImport(ctx, opts, pre, dep, "", nil, &stk, nil, 0)
   325  			if err != nil && pmain.Error == nil {
   326  				pmain.Error = err
   327  				pmain.Incomplete = true
   328  			}
   329  			pmain.Internal.Imports = append(pmain.Internal.Imports, p1)
   330  		}
   331  	}
   332  	stk.Pop()
   333  
   334  	parallelizablePart := func() {
   335  		allTestImports := make([]*Package, 0, len(pmain.Internal.Imports)+len(imports)+len(ximports))
   336  		allTestImports = append(allTestImports, pmain.Internal.Imports...)
   337  		allTestImports = append(allTestImports, imports...)
   338  		allTestImports = append(allTestImports, ximports...)
   339  		setToolFlags(allTestImports...)
   340  
   341  		// Do initial scan for metadata needed for writing _testmain.go
   342  		// Use that metadata to update the list of imports for package main.
   343  		// The list of imports is used by recompileForTest and by the loop
   344  		// afterward that gathers t.Cover information.
   345  		t, err := loadTestFuncs(p)
   346  		if err != nil && pmain.Error == nil {
   347  			pmain.setLoadPackageDataError(err, p.ImportPath, &stk, nil)
   348  		}
   349  		t.Cover = cover
   350  		if len(ptest.GoFiles)+len(ptest.CgoFiles) > 0 {
   351  			pmain.Internal.Imports = append(pmain.Internal.Imports, ptest)
   352  			pmain.Imports = append(pmain.Imports, ptest.ImportPath)
   353  			t.ImportTest = true
   354  		}
   355  		if pxtest != nil {
   356  			pmain.Internal.Imports = append(pmain.Internal.Imports, pxtest)
   357  			pmain.Imports = append(pmain.Imports, pxtest.ImportPath)
   358  			t.ImportXtest = true
   359  		}
   360  
   361  		// Sort and dedup pmain.Imports.
   362  		// Only matters for go list -test output.
   363  		sort.Strings(pmain.Imports)
   364  		w := 0
   365  		for _, path := range pmain.Imports {
   366  			if w == 0 || path != pmain.Imports[w-1] {
   367  				pmain.Imports[w] = path
   368  				w++
   369  			}
   370  		}
   371  		pmain.Imports = pmain.Imports[:w]
   372  		pmain.Internal.RawImports = str.StringList(pmain.Imports)
   373  
   374  		// Replace pmain's transitive dependencies with test copies, as necessary.
   375  		cycleErr := recompileForTest(pmain, p, ptest, pxtest)
   376  		if cycleErr != nil {
   377  			ptest.Error = cycleErr
   378  			ptest.Incomplete = true
   379  		}
   380  
   381  		if cover != nil {
   382  			// Here ptest needs to inherit the proper coverage mode (since
   383  			// it contains p's Go files), whereas pmain contains only
   384  			// test harness code (don't want to instrument it, and
   385  			// we don't want coverage hooks in the pkg init).
   386  			ptest.Internal.Cover.Mode = p.Internal.Cover.Mode
   387  			pmain.Internal.Cover.Mode = "testmain"
   388  
   389  			// Should we apply coverage analysis locally, only for this
   390  			// package and only for this test? Yes, if -cover is on but
   391  			// -coverpkg has not specified a list of packages for global
   392  			// coverage.
   393  			if cover.Local {
   394  				ptest.Internal.Cover.Mode = cover.Mode
   395  			}
   396  		}
   397  
   398  		data, err := formatTestmain(t)
   399  		if err != nil && pmain.Error == nil {
   400  			pmain.Error = &PackageError{Err: err}
   401  			pmain.Incomplete = true
   402  		}
   403  		// Set TestmainGo even if it is empty: the presence of a TestmainGo
   404  		// indicates that this package is, in fact, a test main.
   405  		pmain.Internal.TestmainGo = &data
   406  	}
   407  
   408  	if done != nil {
   409  		go func() {
   410  			parallelizablePart()
   411  			done()
   412  		}()
   413  	} else {
   414  		parallelizablePart()
   415  	}
   416  
   417  	return pmain, ptest, pxtest
   418  }
   419  
   420  // recompileForTest copies and replaces certain packages in pmain's dependency
   421  // graph. This is necessary for two reasons. First, if ptest is different than
   422  // preal, packages that import the package under test should get ptest instead
   423  // of preal. This is particularly important if pxtest depends on functionality
   424  // exposed in test sources in ptest. Second, if there is a main package
   425  // (other than pmain) anywhere, we need to set p.Internal.ForceLibrary and
   426  // clear p.Internal.BuildInfo in the test copy to prevent link conflicts.
   427  // This may happen if both -coverpkg and the command line patterns include
   428  // multiple main packages.
   429  func recompileForTest(pmain, preal, ptest, pxtest *Package) *PackageError {
   430  	// The "test copy" of preal is ptest.
   431  	// For each package that depends on preal, make a "test copy"
   432  	// that depends on ptest. And so on, up the dependency tree.
   433  	testCopy := map[*Package]*Package{preal: ptest}
   434  	for _, p := range PackageList([]*Package{pmain}) {
   435  		if p == preal {
   436  			continue
   437  		}
   438  		// Copy on write.
   439  		didSplit := p == pmain || p == pxtest || p == ptest
   440  		split := func() {
   441  			if didSplit {
   442  				return
   443  			}
   444  			didSplit = true
   445  			if testCopy[p] != nil {
   446  				panic("recompileForTest loop")
   447  			}
   448  			p1 := new(Package)
   449  			testCopy[p] = p1
   450  			*p1 = *p
   451  			p1.ForTest = preal.ImportPath
   452  			p1.Internal.Imports = make([]*Package, len(p.Internal.Imports))
   453  			copy(p1.Internal.Imports, p.Internal.Imports)
   454  			p1.Imports = make([]string, len(p.Imports))
   455  			copy(p1.Imports, p.Imports)
   456  			p = p1
   457  			p.Target = ""
   458  			p.Internal.BuildInfo = nil
   459  			p.Internal.ForceLibrary = true
   460  			p.Internal.PGOProfile = preal.Internal.PGOProfile
   461  		}
   462  
   463  		// Update p.Internal.Imports to use test copies.
   464  		for i, imp := range p.Internal.Imports {
   465  			if p1 := testCopy[imp]; p1 != nil && p1 != imp {
   466  				split()
   467  
   468  				// If the test dependencies cause a cycle with pmain, this is
   469  				// where it is introduced.
   470  				// (There are no cycles in the graph until this assignment occurs.)
   471  				p.Internal.Imports[i] = p1
   472  			}
   473  		}
   474  
   475  		// Force main packages the test imports to be built as libraries.
   476  		// Normal imports of main packages are forbidden by the package loader,
   477  		// but this can still happen if -coverpkg patterns include main packages:
   478  		// covered packages are imported by pmain. Linking multiple packages
   479  		// compiled with '-p main' causes duplicate symbol errors.
   480  		// See golang.org/issue/30907, golang.org/issue/34114.
   481  		if p.Name == "main" && p != pmain && p != ptest {
   482  			split()
   483  		}
   484  		// Split and attach PGO information to test dependencies if preal
   485  		// is built with PGO.
   486  		if preal.Internal.PGOProfile != "" && p.Internal.PGOProfile == "" {
   487  			split()
   488  		}
   489  	}
   490  
   491  	// Do search to find cycle.
   492  	// importerOf maps each import path to its importer nearest to p.
   493  	importerOf := map[*Package]*Package{}
   494  	for _, p := range ptest.Internal.Imports {
   495  		importerOf[p] = nil
   496  	}
   497  
   498  	// q is a breadth-first queue of packages to search for target.
   499  	// Every package added to q has a corresponding entry in pathTo.
   500  	//
   501  	// We search breadth-first for two reasons:
   502  	//
   503  	// 	1. We want to report the shortest cycle.
   504  	//
   505  	// 	2. If p contains multiple cycles, the first cycle we encounter might not
   506  	// 	   contain target. To ensure termination, we have to break all cycles
   507  	// 	   other than the first.
   508  	q := slices.Clip(ptest.Internal.Imports)
   509  	for len(q) > 0 {
   510  		p := q[0]
   511  		q = q[1:]
   512  		if p == ptest {
   513  			// The stack is supposed to be in the order x imports y imports z.
   514  			// We collect in the reverse order: z is imported by y is imported
   515  			// by x, and then we reverse it.
   516  			var stk ImportStack
   517  			for p != nil {
   518  				importer, ok := importerOf[p]
   519  				if importer == nil && ok { // we set importerOf[p] == nil for the initial set of packages p that are imports of ptest
   520  					importer = ptest
   521  				}
   522  				stk = append(stk, ImportInfo{
   523  					Pkg: p.ImportPath,
   524  					Pos: extractFirstImport(importer.Internal.Build.ImportPos[p.ImportPath]),
   525  				})
   526  				p = importerOf[p]
   527  			}
   528  			// complete the cycle: we set importer[p] = nil to break the cycle
   529  			// in importerOf, it's an implicit importerOf[p] == pTest. Add it
   530  			// back here since we reached nil in the loop above to demonstrate
   531  			// the cycle as (for example) package p imports package q imports package r
   532  			// imports package p.
   533  			stk = append(stk, ImportInfo{
   534  				Pkg: ptest.ImportPath,
   535  			})
   536  			slices.Reverse(stk)
   537  			return &PackageError{
   538  				ImportStack:   stk,
   539  				Err:           errors.New("import cycle not allowed in test"),
   540  				IsImportCycle: true,
   541  			}
   542  		}
   543  		for _, dep := range p.Internal.Imports {
   544  			if _, ok := importerOf[dep]; !ok {
   545  				importerOf[dep] = p
   546  				q = append(q, dep)
   547  			}
   548  		}
   549  	}
   550  
   551  	return nil
   552  }
   553  
   554  // isTestFunc tells whether fn has the type of a testing function. arg
   555  // specifies the parameter type we look for: B, F, M or T.
   556  func isTestFunc(fn *ast.FuncDecl, arg string) bool {
   557  	if fn.Type.Results != nil && len(fn.Type.Results.List) > 0 ||
   558  		fn.Type.Params.List == nil ||
   559  		len(fn.Type.Params.List) != 1 ||
   560  		len(fn.Type.Params.List[0].Names) > 1 {
   561  		return false
   562  	}
   563  	ptr, ok := fn.Type.Params.List[0].Type.(*ast.StarExpr)
   564  	if !ok {
   565  		return false
   566  	}
   567  	// We can't easily check that the type is *testing.M
   568  	// because we don't know how testing has been imported,
   569  	// but at least check that it's *M or *something.M.
   570  	// Same applies for B, F and T.
   571  	if name, ok := ptr.X.(*ast.Ident); ok && name.Name == arg {
   572  		return true
   573  	}
   574  	if sel, ok := ptr.X.(*ast.SelectorExpr); ok && sel.Sel.Name == arg {
   575  		return true
   576  	}
   577  	return false
   578  }
   579  
   580  // isTest tells whether name looks like a test (or benchmark, according to prefix).
   581  // It is a Test (say) if there is a character after Test that is not a lower-case letter.
   582  // We don't want TesticularCancer.
   583  func isTest(name, prefix string) bool {
   584  	if !strings.HasPrefix(name, prefix) {
   585  		return false
   586  	}
   587  	if len(name) == len(prefix) { // "Test" is ok
   588  		return true
   589  	}
   590  	rune, _ := utf8.DecodeRuneInString(name[len(prefix):])
   591  	return !unicode.IsLower(rune)
   592  }
   593  
   594  // loadTestFuncs returns the testFuncs describing the tests that will be run.
   595  // The returned testFuncs is always non-nil, even if an error occurred while
   596  // processing test files.
   597  func loadTestFuncs(ptest *Package) (*testFuncs, error) {
   598  	t := &testFuncs{
   599  		Package: ptest,
   600  	}
   601  	var err error
   602  	for _, file := range ptest.TestGoFiles {
   603  		if lerr := t.load(filepath.Join(ptest.Dir, file), "_test", &t.ImportTest, &t.NeedTest); lerr != nil && err == nil {
   604  			err = lerr
   605  		}
   606  	}
   607  	for _, file := range ptest.XTestGoFiles {
   608  		if lerr := t.load(filepath.Join(ptest.Dir, file), "_xtest", &t.ImportXtest, &t.NeedXtest); lerr != nil && err == nil {
   609  			err = lerr
   610  		}
   611  	}
   612  	return t, err
   613  }
   614  
   615  // formatTestmain returns the content of the _testmain.go file for t.
   616  func formatTestmain(t *testFuncs) ([]byte, error) {
   617  	var buf bytes.Buffer
   618  	tmpl := testmainTmpl
   619  	if err := tmpl.Execute(&buf, t); err != nil {
   620  		return nil, err
   621  	}
   622  	return buf.Bytes(), nil
   623  }
   624  
   625  type testFuncs struct {
   626  	Tests       []testFunc
   627  	Benchmarks  []testFunc
   628  	FuzzTargets []testFunc
   629  	Examples    []testFunc
   630  	TestMain    *testFunc
   631  	Package     *Package
   632  	ImportTest  bool
   633  	NeedTest    bool
   634  	ImportXtest bool
   635  	NeedXtest   bool
   636  	Cover       *TestCover
   637  }
   638  
   639  // ImportPath returns the import path of the package being tested, if it is within GOPATH.
   640  // This is printed by the testing package when running benchmarks.
   641  func (t *testFuncs) ImportPath() string {
   642  	pkg := t.Package.ImportPath
   643  	if strings.HasPrefix(pkg, "_/") {
   644  		return ""
   645  	}
   646  	if pkg == "command-line-arguments" {
   647  		return ""
   648  	}
   649  	return pkg
   650  }
   651  
   652  // Covered returns a string describing which packages are being tested for coverage.
   653  // If the covered package is the same as the tested package, it returns the empty string.
   654  // Otherwise it is a comma-separated human-readable list of packages beginning with
   655  // " in", ready for use in the coverage message.
   656  func (t *testFuncs) Covered() string {
   657  	if t.Cover == nil || t.Cover.Paths == nil {
   658  		return ""
   659  	}
   660  	return " in " + strings.Join(t.Cover.Paths, ", ")
   661  }
   662  
   663  func (t *testFuncs) CoverSelectedPackages() string {
   664  	if t.Cover == nil || t.Cover.Paths == nil {
   665  		return `[]string{"` + t.Package.ImportPath + `"}`
   666  	}
   667  	var sb strings.Builder
   668  	fmt.Fprintf(&sb, "[]string{")
   669  	for k, p := range t.Cover.Pkgs {
   670  		if k != 0 {
   671  			sb.WriteString(", ")
   672  		}
   673  		fmt.Fprintf(&sb, `"%s"`, p.ImportPath)
   674  	}
   675  	sb.WriteString("}")
   676  	return sb.String()
   677  }
   678  
   679  // Tested returns the name of the package being tested.
   680  func (t *testFuncs) Tested() string {
   681  	return t.Package.Name
   682  }
   683  
   684  type testFunc struct {
   685  	Package   string // imported package name (_test or _xtest)
   686  	Name      string // function name
   687  	Output    string // output, for examples
   688  	Unordered bool   // output is allowed to be unordered.
   689  }
   690  
   691  var testFileSet = token.NewFileSet()
   692  
   693  func (t *testFuncs) load(filename, pkg string, doImport, seen *bool) error {
   694  	// Pass in the overlaid source if we have an overlay for this file.
   695  	src, err := fsys.Open(filename)
   696  	if err != nil {
   697  		return err
   698  	}
   699  	defer src.Close()
   700  	f, err := parser.ParseFile(testFileSet, filename, src, parser.ParseComments|parser.SkipObjectResolution)
   701  	if err != nil {
   702  		return err
   703  	}
   704  	for _, d := range f.Decls {
   705  		n, ok := d.(*ast.FuncDecl)
   706  		if !ok {
   707  			continue
   708  		}
   709  		if n.Recv != nil {
   710  			continue
   711  		}
   712  		name := n.Name.String()
   713  		switch {
   714  		case name == "TestMain":
   715  			if isTestFunc(n, "T") {
   716  				t.Tests = append(t.Tests, testFunc{pkg, name, "", false})
   717  				*doImport, *seen = true, true
   718  				continue
   719  			}
   720  			err := checkTestFunc(n, "M")
   721  			if err != nil {
   722  				return err
   723  			}
   724  			if t.TestMain != nil {
   725  				return errors.New("multiple definitions of TestMain")
   726  			}
   727  			t.TestMain = &testFunc{pkg, name, "", false}
   728  			*doImport, *seen = true, true
   729  		case isTest(name, "Test"):
   730  			err := checkTestFunc(n, "T")
   731  			if err != nil {
   732  				return err
   733  			}
   734  			t.Tests = append(t.Tests, testFunc{pkg, name, "", false})
   735  			*doImport, *seen = true, true
   736  		case isTest(name, "Benchmark"):
   737  			err := checkTestFunc(n, "B")
   738  			if err != nil {
   739  				return err
   740  			}
   741  			t.Benchmarks = append(t.Benchmarks, testFunc{pkg, name, "", false})
   742  			*doImport, *seen = true, true
   743  		case isTest(name, "Fuzz"):
   744  			err := checkTestFunc(n, "F")
   745  			if err != nil {
   746  				return err
   747  			}
   748  			t.FuzzTargets = append(t.FuzzTargets, testFunc{pkg, name, "", false})
   749  			*doImport, *seen = true, true
   750  		}
   751  	}
   752  	ex := doc.Examples(f)
   753  	sort.Slice(ex, func(i, j int) bool { return ex[i].Order < ex[j].Order })
   754  	for _, e := range ex {
   755  		*doImport = true // import test file whether executed or not
   756  		if e.Output == "" && !e.EmptyOutput {
   757  			// Don't run examples with no output.
   758  			continue
   759  		}
   760  		t.Examples = append(t.Examples, testFunc{pkg, "Example" + e.Name, e.Output, e.Unordered})
   761  		*seen = true
   762  	}
   763  	return nil
   764  }
   765  
   766  func checkTestFunc(fn *ast.FuncDecl, arg string) error {
   767  	var why string
   768  	if !isTestFunc(fn, arg) {
   769  		why = fmt.Sprintf("must be: func %s(%s *testing.%s)", fn.Name.String(), strings.ToLower(arg), arg)
   770  	}
   771  	if fn.Type.TypeParams.NumFields() > 0 {
   772  		why = "test functions cannot have type parameters"
   773  	}
   774  	if why != "" {
   775  		pos := testFileSet.Position(fn.Pos())
   776  		return fmt.Errorf("%s: wrong signature for %s, %s", pos, fn.Name.String(), why)
   777  	}
   778  	return nil
   779  }
   780  
   781  var testmainTmpl = lazytemplate.New("main", `
   782  // Code generated by 'go test'. DO NOT EDIT.
   783  
   784  package main
   785  
   786  import (
   787  	"os"
   788  {{if .TestMain}}
   789  	"reflect"
   790  {{end}}
   791  	"testing"
   792  	"testing/internal/testdeps"
   793  {{if .Cover}}
   794  	"internal/coverage/cfile"
   795  {{end}}
   796  
   797  {{if .ImportTest}}
   798  	{{if .NeedTest}}_test{{else}}_{{end}} {{.Package.ImportPath | printf "%q"}}
   799  {{end}}
   800  {{if .ImportXtest}}
   801  	{{if .NeedXtest}}_xtest{{else}}_{{end}} {{.Package.ImportPath | printf "%s_test" | printf "%q"}}
   802  {{end}}
   803  )
   804  
   805  var tests = []testing.InternalTest{
   806  {{range .Tests}}
   807  	{"{{.Name}}", {{.Package}}.{{.Name}}},
   808  {{end}}
   809  }
   810  
   811  var benchmarks = []testing.InternalBenchmark{
   812  {{range .Benchmarks}}
   813  	{"{{.Name}}", {{.Package}}.{{.Name}}},
   814  {{end}}
   815  }
   816  
   817  var fuzzTargets = []testing.InternalFuzzTarget{
   818  {{range .FuzzTargets}}
   819  	{"{{.Name}}", {{.Package}}.{{.Name}}},
   820  {{end}}
   821  }
   822  
   823  var examples = []testing.InternalExample{
   824  {{range .Examples}}
   825  	{"{{.Name}}", {{.Package}}.{{.Name}}, {{.Output | printf "%q"}}, {{.Unordered}}},
   826  {{end}}
   827  }
   828  
   829  func init() {
   830  {{if .Cover}}
   831  	testdeps.CoverMode = {{printf "%q" .Cover.Mode}}
   832  	testdeps.Covered = {{printf "%q" .Covered}}
   833  	testdeps.CoverSelectedPackages = {{printf "%s" .CoverSelectedPackages}}
   834  	testdeps.CoverSnapshotFunc = cfile.Snapshot
   835  	testdeps.CoverProcessTestDirFunc = cfile.ProcessCoverTestDir
   836  	testdeps.CoverMarkProfileEmittedFunc = cfile.MarkProfileEmitted
   837  
   838  {{end}}
   839  	testdeps.ImportPath = {{.ImportPath | printf "%q"}}
   840  }
   841  
   842  func main() {
   843  	m := testing.MainStart(testdeps.TestDeps{}, tests, benchmarks, fuzzTargets, examples)
   844  {{with .TestMain}}
   845  	{{.Package}}.{{.Name}}(m)
   846  	os.Exit(int(reflect.ValueOf(m).Elem().FieldByName("exitCode").Int()))
   847  {{else}}
   848  	os.Exit(m.Run())
   849  {{end}}
   850  }
   851  
   852  `)
   853  

View as plain text