Wednesday 15 February 2012

testing - Checking for compatible types using reflection in Go -



testing - Checking for compatible types using reflection in Go -

although aware might not idiomatic panic in go, test ensure function panics under conditions , not in others.

an illustration of function.

func paniconerr(potentialerr error) { if potentialerr != nil { panic(potentialerr) } }

the next implementation checking if function panic.

func invocationcausedpanic(f interface{}, params ...interface{}) bool { // obtain function's signature. reflectedfunc := reflect.valueof(f) functype := reflect.typeof(f) if functype.numin() != len(params) { panic("invocationcausedpanic called function , wrong number of parameter(s).") } reflectedparams := make([]reflect.value, len(params)) paramindex, paramvalue := range params { expectedtype := functype.in(paramindex) actualtype := reflect.typeof(paramvalue) if actualtype != expectedtype { errstr := fmt.sprintf("invocationcausedpanic called mismatched parameter type [parameter #%v: expected %v; got %v].", paramindex, expectedtype, actualtype) panic(errstr) } reflectedparams[paramindex] = reflect.valueof(paramvalue) } homecoming invoke(reflectedfunc, reflectedparams) } func invoke(reflectedfunc reflect.value, reflectedparams []reflect.value) (panicked bool) { defer func() { if r := recover(); r != nil { panicked = true } }() reflectedfunc.call(reflectedparams) homecoming }

calling either of next cause type-check fail.

invocationcausedpanic(paniconerr, errors.new("some error.")) invocationcausedpanic(paniconerr, nil)

however, seems possible phone call paniconerr using both nil , generate calling errors.new (seems of type *errors.errorstring).

as such, there way check if type of parameter suitable invoking function?

while know possible utilize defer , recover more test function, curious whether possible write general function can take function , parameters , determine whether resulted in panic (assuming function completes).

relevant go playground: http://play.golang.org/p/qug7oguibd

use function determine if parameter compatible:

func compatible(actual, expected reflect.type) bool { if actual == nil { k := expected.kind() homecoming k == reflect.chan || k == reflect.func || k == reflect.interface || k == reflect.map || k == reflect.ptr || k == reflect.slice } homecoming actual.assignableto(expected) }

playground

testing reflection go

No comments:

Post a Comment