aboutsummaryrefslogtreecommitdiff
path: root/vendor/github.com/onsi/gomega/matchers/satisfy_matcher.go
blob: ec68fe8b62c06cac24c5cf47b596c70606de2bb1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package matchers

import (
	"fmt"
	"reflect"

	"github.com/onsi/gomega/format"
)

type SatisfyMatcher struct {
	Predicate interface{}

	// cached type
	predicateArgType reflect.Type
}

func NewSatisfyMatcher(predicate interface{}) *SatisfyMatcher {
	if predicate == nil {
		panic("predicate cannot be nil")
	}
	predicateType := reflect.TypeOf(predicate)
	if predicateType.Kind() != reflect.Func {
		panic("predicate must be a function")
	}
	if predicateType.NumIn() != 1 {
		panic("predicate must have 1 argument")
	}
	if predicateType.NumOut() != 1 || predicateType.Out(0).Kind() != reflect.Bool {
		panic("predicate must return bool")
	}

	return &SatisfyMatcher{
		Predicate:        predicate,
		predicateArgType: predicateType.In(0),
	}
}

func (m *SatisfyMatcher) Match(actual interface{}) (success bool, err error) {
	// prepare a parameter to pass to the predicate
	var param reflect.Value
	if actual != nil && reflect.TypeOf(actual).AssignableTo(m.predicateArgType) {
		// The dynamic type of actual is compatible with the predicate argument.
		param = reflect.ValueOf(actual)

	} else if actual == nil && m.predicateArgType.Kind() == reflect.Interface {
		// The dynamic type of actual is unknown, so there's no way to make its
		// reflect.Value. Create a nil of the predicate argument, which is known.
		param = reflect.Zero(m.predicateArgType)

	} else {
		return false, fmt.Errorf("predicate expects '%s' but we have '%T'", m.predicateArgType, actual)
	}

	// call the predicate with `actual`
	fn := reflect.ValueOf(m.Predicate)
	result := fn.Call([]reflect.Value{param})
	return result[0].Bool(), nil
}

func (m *SatisfyMatcher) FailureMessage(actual interface{}) (message string) {
	return format.Message(actual, "to satisfy predicate", m.Predicate)
}

func (m *SatisfyMatcher) NegatedFailureMessage(actual interface{}) (message string) {
	return format.Message(actual, "to not satisfy predicate", m.Predicate)
}