/
match_specified_contents.go
62 lines (54 loc) · 2.01 KB
/
match_specified_contents.go
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
package matchers
import (
"fmt"
"reflect"
"github.com/cloudfoundry/sonde-go/events"
"github.com/onsi/gomega/format"
"github.com/onsi/gomega/types"
)
func MatchSpecifiedContents(expected *events.Envelope) types.GomegaMatcher {
return &specifiedContentsMatcher{
expected: expected,
}
}
type specifiedContentsMatcher struct {
expected *events.Envelope
failureReason string
}
func (matcher *specifiedContentsMatcher) Match(actual interface{}) (bool, error) {
if _, ok := actual.(*events.Envelope); !ok {
return false, fmt.Errorf("MatchSpecifiedContents matcher expects actual to be an *events.Envelope")
}
return matcher.matchSpecifiedContents(actual, matcher.expected)
}
func (matcher *specifiedContentsMatcher) FailureMessage(actual interface{}) string {
return fmt.Sprintf("Expected\n\t%#s\not equal non-nil contents of\n\t%#s\nReason for failure: %s\n", format.Object(actual, 1), format.Object(matcher.expected, 1), matcher.failureReason)
}
func (matcher *specifiedContentsMatcher) NegatedFailureMessage(actual interface{}) string {
return fmt.Sprintf("Expected\n\t%#s not to equal non-nil contents of\n\t%#s\n", format.Object(actual, 1), format.Object(matcher.expected, 1))
}
func (matcher *specifiedContentsMatcher) matchSpecifiedContents(actualInter, expectedInter interface{}) (bool, error) {
actual := reflect.ValueOf(actualInter)
expected := reflect.ValueOf(expectedInter)
switch expected.Kind() {
case reflect.Ptr:
if expected.IsNil() {
return true, nil
}
return matcher.matchSpecifiedContents(actual.Elem().Interface(), expected.Elem().Interface())
case reflect.Struct:
for i := 0; i < expected.NumField(); i++ {
success, err := matcher.matchSpecifiedContents(actual.Field(i).Interface(), expected.Field(i).Interface())
if !success || err != nil {
return success, err
}
}
return true, nil
default:
if !reflect.DeepEqual(actualInter, expectedInter) {
matcher.failureReason = fmt.Sprintf("%#v != %#v", actualInter, expectedInter)
return false, nil
}
return true, nil
}
}