1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
|
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package testing
import (
"bytes"
"fmt"
"io"
"os"
"time"
)
type InternalExample struct {
Name string
F func()
Output string
}
func RunExamples(examples []InternalExample) (ok bool) {
ok = true
stdout, stderr := os.Stdout, os.Stderr
defer func() {
os.Stdout, os.Stderr = stdout, stderr
if e := recover(); e != nil {
if err, ok := e.(os.Error); ok {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
panic(e)
}
}()
for _, eg := range examples {
if *chatty {
fmt.Fprintln(os.Stderr, "=== RUN:", eg.Name)
}
// capture stdout and stderr for testing purposes
r, w, err := os.Pipe()
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
os.Stdout, os.Stderr = w, w
outC := make(chan string)
go func() {
buf := new(bytes.Buffer)
_, err := io.Copy(buf, r)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
outC <- buf.String()
}()
// run example
ns := -time.Nanoseconds()
eg.F()
ns += time.Nanoseconds()
// close pipe, restore stdout/stderr, get output
w.Close()
os.Stdout, os.Stderr = stdout, stderr
out := <-outC
// report any errors
if out != eg.Output {
fmt.Fprintf(
os.Stderr,
"--- FAIL: %s\ngot:\n%s\nwant:\n%s\n",
eg.Name, out, eg.Output,
)
ok = false
} else if *chatty {
tstr := fmt.Sprintf("(%.2f seconds)", float64(ns)/1e9)
fmt.Fprintln(os.Stderr, "--- PASS:", eg.Name, tstr)
}
}
return
}
|