Support examples as tests

go test supports running examples as tests and verifying their
output, add support for running them to gotestmain.

Change-Id: If51abc64467d4701195cefc6db513f4d008794b5
This commit is contained in:
Colin Cross 2019-02-15 12:49:11 -08:00
parent 33cfa1c98a
commit 463eab7950

View file

@ -19,6 +19,7 @@ import (
"flag"
"fmt"
"go/ast"
"go/doc"
"go/parser"
"go/token"
"io/ioutil"
@ -39,13 +40,14 @@ var (
type data struct {
Package string
Tests []string
Examples []*doc.Example
HasMain bool
MainStartTakesInterface bool
}
func findTests(srcs []string) (tests []string, hasMain bool) {
func findTests(srcs []string) (tests []string, examples []*doc.Example, hasMain bool) {
for _, src := range srcs {
f, err := parser.ParseFile(token.NewFileSet(), src, nil, 0)
f, err := parser.ParseFile(token.NewFileSet(), src, nil, parser.ParseComments)
if err != nil {
panic(err)
}
@ -59,6 +61,8 @@ func findTests(srcs []string) (tests []string, hasMain bool) {
tests = append(tests, obj.Name)
}
}
examples = append(examples, doc.Examples(f)...)
}
sort.Strings(tests)
return
@ -81,11 +85,12 @@ func main() {
buf := &bytes.Buffer{}
tests, hasMain := findTests(flag.Args())
tests, examples, hasMain := findTests(flag.Args())
d := data{
Package: *pkg,
Tests: tests,
Examples: examples,
HasMain: hasMain,
MainStartTakesInterface: mainStartTakesInterface(),
}
@ -121,6 +126,14 @@ var t = []testing.InternalTest{
{{end}}
}
var e = []testing.InternalExample{
{{range .Examples}}
{{if or .Output .EmptyOutput}}
{"{{.Name}}", pkg.Example{{.Name}}, {{.Output | printf "%q" }}, {{.Unordered}}},
{{end}}
{{end}}
}
var matchPat string
var matchRe *regexp.Regexp
@ -170,9 +183,9 @@ func (matchString) StopTestLog() error {
func main() {
{{if .MainStartTakesInterface}}
m := testing.MainStart(matchString{}, t, nil, nil)
m := testing.MainStart(matchString{}, t, nil, e)
{{else}}
m := testing.MainStart(MatchString, t, nil, nil)
m := testing.MainStart(MatchString, t, nil, e)
{{end}}
{{if .HasMain}}
pkg.TestMain(m)