Allow WithTransform function to accept a nil value (#422)
Jim Slattery authored 3 years ago
GitHub committed 3 years ago
39 | 39 |
}
|
40 | 40 |
|
41 | 41 |
func (m *WithTransformMatcher) Match(actual interface{}) (bool, error) {
|
42 | |
// return error if actual's type is incompatible with Transform function's argument type
|
43 | |
actualType := reflect.TypeOf(actual)
|
44 | |
if !actualType.AssignableTo(m.transformArgType) {
|
45 | |
return false, fmt.Errorf("Transform function expects '%s' but we have '%s'", m.transformArgType, actualType)
|
|
42 |
// prepare a parameter to pass to the Transform function
|
|
43 |
var param reflect.Value
|
|
44 |
{
|
|
45 |
if actual != nil {
|
|
46 |
// return error if actual's type is incompatible with Transform function's argument type
|
|
47 |
actualType := reflect.TypeOf(actual)
|
|
48 |
if !actualType.AssignableTo(m.transformArgType) {
|
|
49 |
return false, fmt.Errorf("Transform function expects '%s' but we have '%s'", m.transformArgType, actualType)
|
|
50 |
}
|
|
51 |
param = reflect.ValueOf(actual)
|
|
52 |
} else {
|
|
53 |
// make a nil value of the expected type
|
|
54 |
param = reflect.New(m.transformArgType).Elem()
|
|
55 |
}
|
46 | 56 |
}
|
47 | 57 |
|
48 | 58 |
// call the Transform function with `actual`
|
49 | 59 |
fn := reflect.ValueOf(m.Transform)
|
50 | |
result := fn.Call([]reflect.Value{reflect.ValueOf(actual)})
|
|
60 |
result := fn.Call([]reflect.Value{param})
|
51 | 61 |
m.transformedValue = result[0].Interface() // expect exactly one value
|
52 | 62 |
|
53 | 63 |
return m.Matcher.Match(m.transformedValue)
|
50 | 50 |
Expect(S{1, "hi"}).To(WithTransform(transformer, Equal("hi")))
|
51 | 51 |
|
52 | 52 |
// transform expects interface
|
53 | |
errString := func(e error) string { return e.Error() }
|
|
53 |
errString := func(e error) string {
|
|
54 |
if e == nil {
|
|
55 |
return "<nil>"
|
|
56 |
}
|
|
57 |
return e.Error()
|
|
58 |
}
|
|
59 |
Expect(nil).To(WithTransform(errString, Equal("<nil>")), "handles nil actual values")
|
54 | 60 |
Expect(errors.New("abc")).To(WithTransform(errString, Equal("abc")))
|
55 | 61 |
})
|
56 | 62 |
|