suite.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. package suite
  2. import (
  3. "flag"
  4. "fmt"
  5. "os"
  6. "reflect"
  7. "regexp"
  8. "runtime/debug"
  9. "sync"
  10. "testing"
  11. "time"
  12. "github.com/stretchr/testify/assert"
  13. "github.com/stretchr/testify/require"
  14. )
  15. var allTestsFilter = func(_, _ string) (bool, error) { return true, nil }
  16. var matchMethod = flag.String("testify.m", "", "regular expression to select tests of the testify suite to run")
  17. // Suite is a basic testing suite with methods for storing and
  18. // retrieving the current *testing.T context.
  19. type Suite struct {
  20. *assert.Assertions
  21. mu sync.RWMutex
  22. require *require.Assertions
  23. t *testing.T
  24. // Parent suite to have access to the implemented methods of parent struct
  25. s TestingSuite
  26. }
  27. // T retrieves the current *testing.T context.
  28. func (suite *Suite) T() *testing.T {
  29. suite.mu.RLock()
  30. defer suite.mu.RUnlock()
  31. return suite.t
  32. }
  33. // SetT sets the current *testing.T context.
  34. func (suite *Suite) SetT(t *testing.T) {
  35. suite.mu.Lock()
  36. defer suite.mu.Unlock()
  37. suite.t = t
  38. suite.Assertions = assert.New(t)
  39. suite.require = require.New(t)
  40. }
  41. // SetS needs to set the current test suite as parent
  42. // to get access to the parent methods
  43. func (suite *Suite) SetS(s TestingSuite) {
  44. suite.s = s
  45. }
  46. // Require returns a require context for suite.
  47. func (suite *Suite) Require() *require.Assertions {
  48. suite.mu.Lock()
  49. defer suite.mu.Unlock()
  50. if suite.require == nil {
  51. suite.require = require.New(suite.T())
  52. }
  53. return suite.require
  54. }
  55. // Assert returns an assert context for suite. Normally, you can call
  56. // `suite.NoError(expected, actual)`, but for situations where the embedded
  57. // methods are overridden (for example, you might want to override
  58. // assert.Assertions with require.Assertions), this method is provided so you
  59. // can call `suite.Assert().NoError()`.
  60. func (suite *Suite) Assert() *assert.Assertions {
  61. suite.mu.Lock()
  62. defer suite.mu.Unlock()
  63. if suite.Assertions == nil {
  64. suite.Assertions = assert.New(suite.T())
  65. }
  66. return suite.Assertions
  67. }
  68. func recoverAndFailOnPanic(t *testing.T) {
  69. r := recover()
  70. failOnPanic(t, r)
  71. }
  72. func failOnPanic(t *testing.T, r interface{}) {
  73. if r != nil {
  74. t.Errorf("test panicked: %v\n%s", r, debug.Stack())
  75. t.FailNow()
  76. }
  77. }
  78. // Run provides suite functionality around golang subtests. It should be
  79. // called in place of t.Run(name, func(t *testing.T)) in test suite code.
  80. // The passed-in func will be executed as a subtest with a fresh instance of t.
  81. // Provides compatibility with go test pkg -run TestSuite/TestName/SubTestName.
  82. func (suite *Suite) Run(name string, subtest func()) bool {
  83. oldT := suite.T()
  84. if setupSubTest, ok := suite.s.(SetupSubTest); ok {
  85. setupSubTest.SetupSubTest()
  86. }
  87. defer func() {
  88. suite.SetT(oldT)
  89. if tearDownSubTest, ok := suite.s.(TearDownSubTest); ok {
  90. tearDownSubTest.TearDownSubTest()
  91. }
  92. }()
  93. return oldT.Run(name, func(t *testing.T) {
  94. suite.SetT(t)
  95. subtest()
  96. })
  97. }
  98. // Run takes a testing suite and runs all of the tests attached
  99. // to it.
  100. func Run(t *testing.T, suite TestingSuite) {
  101. defer recoverAndFailOnPanic(t)
  102. suite.SetT(t)
  103. suite.SetS(suite)
  104. var suiteSetupDone bool
  105. var stats *SuiteInformation
  106. if _, ok := suite.(WithStats); ok {
  107. stats = newSuiteInformation()
  108. }
  109. tests := []testing.InternalTest{}
  110. methodFinder := reflect.TypeOf(suite)
  111. suiteName := methodFinder.Elem().Name()
  112. for i := 0; i < methodFinder.NumMethod(); i++ {
  113. method := methodFinder.Method(i)
  114. ok, err := methodFilter(method.Name)
  115. if err != nil {
  116. fmt.Fprintf(os.Stderr, "testify: invalid regexp for -m: %s\n", err)
  117. os.Exit(1)
  118. }
  119. if !ok {
  120. continue
  121. }
  122. if !suiteSetupDone {
  123. if stats != nil {
  124. stats.Start = time.Now()
  125. }
  126. if setupAllSuite, ok := suite.(SetupAllSuite); ok {
  127. setupAllSuite.SetupSuite()
  128. }
  129. suiteSetupDone = true
  130. }
  131. test := testing.InternalTest{
  132. Name: method.Name,
  133. F: func(t *testing.T) {
  134. parentT := suite.T()
  135. suite.SetT(t)
  136. defer recoverAndFailOnPanic(t)
  137. defer func() {
  138. r := recover()
  139. if stats != nil {
  140. passed := !t.Failed() && r == nil
  141. stats.end(method.Name, passed)
  142. }
  143. if afterTestSuite, ok := suite.(AfterTest); ok {
  144. afterTestSuite.AfterTest(suiteName, method.Name)
  145. }
  146. if tearDownTestSuite, ok := suite.(TearDownTestSuite); ok {
  147. tearDownTestSuite.TearDownTest()
  148. }
  149. suite.SetT(parentT)
  150. failOnPanic(t, r)
  151. }()
  152. if setupTestSuite, ok := suite.(SetupTestSuite); ok {
  153. setupTestSuite.SetupTest()
  154. }
  155. if beforeTestSuite, ok := suite.(BeforeTest); ok {
  156. beforeTestSuite.BeforeTest(methodFinder.Elem().Name(), method.Name)
  157. }
  158. if stats != nil {
  159. stats.start(method.Name)
  160. }
  161. method.Func.Call([]reflect.Value{reflect.ValueOf(suite)})
  162. },
  163. }
  164. tests = append(tests, test)
  165. }
  166. if suiteSetupDone {
  167. defer func() {
  168. if tearDownAllSuite, ok := suite.(TearDownAllSuite); ok {
  169. tearDownAllSuite.TearDownSuite()
  170. }
  171. if suiteWithStats, measureStats := suite.(WithStats); measureStats {
  172. stats.End = time.Now()
  173. suiteWithStats.HandleStats(suiteName, stats)
  174. }
  175. }()
  176. }
  177. runTests(t, tests)
  178. }
  179. // Filtering method according to set regular expression
  180. // specified command-line argument -m
  181. func methodFilter(name string) (bool, error) {
  182. if ok, _ := regexp.MatchString("^Test", name); !ok {
  183. return false, nil
  184. }
  185. return regexp.MatchString(*matchMethod, name)
  186. }
  187. func runTests(t testing.TB, tests []testing.InternalTest) {
  188. if len(tests) == 0 {
  189. t.Log("warning: no tests to run")
  190. return
  191. }
  192. r, ok := t.(runner)
  193. if !ok { // backwards compatibility with Go 1.6 and below
  194. if !testing.RunTests(allTestsFilter, tests) {
  195. t.Fail()
  196. }
  197. return
  198. }
  199. for _, test := range tests {
  200. r.Run(test.Name, test.F)
  201. }
  202. }
  203. type runner interface {
  204. Run(name string, f func(t *testing.T)) bool
  205. }