Skip to content

Instantly share code, notes, and snippets.

@dansimau
Created November 20, 2016 04:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dansimau/128826e692d7834eb594bb7fd41d2926 to your computer and use it in GitHub Desktop.
Save dansimau/128826e692d7834eb594bb7fd41d2926 to your computer and use it in GitHub Desktop.
RunParallel is a drop-in replacement for testify/suite.Run that runs all tests in parallel.
// RunParallel is a drop-in replacement for testify/suite.Run that runs
// all tests in parallel.
//
// It uses reflection to create a new instance of the suite for each
// test
func RunParallel(t *testing.T, userSuite suite.TestingSuite) {
if _, ok := userSuite.(suite.SetupAllSuite); ok {
t.Log("Warning: SetupSuite exists but not being run in parallel mode.")
}
if _, ok := userSuite.(suite.TearDownAllSuite); ok {
t.Log("Warning: TearDownSuite exists but not being run in parallel mode.")
}
methodFinder := reflect.TypeOf(userSuite)
tests := []testing.InternalTest{}
for index := 0; index < methodFinder.NumMethod(); index++ {
method := methodFinder.Method(index)
ok, err := methodFilter(method.Name)
if err != nil {
fmt.Fprintf(os.Stderr, "testify: invalid regexp for -m: %s\n", err)
os.Exit(1)
}
if ok {
newSuiteVal := reflect.New(reflect.TypeOf(reflect.ValueOf(userSuite).Elem().Interface()))
setupTest, _ := methodFinder.MethodByName("SetupTest")
teardownTest, _ := methodFinder.MethodByName("TearDownTest")
setT, _ := methodFinder.MethodByName("SetT")
test := testing.InternalTest{
Name: method.Name,
F: func(t *testing.T) {
t.Parallel()
setT.Func.Call([]reflect.Value{newSuiteVal, reflect.ValueOf(t)})
if setupTest.Func.IsValid() {
setupTest.Func.Call([]reflect.Value{newSuiteVal})
}
defer func() {
if teardownTest.Func.IsValid() {
teardownTest.Func.Call([]reflect.Value{newSuiteVal})
}
}()
method.Func.Call([]reflect.Value{newSuiteVal})
},
}
tests = append(tests, test)
}
}
if !testing.RunTests(func(_, _ string) (bool, error) { return true, nil },
tests) {
t.Fail()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment