Debian Codegraph @

check.go

raw symbols SCIP
1 // Package check is a rich testing extension for Go's testing package.
2 //
3 // For details about the project, see:
4 //
5 // http://labix.org/gocheck
6 //
7 package check
8
9 import (
10 "bytes"
11 "errors"
12 "fmt"
13 "io"
14 "math/rand"
15 "os"
16 "path"
17 "path/filepath"
18 "reflect"
19 "regexp"
20 "runtime"
21 "strconv"
22 "strings"
23 "sync"
24 "sync/atomic"
25 "time"
26 )
27
28 // -----------------------------------------------------------------------
29 // Internal type which deals with suite method calling.
30
31 const (
32 fixtureKd = iota
33 testKd
34 )
35
36 type funcKind int
37
38 const (
39 succeededSt = iota
40 failedSt
41 skippedSt
42 panickedSt
43 fixturePanickedSt
44 missedSt
45 timeoutSt
46 )
47
48 type funcStatus uint32
49
50 // A method value can't reach its own Method structure.
51 type methodType struct {
52 reflect.Value
53 Info reflect.Method
54 }
55
56 func newMethod(receiver reflect.Value, i int) *methodType {
57 return &methodType{receiver.Method(i), receiver.Type().Method(i)}
58 }
59
60 func (method *methodType) PC() uintptr {
61 return method.Info.Func.Pointer()
62 }
63
64 func (method *methodType) suiteName() string {
65 t := method.Info.Type.In(0)
66 if t.Kind() == reflect.Ptr {
67 t = t.Elem()
68 }
69 return t.Name()
70 }
71
72 func (method *methodType) String() string {
73 return method.suiteName() + "." + method.Info.Name
74 }
75
76 func (method *methodType) matches(re *regexp.Regexp) bool {
77 return (re.MatchString(method.Info.Name) ||
78 re.MatchString(method.suiteName()) ||
79 re.MatchString(method.String()))
80 }
81
82 type C struct {
83 method *methodType
84 kind funcKind
85 testName string
86 _status funcStatus
87 logb *logger
88 logw io.Writer
89 done chan *C
90 parallel chan *C
91 reason string
92 mustFail bool
93 tempDir *tempDir
94 benchMem bool
95 startTime time.Time
96 timer
97 }
98
99 func (c *C) status() funcStatus {
100 return funcStatus(atomic.LoadUint32((*uint32)(&c._status)))
101 }
102
103 func (c *C) setStatus(s funcStatus) {
104 atomic.StoreUint32((*uint32)(&c._status), uint32(s))
105 }
106
107 func (c *C) stopNow() {
108 runtime.Goexit()
109 }
110
111 // logger is a concurrency safe byte.Buffer
112 type logger struct {
113 sync.Mutex
114 writer bytes.Buffer
115 }
116
117 func (l *logger) Write(buf []byte) (int, error) {
118 l.Lock()
119 defer l.Unlock()
120 return l.writer.Write(buf)
121 }
122
123 func (l *logger) WriteTo(w io.Writer) (int64, error) {
124 l.Lock()
125 defer l.Unlock()
126 return l.writer.WriteTo(w)
127 }
128
129 func (l *logger) String() string {
130 l.Lock()
131 defer l.Unlock()
132 return l.writer.String()
133 }
134
135 // -----------------------------------------------------------------------
136 // Handling of temporary files and directories.
137
138 type tempDir struct {
139 sync.Mutex
140 path string
141 counter int
142 }
143
144 func (td *tempDir) newPath() string {
145 td.Lock()
146 defer td.Unlock()
147 if td.path == "" {
148 var err error
149 for i := 0; i != 100; i++ {
150 path := fmt.Sprintf("%s%ccheck-%d", os.TempDir(), os.PathSeparator, rand.Int())
151 if err = os.Mkdir(path, 0700); err == nil {
152 td.path = path
153 break
154 }
155 }
156 if td.path == "" {
157 panic("Couldn't create temporary directory: " + err.Error())
158 }
159 }
160 result := filepath.Join(td.path, strconv.Itoa(td.counter))
161 td.counter += 1
162 return result
163 }
164
165 func (td *tempDir) removeAll() {
166 td.Lock()
167 defer td.Unlock()
168 if td.path != "" {
169 err := os.RemoveAll(td.path)
170 if err != nil {
171 fmt.Fprintf(os.Stderr, "WARNING: Error cleaning up temporaries: "+err.Error())
172 }
173 }
174 }
175
176 // Create a new temporary directory which is automatically removed after
177 // the suite finishes running.
178 func (c *C) MkDir() string {
179 path := c.tempDir.newPath()
180 if err := os.Mkdir(path, 0700); err != nil {
181 panic(fmt.Sprintf("Couldn't create temporary directory %s: %s", path, err.Error()))
182 }
183 return path
184 }
185
186 // -----------------------------------------------------------------------
187 // Low-level logging functions.
188
189 func (c *C) log(args ...interface{}) {
190 c.writeLog([]byte(fmt.Sprint(args...) + "\n"))
191 }
192
193 func (c *C) logf(format string, args ...interface{}) {
194 c.writeLog([]byte(fmt.Sprintf(format+"\n", args...)))
195 }
196
197 func (c *C) logNewLine() {
198 c.writeLog([]byte{'\n'})
199 }
200
201 func (c *C) writeLog(buf []byte) {
202 c.logb.Write(buf)
203 if c.logw != nil {
204 c.logw.Write(buf)
205 }
206 }
207
208 func hasStringOrError(x interface{}) (ok bool) {
209 _, ok = x.(fmt.Stringer)
210 if ok {
211 return
212 }
213 _, ok = x.(error)
214 return
215 }
216
217 func (c *C) logValue(label string, value interface{}) {
218 if label == "" {
219 if hasStringOrError(value) {
220 c.logf("... %#v (%q)", value, value)
221 } else {
222 c.logf("... %#v", value)
223 }
224 } else if value == nil {
225 c.logf("... %s = nil", label)
226 } else {
227 if hasStringOrError(value) {
228 fv := fmt.Sprintf("%#v", value)
229 qv := fmt.Sprintf("%q", value)
230 if fv != qv {
231 c.logf("... %s %s = %s (%s)", label, reflect.TypeOf(value), fv, qv)
232 return
233 }
234 }
235 if s, ok := value.(string); ok && isMultiLine(s) {
236 c.logf(`... %s %s = "" +`, label, reflect.TypeOf(value))
237 c.logMultiLine(s)
238 } else {
239 c.logf("... %s %s = %#v", label, reflect.TypeOf(value), value)
240 }
241 }
242 }
243
244 func (c *C) logMultiLine(s string) {
245 b := make([]byte, 0, len(s)*2)
246 i := 0
247 n := len(s)
248 for i < n {
249 j := i + 1
250 for j < n && s[j-1] != '\n' {
251 j++
252 }
253 b = append(b, "... "...)
254 b = strconv.AppendQuote(b, s[i:j])
255 if j < n {
256 b = append(b, " +"...)
257 }
258 b = append(b, '\n')
259 i = j
260 }
261 c.writeLog(b)
262 }
263
264 func isMultiLine(s string) bool {
265 for i := 0; i+1 < len(s); i++ {
266 if s[i] == '\n' {
267 return true
268 }
269 }
270 return false
271 }
272
273 func (c *C) logString(issue string) {
274 c.log("... ", issue)
275 }
276
277 func (c *C) logCaller(skip int) {
278 // This is a bit heavier than it ought to be.
279 skip += 1 // Our own frame.
280 pc, callerFile, callerLine, ok := runtime.Caller(skip)
281 if !ok {
282 return
283 }
284 var testFile string
285 var testLine int
286 testFunc := runtime.FuncForPC(c.method.PC())
287 if runtime.FuncForPC(pc) != testFunc {
288 for {
289 skip += 1
290 if pc, file, line, ok := runtime.Caller(skip); ok {
291 // Note that the test line may be different on
292 // distinct calls for the same test. Showing
293 // the "internal" line is helpful when debugging.
294 if runtime.FuncForPC(pc) == testFunc {
295 testFile, testLine = file, line
296 break
297 }
298 } else {
299 break
300 }
301 }
302 }
303 if testFile != "" && (testFile != callerFile || testLine != callerLine) {
304 c.logCode(testFile, testLine)
305 }
306 c.logCode(callerFile, callerLine)
307 }
308
309 func (c *C) logCode(path string, line int) {
310 c.logf("%s:%d:", nicePath(path), line)
311 code, err := printLine(path, line)
312 if code == "" {
313 code = "..." // XXX Open the file and take the raw line.
314 if err != nil {
315 code += err.Error()
316 }
317 }
318 c.log(indent(code, " "))
319 }
320
321 var valueGo = filepath.Join("reflect", "value.go")
322 var asmGo = filepath.Join("runtime", "asm_")
323
324 func (c *C) logPanic(skip int, value interface{}) {
325 skip++ // Our own frame.
326 initialSkip := skip
327 for ; ; skip++ {
328 if pc, file, line, ok := runtime.Caller(skip); ok {
329 if skip == initialSkip {
330 c.logf("... Panic: %s (PC=0x%X)\n", value, pc)
331 }
332 name := niceFuncName(pc)
333 path := nicePath(file)
334 if strings.Contains(path, "/gopkg.in/check.v") {
335 continue
336 }
337 if name == "Value.call" && strings.HasSuffix(path, valueGo) {
338 continue
339 }
340 if (name == "call16" || name == "call32") && strings.Contains(path, asmGo) {
341 continue
342 }
343 c.logf("%s:%d\n in %s", nicePath(file), line, name)
344 } else {
345 break
346 }
347 }
348 }
349
350 func (c *C) logSoftPanic(issue string) {
351 c.log("... Panic: ", issue)
352 }
353
354 func (c *C) logArgPanic(method *methodType, expectedType string) {
355 c.logf("... Panic: %s argument should be %s",
356 niceFuncName(method.PC()), expectedType)
357 }
358
359 // -----------------------------------------------------------------------
360 // Some simple formatting helpers.
361
362 var initWD, initWDErr = os.Getwd()
363
364 func init() {
365 if initWDErr == nil {
366 initWD = strings.Replace(initWD, "\\", "/", -1) + "/"
367 }
368 }
369
370 func nicePath(path string) string {
371 if initWDErr == nil {
372 if strings.HasPrefix(path, initWD) {
373 return path[len(initWD):]
374 }
375 }
376 return path
377 }
378
379 func niceFuncPath(pc uintptr) string {
380 function := runtime.FuncForPC(pc)
381 if function != nil {
382 filename, line := function.FileLine(pc)
383 return fmt.Sprintf("%s:%d", nicePath(filename), line)
384 }
385 return "<unknown path>"
386 }
387
388 func niceFuncName(pc uintptr) string {
389 function := runtime.FuncForPC(pc)
390 if function != nil {
391 name := path.Base(function.Name())
392 if i := strings.Index(name, "."); i > 0 {
393 name = name[i+1:]
394 }
395 if strings.HasPrefix(name, "(*") {
396 if i := strings.Index(name, ")"); i > 0 {
397 name = name[2:i] + name[i+1:]
398 }
399 }
400 if i := strings.LastIndex(name, ".*"); i != -1 {
401 name = name[:i] + "." + name[i+2:]
402 }
403 if i := strings.LastIndex(name, "·"); i != -1 {
404 name = name[:i] + "." + name[i+2:]
405 }
406 return name
407 }
408 return "<unknown function>"
409 }
410
411 // -----------------------------------------------------------------------
412 // Result tracker to aggregate call results.
413
414 type Result struct {
415 Succeeded int
416 Failed int
417 Skipped int
418 Panicked int
419 Timeouted int
420 FixturePanicked int
421 ExpectedFailures int
422 Missed int // Not even tried to run, related to a panic in the fixture.
423 RunError error // Houston, we've got a problem.
424 WorkDir string // If KeepWorkDir is true
425 }
426
427 type resultTracker struct {
428 result Result
429 _lastWasProblem bool
430 _waiting int
431 _missed int
432 _expectChan chan *C
433 _doneChan chan *C
434 _stopChan chan bool
435 }
436
437 func newResultTracker() *resultTracker {
438 return &resultTracker{_expectChan: make(chan *C), // Synchronous
439 _doneChan: make(chan *C, 32), // Asynchronous
440 _stopChan: make(chan bool)} // Synchronous
441 }
442
443 func (tracker *resultTracker) start() {
444 go tracker._loopRoutine()
445 }
446
447 func (tracker *resultTracker) waitAndStop() {
448 <-tracker._stopChan
449 }
450
451 func (tracker *resultTracker) expectCall(c *C) {
452 tracker._expectChan <- c
453 }
454
455 func (tracker *resultTracker) callDone(c *C) {
456 tracker._doneChan <- c
457 }
458
459 func (tracker *resultTracker) _loopRoutine() {
460 for {
461 var c *C
462 if tracker._waiting > 0 {
463 // Calls still running. Can't stop.
464 select {
465 // XXX Reindent this (not now to make diff clear)
466 case c = <-tracker._expectChan:
467 tracker._waiting += 1
468 case c = <-tracker._doneChan:
469 tracker._waiting -= 1
470 switch c.status() {
471 case succeededSt:
472 if c.kind == testKd {
473 if c.mustFail {
474 tracker.result.ExpectedFailures++
475 } else {
476 tracker.result.Succeeded++
477 }
478 }
479 case failedSt:
480 tracker.result.Failed++
481 case timeoutSt:
482 tracker.result.Timeouted++
483 case panickedSt:
484 if c.kind == fixtureKd {
485 tracker.result.FixturePanicked++
486 } else {
487 tracker.result.Panicked++
488 }
489 case fixturePanickedSt:
490 // Track it as missed, since the panic
491 // was on the fixture, not on the test.
492 tracker.result.Missed++
493 case missedSt:
494 tracker.result.Missed++
495 case skippedSt:
496 if c.kind == testKd {
497 tracker.result.Skipped++
498 }
499 }
500 }
501 } else {
502 // No calls. Can stop, but no done calls here.
503 select {
504 case tracker._stopChan <- true:
505 return
506 case c = <-tracker._expectChan:
507 tracker._waiting += 1
508 case c = <-tracker._doneChan:
509 panic("Tracker got an unexpected done call.")
510 }
511 }
512 }
513 }
514
515 // -----------------------------------------------------------------------
516 // The underlying suite runner.
517
518 type suiteRunner struct {
519 suite interface{}
520 setUpSuite, tearDownSuite *methodType
521 setUpTest, tearDownTest *methodType
522 tests []*methodType
523 tracker *resultTracker
524 tempDir *tempDir
525 keepDir bool
526 output *outputWriter
527 reportedProblemLast bool
528 benchTime time.Duration
529 benchMem bool
530 methodTimeout time.Duration
531 }
532
533 type RunConf struct {
534 Output io.Writer
535 Stream bool
536 Verbose bool
537 Filter string
538 MethodTimeout time.Duration
539 Benchmark bool
540 BenchmarkTime time.Duration // Defaults to 1 second
541 BenchmarkMem bool
542 KeepWorkDir bool
543 Exclude string
544 }
545
546 // Create a new suiteRunner able to run all methods in the given suite.
547 func newSuiteRunner(suite interface{}, runConf *RunConf) *suiteRunner {
548 var conf RunConf
549 if runConf != nil {
550 conf = *runConf
551 }
552 if conf.Output == nil {
553 conf.Output = os.Stdout
554 }
555 if conf.Benchmark {
556 conf.Verbose = true
557 }
558
559 suiteType := reflect.TypeOf(suite)
560 suiteNumMethods := suiteType.NumMethod()
561 suiteValue := reflect.ValueOf(suite)
562
563 runner := &suiteRunner{
564 suite: suite,
565 output: newOutputWriter(conf.Output, conf.Stream, conf.Verbose),
566 tracker: newResultTracker(),
567 benchTime: conf.BenchmarkTime,
568 benchMem: conf.BenchmarkMem,
569 tempDir: &tempDir{},
570 keepDir: conf.KeepWorkDir,
571 tests: make([]*methodType, 0, suiteNumMethods),
572 methodTimeout: conf.MethodTimeout,
573 }
574 if runner.benchTime == 0 {
575 runner.benchTime = 1 * time.Second
576 }
577
578 var filterRegexp *regexp.Regexp
579 if conf.Filter != "" {
580 if regexp, err := regexp.Compile(conf.Filter); err != nil {
581 msg := "Bad filter expression: " + err.Error()
582 runner.tracker.result.RunError = errors.New(msg)
583 return runner
584 } else {
585 filterRegexp = regexp
586 }
587 }
588
589 var excludeRegexp *regexp.Regexp
590 if conf.Exclude != "" {
591 if regexp, err := regexp.Compile(conf.Exclude); err != nil {
592 msg := "Bad exclude expression: " + err.Error()
593 runner.tracker.result.RunError = errors.New(msg)
594 return runner
595 } else {
596 excludeRegexp = regexp
597 }
598 }
599
600 for i := 0; i != suiteNumMethods; i++ {
601 method := newMethod(suiteValue, i)
602 switch method.Info.Name {
603 case "SetUpSuite":
604 runner.setUpSuite = method
605 case "TearDownSuite":
606 runner.tearDownSuite = method
607 case "SetUpTest":
608 runner.setUpTest = method
609 case "TearDownTest":
610 runner.tearDownTest = method
611 default:
612 prefix := "Test"
613 if conf.Benchmark {
614 prefix = "Benchmark"
615 }
616 if !strings.HasPrefix(method.Info.Name, prefix) {
617 continue
618 }
619 if filterRegexp == nil || method.matches(filterRegexp) {
620 if excludeRegexp == nil || !method.matches(excludeRegexp) {
621 runner.tests = append(runner.tests, method)
622 }
623 }
624 }
625 }
626 return runner
627 }
628
629 func (runner *suiteRunner) asyncRun(wg *sync.WaitGroup, notifyRunningSuitesCh chan struct{}) {
630 if runner.tracker.result.RunError != nil || len(runner.tests) <= 0 {
631 return
632 }
633 runner.tracker.start()
634 if !runner.checkFixtureArgs() {
635 runner.skipTests(missedSt, runner.tests)
636 runner.tracker.waitAndStop()
637 if runner.keepDir {
638 runner.tracker.result.WorkDir = runner.tempDir.path
639 } else {
640 runner.tempDir.removeAll()
641 }
642 return
643 }
644
645 wg.Add(1)
646 go func() {
647 c := runner.runFixture(runner.setUpSuite, "", nil)
648 defer wg.Done()
649 <-notifyRunningSuitesCh
650 runner.doRun(c)
651
652 runner.tracker.waitAndStop()
653 if runner.keepDir {
654 runner.tracker.result.WorkDir = runner.tempDir.path
655 } else {
656 runner.tempDir.removeAll()
657 }
658 }()
659 }
660
661 func (runner *suiteRunner) doRun(c *C) {
662 if c == nil || c.status() == succeededSt {
663 var delayedC []*C
664
665 for i := 0; i != len(runner.tests); i++ {
666 c := runner.forkTest(runner.tests[i])
667 select {
668 case <-c.done:
669 case <-c.parallel:
670 delayedC = append(delayedC, c)
671 }
672 if c.status() == fixturePanickedSt {
673 runner.skipTests(missedSt, runner.tests[i+1:])
674 break
675 }
676 }
677
678 // Wait those parallel tests finish.
679 for _, delayed := range delayedC {
680 <-delayed.done
681 }
682 } else if c != nil && c.status() == skippedSt {
683 runner.skipTests(skippedSt, runner.tests)
684 } else {
685 runner.skipTests(missedSt, runner.tests)
686 }
687 runner.runFixture(runner.tearDownSuite, "", nil)
688 }
689
690 // Run all methods in the given suite.
691 func (runner *suiteRunner) run() *Result {
692 if runner.tracker.result.RunError == nil && len(runner.tests) > 0 {
693 runner.tracker.start()
694 if runner.checkFixtureArgs() {
695 c := runner.runFixture(runner.setUpSuite, "", nil)
696 runner.doRun(c)
697 } else {
698 runner.skipTests(missedSt, runner.tests)
699 }
700 runner.tracker.waitAndStop()
701 if runner.keepDir {
702 runner.tracker.result.WorkDir = runner.tempDir.path
703 } else {
704 runner.tempDir.removeAll()
705 }
706 }
707 return &runner.tracker.result
708 }
709
710 // Create a call object with the given suite method, and fork a
711 // goroutine with the provided dispatcher for running it.
712 func (runner *suiteRunner) forkCall(method *methodType, kind funcKind, testName string, logb *logger, dispatcher func(c *C)) *C {
713 var logw io.Writer
714 if runner.output.Stream {
715 logw = runner.output
716 }
717 if logb == nil {
718 logb = new(logger)
719 }
720 c := &C{
721 method: method,
722 kind: kind,
723 testName: testName,
724 logb: logb,
725 logw: logw,
726 tempDir: runner.tempDir,
727 done: make(chan *C, 1),
728 parallel: make(chan *C, 1),
729 timer: timer{benchTime: runner.benchTime},
730 startTime: time.Now(),
731 benchMem: runner.benchMem,
732 }
733 runner.tracker.expectCall(c)
734 go (func() {
735 runner.reportCallStarted(c)
736 defer runner.callDone(c)
737 startTime := time.Now()
738
739 dispatcher(c)
740
741 // Don't allow a single test to run too long!
742 if c.status() == succeededSt && runner.methodTimeout > 0 && time.Since(startTime) > runner.methodTimeout {
743 c.setStatus(timeoutSt)
744 }
745 })()
746 return c
747 }
748
749 // Same as forkCall(), but wait for call to finish before returning.
750 func (runner *suiteRunner) runFunc(method *methodType, kind funcKind, testName string, logb *logger, dispatcher func(c *C)) *C {
751 c := runner.forkCall(method, kind, testName, logb, dispatcher)
752 <-c.done
753 return c
754 }
755
756 // Handle a finished call. If there were any panics, update the call status
757 // accordingly. Then, mark the call as done and report to the tracker.
758 func (runner *suiteRunner) callDone(c *C) {
759 value := recover()
760 if value != nil {
761 switch v := value.(type) {
762 case *fixturePanic:
763 if v.status == skippedSt {
764 c.setStatus(skippedSt)
765 } else {
766 c.logSoftPanic("Fixture has panicked (see related PANIC)")
767 c.setStatus(fixturePanickedSt)
768 }
769 default:
770 c.logPanic(1, value)
771 c.setStatus(panickedSt)
772 }
773 }
774 if c.mustFail {
775 switch c.status() {
776 case failedSt:
777 c.setStatus(succeededSt)
778 case succeededSt:
779 c.setStatus(failedSt)
780 c.logString("Error: Test succeeded, but was expected to fail")
781 c.logString("Reason: " + c.reason)
782 }
783 }
784
785 runner.reportCallDone(c)
786 c.done <- c
787 }
788
789 // Runs a fixture call synchronously. The fixture will still be run in a
790 // goroutine like all suite methods, but this method will not return
791 // while the fixture goroutine is not done, because the fixture must be
792 // run in a desired order.
793 func (runner *suiteRunner) runFixture(method *methodType, testName string, logb *logger) *C {
794 if method != nil {
795 c := runner.runFunc(method, fixtureKd, testName, logb, func(c *C) {
796 c.ResetTimer()
797 c.StartTimer()
798 defer c.StopTimer()
799 c.method.Call([]reflect.Value{reflect.ValueOf(c)})
800 })
801 return c
802 }
803 return nil
804 }
805
806 // Run the fixture method with runFixture(), but panic with a fixturePanic{}
807 // in case the fixture method panics. This makes it easier to track the
808 // fixture panic together with other call panics within forkTest().
809 func (runner *suiteRunner) runFixtureWithPanic(method *methodType, testName string, logb *logger, skipped *bool) *C {
810 if skipped != nil && *skipped {
811 return nil
812 }
813 c := runner.runFixture(method, testName, logb)
814 if c != nil && c.status() != succeededSt {
815 if skipped != nil {
816 *skipped = c.status() == skippedSt
817 }
818 panic(&fixturePanic{c.status(), method})
819 }
820 return c
821 }
822
823 type fixturePanic struct {
824 status funcStatus
825 method *methodType
826 }
827
828 // Run the suite test method, together with the test-specific fixture,
829 // asynchronously.
830 func (runner *suiteRunner) forkTest(method *methodType) *C {
831 testName := method.String()
832 return runner.forkCall(method, testKd, testName, nil, func(c *C) {
833 var skipped bool
834 defer runner.runFixtureWithPanic(runner.tearDownTest, testName, nil, &skipped)
835 defer c.StopTimer()
836 benchN := 1
837 for {
838 runner.runFixtureWithPanic(runner.setUpTest, testName, c.logb, &skipped)
839 mt := c.method.Type()
840 if mt.NumIn() != 1 || mt.In(0) != reflect.TypeOf(c) {
841 // Rather than a plain panic, provide a more helpful message when
842 // the argument type is incorrect.
843 c.setStatus(panickedSt)
844 c.logArgPanic(c.method, "*check.C")
845 return
846 }
847 if strings.HasPrefix(c.method.Info.Name, "Test") {
848 c.ResetTimer()
849 c.StartTimer()
850 c.method.Call([]reflect.Value{reflect.ValueOf(c)})
851 return
852 }
853 if !strings.HasPrefix(c.method.Info.Name, "Benchmark") {
854 panic("unexpected method prefix: " + c.method.Info.Name)
855 }
856
857 runtime.GC()
858 c.N = benchN
859 c.ResetTimer()
860 c.StartTimer()
861 c.method.Call([]reflect.Value{reflect.ValueOf(c)})
862 c.StopTimer()
863 if c.status() != succeededSt || c.duration >= c.benchTime || benchN >= 1e9 {
864 return
865 }
866 perOpN := int(1e9)
867 if c.nsPerOp() != 0 {
868 perOpN = int(c.benchTime.Nanoseconds() / c.nsPerOp())
869 }
870
871 // Logic taken from the stock testing package:
872 // - Run more iterations than we think we'll need for a second (1.5x).
873 // - Don't grow too fast in case we had timing errors previously.
874 // - Be sure to run at least one more than last time.
875 benchN = max(min(perOpN+perOpN/2, 100*benchN), benchN+1)
876 benchN = roundUp(benchN)
877
878 skipped = true // Don't run the deferred one if this panics.
879 runner.runFixtureWithPanic(runner.tearDownTest, testName, nil, nil)
880 skipped = false
881 }
882 })
883 }
884
885 // Same as forkTest(), but wait for the test to finish before returning.
886 func (runner *suiteRunner) runTest(method *methodType) *C {
887 c := runner.forkTest(method)
888 <-c.done
889 return c
890 }
891
892 // Helper to mark tests as skipped or missed. A bit heavy for what
893 // it does, but it enables homogeneous handling of tracking, including
894 // nice verbose output.
895 func (runner *suiteRunner) skipTests(status funcStatus, methods []*methodType) {
896 for _, method := range methods {
897 runner.runFunc(method, testKd, "", nil, func(c *C) {
898 c.setStatus(status)
899 })
900 }
901 }
902
903 // Verify if the fixture arguments are *check.C. In case of errors,
904 // log the error as a panic in the fixture method call, and return false.
905 func (runner *suiteRunner) checkFixtureArgs() bool {
906 succeeded := true
907 argType := reflect.TypeOf(&C{})
908 for _, method := range []*methodType{runner.setUpSuite, runner.tearDownSuite, runner.setUpTest, runner.tearDownTest} {
909 if method != nil {
910 mt := method.Type()
911 if mt.NumIn() != 1 || mt.In(0) != argType {
912 succeeded = false
913 runner.runFunc(method, fixtureKd, "", nil, func(c *C) {
914 c.logArgPanic(method, "*check.C")
915 c.setStatus(panickedSt)
916 })
917 }
918 }
919 }
920 return succeeded
921 }
922
923 func (runner *suiteRunner) reportCallStarted(c *C) {
924 runner.output.WriteCallStarted("START", c)
925 }
926
927 func (runner *suiteRunner) reportCallDone(c *C) {
928 runner.tracker.callDone(c)
929 switch c.status() {
930 case succeededSt:
931 if c.mustFail {
932 runner.output.WriteCallSuccess("FAIL EXPECTED", c)
933 } else {
934 runner.output.WriteCallSuccess("PASS", c)
935 }
936 case skippedSt:
937 runner.output.WriteCallSuccess("SKIP", c)
938 case failedSt:
939 runner.output.WriteCallProblem("FAIL", c)
940 case timeoutSt:
941 runner.output.WriteCallProblem("TIMEOUT", c)
942 case panickedSt:
943 runner.output.WriteCallProblem("PANIC", c)
944 case fixturePanickedSt:
945 // That's a testKd call reporting that its fixture
946 // has panicked. The fixture call which caused the
947 // panic itself was tracked above. We'll report to
948 // aid debugging.
949 runner.output.WriteCallProblem("PANIC", c)
950 case missedSt:
951 runner.output.WriteCallSuccess("MISS", c)
952 }
953 }
954
955 // -----------------------------------------------------------------------
956 // Output writer manages atomic output writing according to settings.
957
958 type outputWriter struct {
959 m sync.Mutex
960 writer io.Writer
961 wroteCallProblemLast bool
962 Stream bool
963 Verbose bool
964 }
965
966 func newOutputWriter(writer io.Writer, stream, verbose bool) *outputWriter {
967 return &outputWriter{writer: writer, Stream: stream, Verbose: verbose}
968 }
969
970 func (ow *outputWriter) Write(content []byte) (n int, err error) {
971 ow.m.Lock()
972 n, err = ow.writer.Write(content)
973 ow.m.Unlock()
974 return
975 }
976
977 func (ow *outputWriter) WriteCallStarted(label string, c *C) {
978 if ow.Stream {
979 header := renderCallHeader(label, c, "", "\n")
980 ow.m.Lock()
981 ow.writer.Write([]byte(header))
982 ow.m.Unlock()
983 }
984 }
985
986 func (ow *outputWriter) WriteCallProblem(label string, c *C) {
987 var prefix string
988 if !ow.Stream {
989 prefix = "\n-----------------------------------" +
990 "-----------------------------------\n"
991 }
992 header := renderCallHeader(label, c, prefix, "\n\n")
993 ow.m.Lock()
994 ow.wroteCallProblemLast = true
995 ow.writer.Write([]byte(header))
996 if !ow.Stream {
997 c.logb.WriteTo(ow.writer)
998 }
999 ow.m.Unlock()
1000 }
1001
1002 func (ow *outputWriter) WriteCallSuccess(label string, c *C) {
1003 if ow.Stream || (ow.Verbose && c.kind == testKd) {
1004 // TODO Use a buffer here.
1005 var suffix string
1006 if c.reason != "" {
1007 suffix = " (" + c.reason + ")"
1008 }
1009 if c.status() == succeededSt || c.status() == timeoutSt {
1010 suffix += "\t" + c.timerString()
1011 }
1012 suffix += "\n"
1013 if ow.Stream {
1014 suffix += "\n"
1015 }
1016 header := renderCallHeader(label, c, "", suffix)
1017 ow.m.Lock()
1018 // Resist temptation of using line as prefix above due to race.
1019 if !ow.Stream && ow.wroteCallProblemLast {
1020 header = "\n-----------------------------------" +
1021 "-----------------------------------\n" +
1022 header
1023 }
1024 ow.wroteCallProblemLast = false
1025 ow.writer.Write([]byte(header))
1026 ow.m.Unlock()
1027 }
1028 }
1029
1030 func renderCallHeader(label string, c *C, prefix, suffix string) string {
1031 pc := c.method.PC()
1032 return fmt.Sprintf("%s%s: %s: %s%s", prefix, label, niceFuncPath(pc),
1033 niceFuncName(pc), suffix)
1034 }