mirror-to-gitea/vendor/github.com/onsi/gomega/matchers/with_transform.go
vendor/github.com/onsi/gomega/matchers/with_transform.goRaw
1package matchers
2
3import (
4 "fmt"
5 "reflect"
6
7 "github.com/onsi/gomega/internal/oraclematcher"
8 "github.com/onsi/gomega/types"
9)
10
11type WithTransformMatcher struct {
12 // input
13 Transform interface{} // must be a function of one parameter that returns one value
14 Matcher types.GomegaMatcher
15
16 // cached value
17 transformArgType reflect.Type
18
19 // state
20 transformedValue interface{}
21}
22
23func NewWithTransformMatcher(transform interface{}, matcher types.GomegaMatcher) *WithTransformMatcher {
24 if transform == nil {
25 panic("transform function cannot be nil")
26 }
27 txType := reflect.TypeOf(transform)
28 if txType.NumIn() != 1 {
29 panic("transform function must have 1 argument")
30 }
31 if txType.NumOut() != 1 {
32 panic("transform function must have 1 return value")
33 }
34
35 return &WithTransformMatcher{
36 Transform: transform,
37 Matcher: matcher,
38 transformArgType: reflect.TypeOf(transform).In(0),
39 }
40}
41
42func (m *WithTransformMatcher) Match(actual interface{}) (bool, error) {
43 // prepare a parameter to pass to the Transform function
44 var param reflect.Value
45 if actual != nil && reflect.TypeOf(actual).AssignableTo(m.transformArgType) {
46 // The dynamic type of actual is compatible with the transform argument.
47 param = reflect.ValueOf(actual)
48
49 } else if actual == nil && m.transformArgType.Kind() == reflect.Interface {
50 // The dynamic type of actual is unknown, so there's no way to make its
51 // reflect.Value. Create a nil of the transform argument, which is known.
52 param = reflect.Zero(m.transformArgType)
53
54 } else {
55 return false, fmt.Errorf("Transform function expects '%s' but we have '%T'", m.transformArgType, actual)
56 }
57
58 // call the Transform function with `actual`
59 fn := reflect.ValueOf(m.Transform)
60 result := fn.Call([]reflect.Value{param})
61 m.transformedValue = result[0].Interface() // expect exactly one value
62
63 return m.Matcher.Match(m.transformedValue)
64}
65
66func (m *WithTransformMatcher) FailureMessage(_ interface{}) (message string) {
67 return m.Matcher.FailureMessage(m.transformedValue)
68}
69
70func (m *WithTransformMatcher) NegatedFailureMessage(_ interface{}) (message string) {
71 return m.Matcher.NegatedFailureMessage(m.transformedValue)
72}
73
74func (m *WithTransformMatcher) MatchMayChangeInTheFuture(_ interface{}) bool {
75 // TODO: Maybe this should always just return true? (Only an issue for non-deterministic transformers.)
76 //
77 // Querying the next matcher is fine if the transformer always will return the same value.
78 // But if the transformer is non-deterministic and returns a different value each time, then there
79 // is no point in querying the next matcher, since it can only comment on the last transformed value.
80 return oraclematcher.MatchMayChangeInTheFuture(m.Matcher, m.transformedValue)
81}