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.
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.
11 // TODO(adonovan): throws this all away now that x/tools/go/packages
12 // provides access to the actual synthetic test main files.
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.
30 // Deprecated: Use golang.org/x/tools/go/packages to access synthetic
32 func FindTests(pkg *Package) (tests, benchmarks, examples []*Function, main *Function) {
35 // The first two of these may be nil: if the program doesn't import "testing",
36 // it can't contain any tests, but it may yet contain Examples.
37 var testSig *types.Signature // func(*testing.T)
38 var benchmarkSig *types.Signature // func(*testing.B)
39 var exampleSig = types.NewSignature(nil, nil, nil, false) // func()
41 // Obtain the types from the parameters of testing.MainStart.
42 if testingPkg := prog.ImportedPackage("testing"); testingPkg != nil {
43 mainStart := testingPkg.Func("MainStart")
44 params := mainStart.Signature.Params()
45 testSig = funcField(params.At(1).Type())
46 benchmarkSig = funcField(params.At(2).Type())
48 // Does the package define this function?
49 // func TestMain(*testing.M)
50 if f := pkg.Func("TestMain"); f != nil {
51 sig := f.Type().(*types.Signature)
52 starM := mainStart.Signature.Results().At(0).Type() // *testing.M
53 if sig.Results().Len() == 0 &&
54 sig.Params().Len() == 1 &&
55 types.Identical(sig.Params().At(0).Type(), starM) {
61 // TODO(adonovan): use a stable order, e.g. lexical.
62 for _, mem := range pkg.Members {
63 if f, ok := mem.(*Function); ok &&
64 ast.IsExported(f.Name()) &&
65 strings.HasSuffix(prog.Fset.Position(f.Pos()).Filename, "_test.go") {
68 case testSig != nil && isTestSig(f, "Test", testSig):
69 tests = append(tests, f)
70 case benchmarkSig != nil && isTestSig(f, "Benchmark", benchmarkSig):
71 benchmarks = append(benchmarks, f)
72 case isTestSig(f, "Example", exampleSig):
73 examples = append(examples, f)
82 // Like isTest, but checks the signature too.
83 func isTestSig(f *Function, prefix string, sig *types.Signature) bool {
84 return isTest(f.Name(), prefix) && types.Identical(f.Signature, sig)
87 // Given the type of one of the three slice parameters of testing.Main,
88 // returns the function type.
89 func funcField(slice types.Type) *types.Signature {
90 return slice.(*types.Slice).Elem().Underlying().(*types.Struct).Field(1).Type().(*types.Signature)
93 // isTest tells whether name looks like a test (or benchmark, according to prefix).
94 // It is a Test (say) if there is a character after Test that is not a lower-case letter.
95 // We don't want TesticularCancer.
96 // Plundered from $GOROOT/src/cmd/go/test.go
97 func isTest(name, prefix string) bool {
98 if !strings.HasPrefix(name, prefix) {
101 if len(name) == len(prefix) { // "Test" is ok
104 return ast.IsExported(name[len(prefix):])
107 // CreateTestMainPackage creates and returns a synthetic "testmain"
108 // package for the specified package if it defines tests, benchmarks or
109 // executable examples, or nil otherwise. The new package is named
110 // "main" and provides a function named "main" that runs the tests,
111 // similar to the one that would be created by the 'go test' tool.
113 // Subsequent calls to prog.AllPackages include the new package.
114 // The package pkg must belong to the program prog.
116 // Deprecated: Use golang.org/x/tools/go/packages to access synthetic
117 // testmain packages.
118 func (prog *Program) CreateTestMainPackage(pkg *Package) *Package {
119 if pkg.Prog != prog {
120 log.Fatal("Package does not belong to Program")
126 Tests, Benchmarks, Examples []*Function
133 data.Tests, data.Benchmarks, data.Examples, data.Main = FindTests(pkg)
134 if data.Main == nil &&
135 data.Tests == nil && data.Benchmarks == nil && data.Examples == nil {
139 // Synthesize source for testmain package.
140 path := pkg.Pkg.Path() + "$testmain"
142 if testingPkg := prog.ImportedPackage("testing"); testingPkg != nil {
143 // In Go 1.8, testing.MainStart's first argument is an interface, not a func.
144 data.Go18 = types.IsInterface(testingPkg.Func("MainStart").Signature.Params().At(0).Type())
146 // The program does not import "testing", but FindTests
147 // returned non-nil, which must mean there were Examples
148 // but no Test, Benchmark, or TestMain functions.
150 // We'll simply call them from testmain.main; this will
151 // ensure they don't panic, but will not check any
152 // "Output:" comments.
153 // (We should not execute an Example that has no
154 // "Output:" comment, but it's impossible to tell here.)
155 tmpl = examplesOnlyTmpl
158 if err := tmpl.Execute(&buf, data); err != nil {
159 log.Fatalf("internal error expanding template for %s: %v", path, err)
161 if false { // debugging
162 fmt.Fprintln(os.Stderr, buf.String())
165 // Parse and type-check the testmain package.
166 f, err := parser.ParseFile(prog.Fset, path+".go", &buf, parser.Mode(0))
168 log.Fatalf("internal error parsing %s: %v", path, err)
170 conf := types.Config{
171 DisableUnusedImportCheck: true,
172 Importer: importer{pkg},
174 files := []*ast.File{f}
176 Types: make(map[ast.Expr]types.TypeAndValue),
177 Defs: make(map[*ast.Ident]types.Object),
178 Uses: make(map[*ast.Ident]types.Object),
179 Implicits: make(map[ast.Node]types.Object),
180 Scopes: make(map[ast.Node]*types.Scope),
181 Selections: make(map[*ast.SelectorExpr]*types.Selection),
183 testmainPkg, err := conf.Check(path, prog.Fset, files, info)
185 log.Fatalf("internal error type-checking %s: %v", path, err)
188 // Create and build SSA code.
189 testmain := prog.CreatePackage(testmainPkg, files, info, false)
190 testmain.SetDebugMode(false)
192 testmain.Func("main").Synthetic = "test main function"
193 testmain.Func("init").Synthetic = "package initializer"
197 // An implementation of types.Importer for an already loaded SSA program.
198 type importer struct {
199 pkg *Package // package under test; may be non-importable
202 func (imp importer) Import(path string) (*types.Package, error) {
203 if p := imp.pkg.Prog.ImportedPackage(path); p != nil {
206 if path == imp.pkg.Pkg.Path() {
207 return imp.pkg.Pkg, nil
209 return nil, fmt.Errorf("not found") // can't happen
212 var testmainTmpl = template.Must(template.New("testmain").Parse(`
218 import p {{printf "%q" .Pkg.Pkg.Path}}
223 func (deps) ImportPath() string { return "" }
224 func (deps) MatchString(pat, str string) (bool, error) { return true, nil }
225 func (deps) SetPanicOnExit0(bool) {}
226 func (deps) StartCPUProfile(io.Writer) error { return nil }
227 func (deps) StartTestLog(io.Writer) {}
228 func (deps) StopCPUProfile() {}
229 func (deps) StopTestLog() error { return nil }
230 func (deps) WriteHeapProfile(io.Writer) error { return nil }
231 func (deps) WriteProfileTo(string, io.Writer, int) error { return nil }
235 func match(_, _ string) (bool, error) { return true, nil }
239 tests := []testing.InternalTest{
241 { {{printf "%q" .Name}}, p.{{.Name}} },
244 benchmarks := []testing.InternalBenchmark{
245 {{range .Benchmarks}}
246 { {{printf "%q" .Name}}, p.{{.Name}} },
249 examples := []testing.InternalExample{
251 {Name: {{printf "%q" .Name}}, F: p.{{.Name}}},
254 m := testing.MainStart(match, tests, benchmarks, examples)
264 var examplesOnlyTmpl = template.Must(template.New("examples").Parse(`
267 import p {{printf "%q" .Pkg.Pkg.Path}}