...
1
2
3
4 package testutil
5
6 import (
7 "errors"
8 "fmt"
9 "reflect"
10 "strings"
11
12 "github.com/google/go-cmp/cmp"
13 "github.com/onsi/gomega/format"
14 )
15
16
17
18
19
20
21 func Equal(expected interface{}) *EqualMatcher {
22 return DefaultAsserter.EqualMatcher(expected)
23 }
24
25 type EqualMatcher struct {
26 Expected interface{}
27 Options cmp.Options
28
29 explanation error
30 }
31
32 func (cm *EqualMatcher) Match(actual interface{}) (bool, error) {
33 match := cmp.Equal(cm.Expected, actual, cm.Options...)
34 if !match {
35 cm.explanation = errors.New(cmp.Diff(cm.Expected, actual, cm.Options...))
36 }
37 return match, nil
38 }
39
40 func (cm *EqualMatcher) FailureMessage(actual interface{}) string {
41 return "\n" + format.Message(actual, "to deeply equal", cm.Expected) +
42 "\nDiff (- Expected, + Actual):\n" + indent(cm.explanation.Error(), 1)
43 }
44
45 func (cm *EqualMatcher) NegatedFailureMessage(actual interface{}) string {
46 return "\n" + format.Message(actual, "not to deeply equal", cm.Expected) +
47 "\nDiff (- Expected, + Actual):\n" + indent(cm.explanation.Error(), 1)
48 }
49
50 func indent(in string, indentation uint) string {
51 indent := strings.Repeat(format.Indent, int(indentation))
52 lines := strings.Split(in, "\n")
53 return indent + strings.Join(lines, fmt.Sprintf("\n%s", indent))
54 }
55
56
57
58
59
60 func EqualErrorType(err error) error {
61 return equalErrorType{
62 err: err,
63 }
64 }
65
66 type equalErrorType struct {
67 err error
68 }
69
70 func (e equalErrorType) Error() string {
71 return fmt.Sprintf("EqualErrorType{Type: %T}", e.err)
72 }
73
74 func (e equalErrorType) Is(err error) bool {
75 if err == nil {
76 return false
77 }
78 return reflect.TypeOf(e.err) == reflect.TypeOf(err)
79 }
80
81 func (e equalErrorType) Unwrap() error {
82 return e.err
83 }
84
85
86
87
88
89 func EqualErrorString(err string) error {
90 return equalErrorString{
91 err: err,
92 }
93 }
94
95
96 type equalErrorString struct {
97 err string
98 }
99
100 func (e equalErrorString) Error() string {
101 return fmt.Sprintf("EqualErrorString{Error: %q}", e.err)
102 }
103
104 func (e equalErrorString) Is(err error) bool {
105 if err == nil {
106 return false
107 }
108 return e.err == err.Error()
109 }
110
111
112
113
114
115 func EqualError(err error) error {
116 return equalError{
117 err: err,
118 }
119 }
120
121 type equalError struct {
122 err error
123 }
124
125 func (e equalError) Error() string {
126 return fmt.Sprintf("EqualError{Type: %T, Error: %q}", e.err, e.err)
127 }
128
129 func (e equalError) Is(err error) bool {
130 if err == nil {
131 return false
132 }
133 return reflect.TypeOf(e.err) == reflect.TypeOf(err) &&
134 e.err.Error() == err.Error()
135 }
136
137 func (e equalError) Unwrap() error {
138 return e.err
139 }
140
View as plain text