Commit 5bd5ed2b authored by Andrew Gerrand's avatar Andrew Gerrand

testing: catch panicking example and report, just like tests

Fixes #4670.

R=rsc
CC=golang-dev
https://golang.org/cl/7148043
parent 07dfd8b1
...@@ -24,8 +24,6 @@ func RunExamples(matchString func(pat, str string) (bool, error), examples []Int ...@@ -24,8 +24,6 @@ func RunExamples(matchString func(pat, str string) (bool, error), examples []Int
var eg InternalExample var eg InternalExample
stdout := os.Stdout
for _, eg = range examples { for _, eg = range examples {
matched, err := matchString(*match, eg.Name) matched, err := matchString(*match, eg.Name)
if err != nil { if err != nil {
...@@ -35,11 +33,21 @@ func RunExamples(matchString func(pat, str string) (bool, error), examples []Int ...@@ -35,11 +33,21 @@ func RunExamples(matchString func(pat, str string) (bool, error), examples []Int
if !matched { if !matched {
continue continue
} }
if !runExample(eg) {
ok = false
}
}
return
}
func runExample(eg InternalExample) (ok bool) {
if *chatty { if *chatty {
fmt.Printf("=== RUN: %s\n", eg.Name) fmt.Printf("=== RUN: %s\n", eg.Name)
} }
// capture stdout // Capture stdout.
stdout := os.Stdout
r, w, err := os.Pipe() r, w, err := os.Pipe()
if err != nil { if err != nil {
fmt.Fprintln(os.Stderr, err) fmt.Fprintln(os.Stderr, err)
...@@ -58,26 +66,33 @@ func RunExamples(matchString func(pat, str string) (bool, error), examples []Int ...@@ -58,26 +66,33 @@ func RunExamples(matchString func(pat, str string) (bool, error), examples []Int
outC <- buf.String() outC <- buf.String()
}() }()
// run example start := time.Now()
t0 := time.Now()
eg.F()
dt := time.Now().Sub(t0)
// close pipe, restore stdout, get output // Clean up in a deferred call so we can recover if the example panics.
defer func() {
d := time.Now().Sub(start)
// Close pipe, restore stdout, get output.
w.Close() w.Close()
os.Stdout = stdout os.Stdout = stdout
out := <-outC out := <-outC
// report any errors var fail string
tstr := fmt.Sprintf("(%.2f seconds)", dt.Seconds()) err := recover()
if g, e := strings.TrimSpace(out), strings.TrimSpace(eg.Output); g != e { if g, e := strings.TrimSpace(out), strings.TrimSpace(eg.Output); g != e && err == nil {
fmt.Printf("--- FAIL: %s %s\ngot:\n%s\nwant:\n%s\n", fail = fmt.Sprintf("got:\n%s\nwant:\n%s\n", g, e)
eg.Name, tstr, g, e) }
ok = false if fail != "" || err != nil {
fmt.Printf("--- FAIL: %s (%v)\n%s", eg.Name, d, fail)
} else if *chatty { } else if *chatty {
fmt.Printf("--- PASS: %s %s\n", eg.Name, tstr) fmt.Printf("--- PASS: %s (%v)\n", eg.Name, d)
} }
if err != nil {
panic(err)
} }
}()
// Run example.
eg.F()
return return
} }
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment