10
10
// [a-z]) and serves to identify the test routine.
11
11
// These TestXxx routines should be declared within the package they are testing.
13
// Tests and benchmarks may be skipped if not applicable like this:
14
// func TestTimeConsuming(t *testing.T) {
15
// if testing.Short() {
16
// t.Skip("skipping test in short mode.")
13
23
// Functions of the form
14
24
// func BenchmarkXxx(*testing.B)
15
25
// are considered benchmarks, and are executed by the "go test" command when
16
// the -test.bench flag is provided.
26
// the -test.bench flag is provided. Benchmarks are run sequentially.
28
// For a description of the testing flags, see
29
// http://golang.org/cmd/go/#Description_of_testing_flags.
18
31
// A sample benchmark function looks like this:
19
32
// func BenchmarkHello(b *testing.B) {
38
// The benchmark function must run the target code b.N times.
25
39
// The benchmark package will vary b.N until the benchmark function lasts
26
40
// long enough to be timed reliably. The output
27
// testing.BenchmarkHello 10000000 282 ns/op
41
// BenchmarkHello 10000000 282 ns/op
28
42
// means that the loop ran 10000000 times at a speed of 282 ns per loop.
30
44
// If a benchmark needs some expensive setup before running, the timer
32
46
// func BenchmarkBigLen(b *testing.B) {
36
49
// for i := 0; i < b.N; i++ {
41
56
// The package also runs and verifies example code. Example functions may
42
// include a concluding comment that begins with "Output:" and is compared with
43
// the standard output of the function when the tests are run, as in these
44
// examples of an example:
57
// include a concluding line comment that begins with "Output:" and is compared with
58
// the standard output of the function when the tests are run. (The comparison
59
// ignores leading and trailing space.) These are examples of an example:
46
61
// func ExampleHello() {
47
62
// fmt.Println("hello")
98
115
short = flag.Bool("test.short", false, "run smaller test suite to save time")
100
117
// Report as tests are run; default is silent for success.
101
chatty = flag.Bool("test.v", false, "verbose: print additional output")
102
match = flag.String("test.run", "", "regular expression to select tests and examples to run")
103
memProfile = flag.String("test.memprofile", "", "write a memory profile to the named file after execution")
104
memProfileRate = flag.Int("test.memprofilerate", 0, "if >=0, sets runtime.MemProfileRate")
105
cpuProfile = flag.String("test.cpuprofile", "", "write a cpu profile to the named file during execution")
106
timeout = flag.Duration("test.timeout", 0, "if positive, sets an aggregate time limit for all tests")
107
cpuListStr = flag.String("test.cpu", "", "comma-separated list of number of CPUs to use for each test")
108
parallel = flag.Int("test.parallel", runtime.GOMAXPROCS(0), "maximum test parallelism")
118
chatty = flag.Bool("test.v", false, "verbose: print additional output")
119
match = flag.String("test.run", "", "regular expression to select tests and examples to run")
120
memProfile = flag.String("test.memprofile", "", "write a memory profile to the named file after execution")
121
memProfileRate = flag.Int("test.memprofilerate", 0, "if >=0, sets runtime.MemProfileRate")
122
cpuProfile = flag.String("test.cpuprofile", "", "write a cpu profile to the named file during execution")
123
blockProfile = flag.String("test.blockprofile", "", "write a goroutine blocking profile to the named file after execution")
124
blockProfileRate = flag.Int("test.blockprofilerate", 1, "if >= 0, calls runtime.SetBlockProfileRate()")
125
timeout = flag.Duration("test.timeout", 0, "if positive, sets an aggregate time limit for all tests")
126
cpuListStr = flag.String("test.cpu", "", "comma-separated list of number of CPUs to use for each test")
127
parallel = flag.Int("test.parallel", runtime.GOMAXPROCS(0), "maximum test parallelism")
110
129
haveExamples bool // are there examples?
115
134
// common holds the elements common between T and B and
116
135
// captures common methods such as Errorf.
117
136
type common struct {
118
output []byte // Output generated by test or benchmark.
119
failed bool // Test or benchmark has failed.
137
mu sync.RWMutex // guards output and failed
138
output []byte // Output generated by test or benchmark.
139
failed bool // Test or benchmark has failed.
140
skipped bool // Test of benchmark has been skipped.
120
142
start time.Time // Time test or benchmark started
121
143
duration time.Duration
122
144
self interface{} // To be sent on signal channel when done.
131
// decorate inserts the final newline if needed and indentation tabs for formatting.
132
// If addFileLine is true, it also prefixes the string with the file and line of the call site.
133
func decorate(s string, addFileLine bool) string {
135
_, file, line, ok := runtime.Caller(3) // decorate + log + public function.
137
// Truncate file name at last file name separator.
138
if index := strings.LastIndex(file, "/"); index >= 0 {
139
file = file[index+1:]
140
} else if index = strings.LastIndex(file, "\\"); index >= 0 {
141
file = file[index+1:]
153
// Verbose reports whether the -test.v flag is set.
154
func Verbose() bool {
158
// decorate prefixes the string with the file and line of the call site
159
// and inserts the final newline if needed and indentation tabs for formatting.
160
func decorate(s string) string {
161
_, file, line, ok := runtime.Caller(3) // decorate + log + public function.
163
// Truncate file name at last file name separator.
164
if index := strings.LastIndex(file, "/"); index >= 0 {
165
file = file[index+1:]
166
} else if index = strings.LastIndex(file, "\\"); index >= 0 {
167
file = file[index+1:]
147
s = fmt.Sprintf("%s:%d: %s", file, line, s)
149
s = "\t" + s // Every line is indented at least one tab.
151
if n > 0 && s[n-1] != '\n' {
155
for i := 0; i < n-1; i++ { // -1 to avoid final newline
173
buf := new(bytes.Buffer)
174
// Every line is indented at least one tab.
176
fmt.Fprintf(buf, "%s:%d: ", file, line)
177
lines := strings.Split(s, "\n")
178
if l := len(lines); l > 1 && lines[l-1] == "" {
181
for i, line := range lines {
157
183
// Second and subsequent lines are indented an extra tab.
158
return s[0:i+1] + "\t" + decorate(s[i+1:n], false)
184
buf.WriteString("\n\t\t")
186
buf.WriteString(line)
164
192
// T is a type passed to Test functions to manage test state and support formatted test logs.
172
200
// Fail marks the function as having failed but continues execution.
173
func (c *common) Fail() { c.failed = true }
201
func (c *common) Fail() {
175
// Failed returns whether the function has failed.
176
func (c *common) Failed() bool { return c.failed }
207
// Failed reports whether the function has failed.
208
func (c *common) Failed() bool {
178
214
// FailNow marks the function as having failed and stops its execution.
179
215
// Execution will continue at the next test or benchmark.
216
// FailNow must be called from the goroutine running the
217
// test or benchmark function, not from other goroutines
218
// created during the test. Calling FailNow does not stop
219
// those other goroutines.
180
220
func (c *common) FailNow() {
205
245
// log generates the output. It's always at the same stack depth.
206
246
func (c *common) log(s string) {
207
c.output = append(c.output, decorate(s, true)...)
249
c.output = append(c.output, decorate(s)...)
210
// Log formats its arguments using default formatting, analogous to Println(),
211
// and records the text in the error log.
252
// Log formats its arguments using default formatting, analogous to Println,
253
// and records the text in the error log. The text will be printed only if
254
// the test fails or the -test.v flag is set.
212
255
func (c *common) Log(args ...interface{}) { c.log(fmt.Sprintln(args...)) }
214
// Logf formats its arguments according to the format, analogous to Printf(),
215
// and records the text in the error log.
257
// Logf formats its arguments according to the format, analogous to Printf,
258
// and records the text in the error log. The text will be printed only if
259
// the test fails or the -test.v flag is set.
216
260
func (c *common) Logf(format string, args ...interface{}) { c.log(fmt.Sprintf(format, args...)) }
218
// Error is equivalent to Log() followed by Fail().
262
// Error is equivalent to Log followed by Fail.
219
263
func (c *common) Error(args ...interface{}) {
220
264
c.log(fmt.Sprintln(args...))
224
// Errorf is equivalent to Logf() followed by Fail().
268
// Errorf is equivalent to Logf followed by Fail.
225
269
func (c *common) Errorf(format string, args ...interface{}) {
226
270
c.log(fmt.Sprintf(format, args...))
230
// Fatal is equivalent to Log() followed by FailNow().
274
// Fatal is equivalent to Log followed by FailNow.
231
275
func (c *common) Fatal(args ...interface{}) {
232
276
c.log(fmt.Sprintln(args...))
236
// Fatalf is equivalent to Logf() followed by FailNow().
280
// Fatalf is equivalent to Logf followed by FailNow.
237
281
func (c *common) Fatalf(format string, args ...interface{}) {
238
282
c.log(fmt.Sprintf(format, args...))
242
// Parallel signals that this test is to be run in parallel with (and only with)
243
// other parallel tests in this CPU group.
286
// Skip is equivalent to Log followed by SkipNow.
287
func (c *common) Skip(args ...interface{}) {
288
c.log(fmt.Sprintln(args...))
292
// Skipf is equivalent to Logf followed by SkipNow.
293
func (c *common) Skipf(format string, args ...interface{}) {
294
c.log(fmt.Sprintf(format, args...))
298
// SkipNow marks the test as having been skipped and stops its execution.
299
// Execution will continue at the next test or benchmark. See also FailNow.
300
// SkipNow must be called from the goroutine running the test, not from
301
// other goroutines created during the test. Calling SkipNow does not stop
302
// those other goroutines.
303
func (c *common) SkipNow() {
308
func (c *common) skip() {
314
// Skipped reports whether the test was skipped.
315
func (c *common) Skipped() bool {
321
// Parallel signals that this test is to be run in parallel with (and only with)
322
// other parallel tests.
244
323
func (t *T) Parallel() {
245
324
t.signal <- (*T)(nil) // Release main testing loop
246
325
<-t.startParallel // Wait for serial tests to finish
257
336
t.start = time.Now()
259
338
// When this goroutine is done, either because test.F(t)
260
// returned normally or because a test failure triggered
339
// returned normally or because a test failure triggered
261
340
// a call to runtime.Goexit, record the duration and send
262
341
// a signal saying that the test is done.
264
343
t.duration = time.Now().Sub(t.start)
265
344
// If the test panicked, print any test output before dying.
266
345
if err := recover(); err != nil {
297
377
func (t *T) report() {
298
378
tstr := fmt.Sprintf("(%.2f seconds)", t.duration.Seconds())
299
379
format := "--- %s: %s %s\n%s"
301
381
fmt.Printf(format, "FAIL", t.name, tstr, t.output)
302
382
} else if *chatty {
303
fmt.Printf(format, "PASS", t.name, tstr, t.output)
384
fmt.Printf(format, "SKIP", t.name, tstr, t.output)
386
fmt.Printf(format, "PASS", t.name, tstr, t.output)