Codebase list golang-gomega / b75d2f2
Allow WithTransform function to accept a nil value (#422) Jim Slattery authored 3 years ago GitHub committed 3 years ago
2 changed file(s) with 22 addition(s) and 6 deletion(s). Raw diff Collapse all Expand all
3939 }
4040
4141 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 }
4656 }
4757
4858 // call the Transform function with `actual`
4959 fn := reflect.ValueOf(m.Transform)
50 result := fn.Call([]reflect.Value{reflect.ValueOf(actual)})
60 result := fn.Call([]reflect.Value{param})
5161 m.transformedValue = result[0].Interface() // expect exactly one value
5262
5363 return m.Matcher.Match(m.transformedValue)
5050 Expect(S{1, "hi"}).To(WithTransform(transformer, Equal("hi")))
5151
5252 // 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")
5460 Expect(errors.New("abc")).To(WithTransform(errString, Equal("abc")))
5561 })
5662