github.com/golangci/go-tools@v0.0.0-20190318060251-af6baa5dc196/ssa/testmain.go (about)

     1  // Copyright 2013 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 ssa
     6  
     7  // CreateTestMainPackage synthesizes a main package that runs all the
     8  // tests of the supplied packages.
     9  // It is closely coupled to $GOROOT/src/cmd/go/test.go and $GOROOT/src/testing.
    10  //
    11  // TODO(adonovan): this file no longer needs to live in the ssa package.
    12  // Move it to ssautil.
    13  
    14  import (
    15  	"bytes"
    16  	"fmt"
    17  	"go/ast"
    18  	"go/parser"
    19  	"go/types"
    20  	"log"
    21  	"os"
    22  	"strings"
    23  	"text/template"
    24  )
    25  
    26  // FindTests returns the Test, Benchmark, and Example functions
    27  // (as defined by "go test") defined in the specified package,
    28  // and its TestMain function, if any.
    29  func FindTests(pkg *Package) (tests, benchmarks, examples []*Function, main *Function) {
    30  	prog := pkg.Prog
    31  
    32  	// The first two of these may be nil: if the program doesn't import "testing",
    33  	// it can't contain any tests, but it may yet contain Examples.
    34  	var testSig *types.Signature                              // func(*testing.T)
    35  	var benchmarkSig *types.Signature                         // func(*testing.B)
    36  	var exampleSig = types.NewSignature(nil, nil, nil, false) // func()
    37  
    38  	// Obtain the types from the parameters of testing.MainStart.
    39  	if testingPkg := prog.ImportedPackage("testing"); testingPkg != nil {
    40  		mainStart := testingPkg.Func("MainStart")
    41  		params := mainStart.Signature.Params()
    42  		testSig = funcField(params.At(1).Type())
    43  		benchmarkSig = funcField(params.At(2).Type())
    44  
    45  		// Does the package define this function?
    46  		//   func TestMain(*testing.M)
    47  		if f := pkg.Func("TestMain"); f != nil {
    48  			sig := f.Type().(*types.Signature)
    49  			starM := mainStart.Signature.Results().At(0).Type() // *testing.M
    50  			if sig.Results().Len() == 0 &&
    51  				sig.Params().Len() == 1 &&
    52  				types.Identical(sig.Params().At(0).Type(), starM) {
    53  				main = f
    54  			}
    55  		}
    56  	}
    57  
    58  	// TODO(adonovan): use a stable order, e.g. lexical.
    59  	for _, mem := range pkg.Members {
    60  		if f, ok := mem.(*Function); ok &&
    61  			ast.IsExported(f.Name()) &&
    62  			strings.HasSuffix(prog.Fset.Position(f.Pos()).Filename, "_test.go") {
    63  
    64  			switch {
    65  			case testSig != nil && isTestSig(f, "Test", testSig):
    66  				tests = append(tests, f)
    67  			case benchmarkSig != nil && isTestSig(f, "Benchmark", benchmarkSig):
    68  				benchmarks = append(benchmarks, f)
    69  			case isTestSig(f, "Example", exampleSig):
    70  				examples = append(examples, f)
    71  			default:
    72  				continue
    73  			}
    74  		}
    75  	}
    76  	return
    77  }
    78  
    79  // Like isTest, but checks the signature too.
    80  func isTestSig(f *Function, prefix string, sig *types.Signature) bool {
    81  	return isTest(f.Name(), prefix) && types.Identical(f.Signature, sig)
    82  }
    83  
    84  // Given the type of one of the three slice parameters of testing.Main,
    85  // returns the function type.
    86  func funcField(slice types.Type) *types.Signature {
    87  	return slice.(*types.Slice).Elem().Underlying().(*types.Struct).Field(1).Type().(*types.Signature)
    88  }
    89  
    90  // isTest tells whether name looks like a test (or benchmark, according to prefix).
    91  // It is a Test (say) if there is a character after Test that is not a lower-case letter.
    92  // We don't want TesticularCancer.
    93  // Plundered from $GOROOT/src/cmd/go/test.go
    94  func isTest(name, prefix string) bool {
    95  	if !strings.HasPrefix(name, prefix) {
    96  		return false
    97  	}
    98  	if len(name) == len(prefix) { // "Test" is ok
    99  		return true
   100  	}
   101  	return ast.IsExported(name[len(prefix):])
   102  }
   103  
   104  // CreateTestMainPackage creates and returns a synthetic "testmain"
   105  // package for the specified package if it defines tests, benchmarks or
   106  // executable examples, or nil otherwise.  The new package is named
   107  // "main" and provides a function named "main" that runs the tests,
   108  // similar to the one that would be created by the 'go test' tool.
   109  //
   110  // Subsequent calls to prog.AllPackages include the new package.
   111  // The package pkg must belong to the program prog.
   112  func (prog *Program) CreateTestMainPackage(pkg *Package) *Package {
   113  	if pkg.Prog != prog {
   114  		log.Fatal("Package does not belong to Program")
   115  	}
   116  
   117  	// Template data
   118  	var data struct {
   119  		Pkg                         *Package
   120  		Tests, Benchmarks, Examples []*Function
   121  		Main                        *Function
   122  		Go18                        bool
   123  	}
   124  	data.Pkg = pkg
   125  
   126  	// Enumerate tests.
   127  	data.Tests, data.Benchmarks, data.Examples, data.Main = FindTests(pkg)
   128  	if data.Main == nil &&
   129  		data.Tests == nil && data.Benchmarks == nil && data.Examples == nil {
   130  		return nil
   131  	}
   132  
   133  	// Synthesize source for testmain package.
   134  	path := pkg.Pkg.Path() + "$testmain"
   135  	tmpl := testmainTmpl
   136  	if testingPkg := prog.ImportedPackage("testing"); testingPkg != nil {
   137  		// In Go 1.8, testing.MainStart's first argument is an interface, not a func.
   138  		data.Go18 = types.IsInterface(testingPkg.Func("MainStart").Signature.Params().At(0).Type())
   139  	} else {
   140  		// The program does not import "testing", but FindTests
   141  		// returned non-nil, which must mean there were Examples
   142  		// but no Test, Benchmark, or TestMain functions.
   143  
   144  		// We'll simply call them from testmain.main; this will
   145  		// ensure they don't panic, but will not check any
   146  		// "Output:" comments.
   147  		// (We should not execute an Example that has no
   148  		// "Output:" comment, but it's impossible to tell here.)
   149  		tmpl = examplesOnlyTmpl
   150  	}
   151  	var buf bytes.Buffer
   152  	if err := tmpl.Execute(&buf, data); err != nil {
   153  		log.Fatalf("internal error expanding template for %s: %v", path, err)
   154  	}
   155  	if false { // debugging
   156  		fmt.Fprintln(os.Stderr, buf.String())
   157  	}
   158  
   159  	// Parse and type-check the testmain package.
   160  	f, err := parser.ParseFile(prog.Fset, path+".go", &buf, parser.Mode(0))
   161  	if err != nil {
   162  		log.Fatalf("internal error parsing %s: %v", path, err)
   163  	}
   164  	conf := types.Config{
   165  		DisableUnusedImportCheck: true,
   166  		Importer:                 importer{pkg},
   167  	}
   168  	files := []*ast.File{f}
   169  	info := &types.Info{
   170  		Types:      make(map[ast.Expr]types.TypeAndValue),
   171  		Defs:       make(map[*ast.Ident]types.Object),
   172  		Uses:       make(map[*ast.Ident]types.Object),
   173  		Implicits:  make(map[ast.Node]types.Object),
   174  		Scopes:     make(map[ast.Node]*types.Scope),
   175  		Selections: make(map[*ast.SelectorExpr]*types.Selection),
   176  	}
   177  	testmainPkg, err := conf.Check(path, prog.Fset, files, info)
   178  	if err != nil {
   179  		log.Fatalf("internal error type-checking %s: %v", path, err)
   180  	}
   181  
   182  	// Create and build SSA code.
   183  	testmain := prog.CreatePackage(testmainPkg, files, info, false)
   184  	testmain.SetDebugMode(false)
   185  	testmain.Build()
   186  	testmain.Func("main").Synthetic = "test main function"
   187  	testmain.Func("init").Synthetic = "package initializer"
   188  	return testmain
   189  }
   190  
   191  // An implementation of types.Importer for an already loaded SSA program.
   192  type importer struct {
   193  	pkg *Package // package under test; may be non-importable
   194  }
   195  
   196  func (imp importer) Import(path string) (*types.Package, error) {
   197  	if p := imp.pkg.Prog.ImportedPackage(path); p != nil {
   198  		return p.Pkg, nil
   199  	}
   200  	if path == imp.pkg.Pkg.Path() {
   201  		return imp.pkg.Pkg, nil
   202  	}
   203  	return nil, fmt.Errorf("not found") // can't happen
   204  }
   205  
   206  var testmainTmpl = template.Must(template.New("testmain").Parse(`
   207  package main
   208  
   209  import "io"
   210  import "os"
   211  import "testing"
   212  import p {{printf "%q" .Pkg.Pkg.Path}}
   213  
   214  {{if .Go18}}
   215  type deps struct{}
   216  
   217  func (deps) ImportPath() string { return "" }
   218  func (deps) MatchString(pat, str string) (bool, error) { return true, nil }
   219  func (deps) StartCPUProfile(io.Writer) error { return nil }
   220  func (deps) StartTestLog(io.Writer) {}
   221  func (deps) StopCPUProfile() {}
   222  func (deps) StopTestLog() error { return nil }
   223  func (deps) WriteHeapProfile(io.Writer) error { return nil }
   224  func (deps) WriteProfileTo(string, io.Writer, int) error { return nil }
   225  
   226  var match deps
   227  {{else}}
   228  func match(_, _ string) (bool, error) { return true, nil }
   229  {{end}}
   230  
   231  func main() {
   232  	tests := []testing.InternalTest{
   233  {{range .Tests}}
   234  		{ {{printf "%q" .Name}}, p.{{.Name}} },
   235  {{end}}
   236  	}
   237  	benchmarks := []testing.InternalBenchmark{
   238  {{range .Benchmarks}}
   239  		{ {{printf "%q" .Name}}, p.{{.Name}} },
   240  {{end}}
   241  	}
   242  	examples := []testing.InternalExample{
   243  {{range .Examples}}
   244  		{Name: {{printf "%q" .Name}}, F: p.{{.Name}}},
   245  {{end}}
   246  	}
   247  	m := testing.MainStart(match, tests, benchmarks, examples)
   248  {{with .Main}}
   249  	p.{{.Name}}(m)
   250  {{else}}
   251  	os.Exit(m.Run())
   252  {{end}}
   253  }
   254  
   255  `))
   256  
   257  var examplesOnlyTmpl = template.Must(template.New("examples").Parse(`
   258  package main
   259  
   260  import p {{printf "%q" .Pkg.Pkg.Path}}
   261  
   262  func main() {
   263  {{range .Examples}}
   264  	p.{{.Name}}()
   265  {{end}}
   266  }
   267  `))