9
9
10
10
type WithTransformMatcher struct {
11
11
// input
12
- Transform interface {} // must be a function of one parameter that returns one value
12
+ Transform interface {} // must be a function of one parameter that returns one value and an optional error
13
13
Matcher types.GomegaMatcher
14
14
15
15
// cached value
@@ -19,6 +19,9 @@ type WithTransformMatcher struct {
19
19
transformedValue interface {}
20
20
}
21
21
22
+ // reflect.Type for error
23
+ var errorT = reflect .TypeOf ((* error )(nil )).Elem ()
24
+
22
25
func NewWithTransformMatcher (transform interface {}, matcher types.GomegaMatcher ) * WithTransformMatcher {
23
26
if transform == nil {
24
27
panic ("transform function cannot be nil" )
@@ -27,8 +30,10 @@ func NewWithTransformMatcher(transform interface{}, matcher types.GomegaMatcher)
27
30
if txType .NumIn () != 1 {
28
31
panic ("transform function must have 1 argument" )
29
32
}
30
- if txType .NumOut () != 1 {
31
- panic ("transform function must have 1 return value" )
33
+ if numout := txType .NumOut (); numout != 1 {
34
+ if numout != 2 || ! txType .Out (1 ).AssignableTo (errorT ) {
35
+ panic ("transform function must either have 1 return value, or 1 return value plus 1 error value" )
36
+ }
32
37
}
33
38
34
39
return & WithTransformMatcher {
@@ -57,6 +62,11 @@ func (m *WithTransformMatcher) Match(actual interface{}) (bool, error) {
57
62
// call the Transform function with `actual`
58
63
fn := reflect .ValueOf (m .Transform )
59
64
result := fn .Call ([]reflect.Value {param })
65
+ if len (result ) == 2 {
66
+ if ! result [1 ].IsNil () {
67
+ return false , fmt .Errorf ("Transform function failed: %e" , result [1 ].Interface ())
68
+ }
69
+ }
60
70
m .transformedValue = result [0 ].Interface () // expect exactly one value
61
71
62
72
return m .Matcher .Match (m .transformedValue )
0 commit comments