suite.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Package suite is a simplified version of testify's suite package which has unnecessary dependencies.
  2. // Please remove this package whenever possible.
  3. package suite
  4. import (
  5. "flag"
  6. "reflect"
  7. "runtime/debug"
  8. "strings"
  9. "testing"
  10. )
  11. // TimeoutFlag is the flag to set a per-test timeout when running tests. Defaults to `-timeout`.
  12. var TimeoutFlag = flag.Duration("timeout", 0, "DO NOT USE")
  13. var typTestingT = reflect.TypeOf(new(testing.T))
  14. // Run takes a testing suite and runs all of the tests attached to it.
  15. func Run(t *testing.T, suite interface{}) {
  16. defer failOnPanic(t)
  17. suiteSetupDone := false
  18. defer func() {
  19. if suiteSetupDone {
  20. if tearDownAllSuite, ok := suite.(TearDownAllSuite); ok {
  21. tearDownAllSuite.TearDownSuite(t)
  22. }
  23. }
  24. }()
  25. methodFinder := reflect.TypeOf(suite)
  26. for index := 0; index < methodFinder.NumMethod(); index++ {
  27. method := methodFinder.Method(index)
  28. if !methodFilter(method.Name, method.Type) {
  29. continue
  30. }
  31. t.Run(method.Name, func(t *testing.T) {
  32. defer failOnPanic(t)
  33. if !suiteSetupDone {
  34. if setupAllSuite, ok := suite.(SetupAllSuite); ok {
  35. setupAllSuite.SetUpSuite(t)
  36. }
  37. suiteSetupDone = true
  38. }
  39. if setupTestSuite, ok := suite.(SetupTestSuite); ok {
  40. setupTestSuite.SetUpTest(t)
  41. }
  42. defer func() {
  43. if tearDownTestSuite, ok := suite.(TearDownTestSuite); ok {
  44. tearDownTestSuite.TearDownTest(t)
  45. }
  46. }()
  47. method.Func.Call([]reflect.Value{reflect.ValueOf(suite), reflect.ValueOf(t)})
  48. })
  49. }
  50. }
  51. func failOnPanic(t *testing.T) {
  52. r := recover()
  53. if r != nil {
  54. t.Errorf("test suite panicked: %v\n%s", r, debug.Stack())
  55. t.FailNow()
  56. }
  57. }
  58. func methodFilter(name string, typ reflect.Type) bool {
  59. return strings.HasPrefix(name, "Test") && typ.NumIn() == 2 && typ.In(1) == typTestingT // 2 params: method receiver and *testing.T
  60. }