Skip to content

Commit

Permalink
Allow WithTransform function to accept a nil value (#422)
Browse files Browse the repository at this point in the history
  • Loading branch information
slatteryjim committed Feb 26, 2021
1 parent 47c613f commit b75d2f2
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
20 changes: 15 additions & 5 deletions matchers/with_transform.go
Expand Up @@ -40,15 +40,25 @@ func NewWithTransformMatcher(transform interface{}, matcher types.GomegaMatcher)
}

func (m *WithTransformMatcher) Match(actual interface{}) (bool, error) {
// return error if actual's type is incompatible with Transform function's argument type
actualType := reflect.TypeOf(actual)
if !actualType.AssignableTo(m.transformArgType) {
return false, fmt.Errorf("Transform function expects '%s' but we have '%s'", m.transformArgType, actualType)
// prepare a parameter to pass to the Transform function
var param reflect.Value
{
if actual != nil {
// return error if actual's type is incompatible with Transform function's argument type
actualType := reflect.TypeOf(actual)
if !actualType.AssignableTo(m.transformArgType) {
return false, fmt.Errorf("Transform function expects '%s' but we have '%s'", m.transformArgType, actualType)
}
param = reflect.ValueOf(actual)
} else {
// make a nil value of the expected type
param = reflect.New(m.transformArgType).Elem()
}
}

// call the Transform function with `actual`
fn := reflect.ValueOf(m.Transform)
result := fn.Call([]reflect.Value{reflect.ValueOf(actual)})
result := fn.Call([]reflect.Value{param})
m.transformedValue = result[0].Interface() // expect exactly one value

return m.Matcher.Match(m.transformedValue)
Expand Down
8 changes: 7 additions & 1 deletion matchers/with_transform_test.go
Expand Up @@ -51,7 +51,13 @@ var _ = Describe("WithTransformMatcher", func() {
Expect(S{1, "hi"}).To(WithTransform(transformer, Equal("hi")))

// transform expects interface
errString := func(e error) string { return e.Error() }
errString := func(e error) string {
if e == nil {
return "<nil>"
}
return e.Error()
}
Expect(nil).To(WithTransform(errString, Equal("<nil>")), "handles nil actual values")
Expect(errors.New("abc")).To(WithTransform(errString, Equal("abc")))
})

Expand Down

0 comments on commit b75d2f2

Please sign in to comment.