check.go 21 KB

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