1
0
mirror of https://github.com/golang/go synced 2024-11-07 13:46:19 -07:00

go/doc: do not treat methods as test functions

The example code was treating a method starting with Test
as a test function when considering whether to produce
a whole-file example or not. As a method can never be
a test function, this isn't correct.

Change-Id: Idd8ec9eaf0904af076e941d7fe7d967f6b7eef78
Reviewed-on: https://go-review.googlesource.com/125257
Reviewed-by: Daniel Martí <mvdan@mvdan.cc>
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
Reviewed-by: Andrew Bonventre <andybons@golang.org>
Run-TryBot: Daniel Martí <mvdan@mvdan.cc>
TryBot-Result: Gobot Gobot <gobot@golang.org>
This commit is contained in:
Roger Peppe 2018-07-20 11:31:39 +01:00 committed by Andrew Bonventre
parent 5332b5e75a
commit 1a5350e123
2 changed files with 73 additions and 11 deletions

View File

@ -56,7 +56,7 @@ func Examples(files ...*ast.File) []*Example {
continue
}
f, ok := decl.(*ast.FuncDecl)
if !ok {
if !ok || f.Recv != nil {
continue
}
numDecl++

View File

@ -6,6 +6,7 @@ package doc_test
import (
"bytes"
"go/ast"
"go/doc"
"go/format"
"go/parser"
@ -280,16 +281,7 @@ func TestExamples(t *testing.T) {
t.Errorf("got Name == %q, want %q", e.Name, c.Name)
}
if w := c.Play; w != "" {
var g string // hah
if e.Play == nil {
g = "<nil>"
} else {
var buf bytes.Buffer
if err := format.Node(&buf, fset, e.Play); err != nil {
t.Fatal(err)
}
g = buf.String()
}
g := formatFile(t, fset, e.Play)
if g != w {
t.Errorf("%s: got Play == %q, want %q", c.Name, g, w)
}
@ -299,3 +291,73 @@ func TestExamples(t *testing.T) {
}
}
}
const exampleWholeFile = `package foo_test
type X int
func (X) Foo() {
}
func (X) TestBlah() {
}
func (X) BenchmarkFoo() {
}
func Example() {
fmt.Println("Hello, world!")
// Output: Hello, world!
}
`
const exampleWholeFileOutput = `package main
type X int
func (X) Foo() {
}
func (X) TestBlah() {
}
func (X) BenchmarkFoo() {
}
func main() {
fmt.Println("Hello, world!")
}
`
func TestExamplesWholeFile(t *testing.T) {
fset := token.NewFileSet()
file, err := parser.ParseFile(fset, "test.go", strings.NewReader(exampleWholeFile), parser.ParseComments)
if err != nil {
t.Fatal(err)
}
es := doc.Examples(file)
if len(es) != 1 {
t.Fatalf("wrong number of examples; got %d want 1", len(es))
}
e := es[0]
if e.Name != "" {
t.Errorf("got Name == %q, want %q", e.Name, "")
}
if g, w := formatFile(t, fset, e.Play), exampleWholeFileOutput; g != w {
t.Errorf("got Play == %q, want %q", g, w)
}
if g, w := e.Output, "Hello, world!\n"; g != w {
t.Errorf("got Output == %q, want %q", g, w)
}
}
func formatFile(t *testing.T, fset *token.FileSet, n *ast.File) string {
if n == nil {
return "<nil>"
}
var buf bytes.Buffer
if err := format.Node(&buf, fset, n); err != nil {
t.Fatal(err)
}
return buf.String()
}