~ubuntu-branches/ubuntu/vivid/golang/vivid

« back to all changes in this revision

Viewing changes to src/pkg/testing/testing.go

  • Committer: Package Import Robot
  • Author(s): James Page
  • Date: 2013-08-20 14:06:23 UTC
  • mfrom: (14.1.23 saucy-proposed)
  • Revision ID: package-import@ubuntu.com-20130820140623-b414jfxi3m0qkmrq
Tags: 2:1.1.2-2ubuntu1
* Merge from Debian unstable (LP: #1211749, #1202027). Remaining changes:
  - 016-armhf-elf-header.patch: Use correct ELF header for armhf binaries.
  - d/control,control.cross: Update Breaks/Replaces for Ubuntu
    versions to ensure smooth upgrades, regenerate control file.

Show diffs side-by-side

added added

removed removed

Lines of Context:
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.
12
12
//
 
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.")
 
17
//         }
 
18
//         ...
 
19
//     }
 
20
//
 
21
// Benchmarks
 
22
//
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.
 
27
//
 
28
// For a description of the testing flags, see
 
29
// http://golang.org/cmd/go/#Description_of_testing_flags.
17
30
//
18
31
// A sample benchmark function looks like this:
19
32
//     func BenchmarkHello(b *testing.B) {
22
35
//         }
23
36
//     }
24
37
//
 
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.
29
43
//
30
44
// If a benchmark needs some expensive setup before running, the timer
31
 
// may be stopped:
 
45
// may be reset:
32
46
//     func BenchmarkBigLen(b *testing.B) {
33
 
//         b.StopTimer()
34
47
//         big := NewBig()
35
 
//         b.StartTimer()
 
48
//         b.ResetTimer()
36
49
//         for i := 0; i < b.N; i++ {
37
50
//             big.Len()
38
51
//         }
39
52
//     }
40
53
//
 
54
// Examples
 
55
//
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:
45
60
//
46
61
//     func ExampleHello() {
47
62
//             fmt.Println("hello")
79
94
package testing
80
95
 
81
96
import (
 
97
        "bytes"
82
98
        "flag"
83
99
        "fmt"
84
100
        "os"
86
102
        "runtime/pprof"
87
103
        "strconv"
88
104
        "strings"
 
105
        "sync"
89
106
        "time"
90
107
)
91
108
 
98
115
        short = flag.Bool("test.short", false, "run smaller test suite to save time")
99
116
 
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")
109
128
 
110
129
        haveExamples bool // are there examples?
111
130
 
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.
 
141
 
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.
128
150
        return *short
129
151
}
130
152
 
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 {
134
 
        if addFileLine {
135
 
                _, file, line, ok := runtime.Caller(3) // decorate + log + public function.
136
 
                if ok {
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:]
142
 
                        }
143
 
                } else {
144
 
                        file = "???"
145
 
                        line = 1
 
153
// Verbose reports whether the -test.v flag is set.
 
154
func Verbose() bool {
 
155
        return *chatty
 
156
}
 
157
 
 
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.
 
162
        if ok {
 
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:]
146
168
                }
147
 
                s = fmt.Sprintf("%s:%d: %s", file, line, s)
148
 
        }
149
 
        s = "\t" + s // Every line is indented at least one tab.
150
 
        n := len(s)
151
 
        if n > 0 && s[n-1] != '\n' {
152
 
                s += "\n"
153
 
                n++
154
 
        }
155
 
        for i := 0; i < n-1; i++ { // -1 to avoid final newline
156
 
                if s[i] == '\n' {
 
169
        } else {
 
170
                file = "???"
 
171
                line = 1
 
172
        }
 
173
        buf := new(bytes.Buffer)
 
174
        // Every line is indented at least one tab.
 
175
        buf.WriteByte('\t')
 
176
        fmt.Fprintf(buf, "%s:%d: ", file, line)
 
177
        lines := strings.Split(s, "\n")
 
178
        if l := len(lines); l > 1 && lines[l-1] == "" {
 
179
                lines = lines[:l-1]
 
180
        }
 
181
        for i, line := range lines {
 
182
                if i > 0 {
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")
159
185
                }
 
186
                buf.WriteString(line)
160
187
        }
161
 
        return s
 
188
        buf.WriteByte('\n')
 
189
        return buf.String()
162
190
}
163
191
 
164
192
// T is a type passed to Test functions to manage test state and support formatted test logs.
170
198
}
171
199
 
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() {
 
202
        c.mu.Lock()
 
203
        defer c.mu.Unlock()
 
204
        c.failed = true
 
205
}
174
206
 
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 {
 
209
        c.mu.RLock()
 
210
        defer c.mu.RUnlock()
 
211
        return c.failed
 
212
}
177
213
 
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() {
181
221
        c.Fail()
182
222
 
204
244
 
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)...)
 
247
        c.mu.Lock()
 
248
        defer c.mu.Unlock()
 
249
        c.output = append(c.output, decorate(s)...)
208
250
}
209
251
 
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...)) }
213
256
 
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...)) }
217
261
 
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...))
221
265
        c.Fail()
222
266
}
223
267
 
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...))
227
271
        c.Fail()
228
272
}
229
273
 
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...))
233
277
        c.FailNow()
234
278
}
235
279
 
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...))
239
283
        c.FailNow()
240
284
}
241
285
 
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...))
 
289
        c.SkipNow()
 
290
}
 
291
 
 
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...))
 
295
        c.SkipNow()
 
296
}
 
297
 
 
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() {
 
304
        c.skip()
 
305
        runtime.Goexit()
 
306
}
 
307
 
 
308
func (c *common) skip() {
 
309
        c.mu.Lock()
 
310
        defer c.mu.Unlock()
 
311
        c.skipped = true
 
312
}
 
313
 
 
314
// Skipped reports whether the test was skipped.
 
315
func (c *common) Skipped() bool {
 
316
        c.mu.RLock()
 
317
        defer c.mu.RUnlock()
 
318
        return c.skipped
 
319
}
 
320
 
 
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()
258
337
 
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.
263
342
        defer func() {
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 {
 
346
                        t.Fail()
267
347
                        t.report()
268
348
                        panic(err)
269
349
                }
297
377
func (t *T) report() {
298
378
        tstr := fmt.Sprintf("(%.2f seconds)", t.duration.Seconds())
299
379
        format := "--- %s: %s %s\n%s"
300
 
        if t.failed {
 
380
        if t.Failed() {
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)
 
383
                if t.Skipped() {
 
384
                        fmt.Printf(format, "SKIP", t.name, tstr, t.output)
 
385
                } else {
 
386
                        fmt.Printf(format, "PASS", t.name, tstr, t.output)
 
387
                }
304
388
        }
305
389
}
306
390
 
356
440
                                continue
357
441
                        }
358
442
                        t.report()
359
 
                        ok = ok && !out.failed
 
443
                        ok = ok && !out.Failed()
360
444
                }
361
445
 
362
446
                running := 0
369
453
                        }
370
454
                        t := (<-collector).(*T)
371
455
                        t.report()
372
 
                        ok = ok && !t.failed
 
456
                        ok = ok && !t.Failed()
373
457
                        running--
374
458
                }
375
459
        }
394
478
                }
395
479
                // Could save f so after can call f.Close; not worth the effort.
396
480
        }
397
 
 
 
481
        if *blockProfile != "" && *blockProfileRate >= 0 {
 
482
                runtime.SetBlockProfileRate(*blockProfileRate)
 
483
        }
398
484
}
399
485
 
400
486
// after runs after all testing.
413
499
                }
414
500
                f.Close()
415
501
        }
 
502
        if *blockProfile != "" && *blockProfileRate >= 0 {
 
503
                f, err := os.Create(*blockProfile)
 
504
                if err != nil {
 
505
                        fmt.Fprintf(os.Stderr, "testing: %s", err)
 
506
                        return
 
507
                }
 
508
                if err = pprof.Lookup("block").WriteTo(f, 0); err != nil {
 
509
                        fmt.Fprintf(os.Stderr, "testing: can't write %s: %s", *blockProfile, err)
 
510
                }
 
511
                f.Close()
 
512
        }
416
513
}
417
514
 
418
515
var timer *time.Timer