Created
February 10, 2023 16:07
-
-
Save micahhausler/c535ae54d5f9a02412ac85f5d8e21ba6 to your computer and use it in GitHub Desktop.
Reflective Go Test Runner
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package tests | |
import ( | |
"reflect" | |
"strings" | |
"testing" | |
) | |
type TestRunner struct{} | |
func (tr *TestRunner) Runtests() { | |
testSuite := []testing.InternalTest{} | |
// Dynamically find methods matching `Test*(*testing.T)` | |
typ := reflect.TypeOf(tr) | |
val := reflect.ValueOf(tr) | |
for i := 0; i < typ.NumMethod(); i++ { | |
method := typ.Method(i) | |
twoIn := method.Type.NumIn() == 2 | |
zeroOut := method.Type.NumOut() == 0 | |
testingArg := method.Type.In(1).String() == "*testing.T" | |
testPrefix := strings.HasPrefix(method.Name, "Test") | |
if twoIn && zeroOut && testingArg && testPrefix { | |
methodVal := val.MethodByName(method.Name) | |
methodIface := methodVal.Convert(reflect.TypeOf((*func(*testing.T))(nil)).Elem()).Interface() | |
if methodFunc, ok := methodIface.(func(*testing.T)); ok { | |
testSuite = append(testSuite, testing.InternalTest{Name: method.Name, F: methodFunc}) | |
} | |
} | |
} | |
testing.Main(matchString, testSuite, nil, nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment