Matthias Andreas Benkard | 832a54e | 2019-01-29 09:27:38 +0100 | [diff] [blame] | 1 | package matchers |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "fmt" |
| 6 | "reflect" |
| 7 | |
| 8 | "github.com/onsi/gomega/format" |
| 9 | ) |
| 10 | |
| 11 | type EqualMatcher struct { |
| 12 | Expected interface{} |
| 13 | } |
| 14 | |
| 15 | func (matcher *EqualMatcher) Match(actual interface{}) (success bool, err error) { |
| 16 | if actual == nil && matcher.Expected == nil { |
| 17 | return false, fmt.Errorf("Refusing to compare <nil> to <nil>.\nBe explicit and use BeNil() instead. This is to avoid mistakes where both sides of an assertion are erroneously uninitialized.") |
| 18 | } |
| 19 | // Shortcut for byte slices. |
| 20 | // Comparing long byte slices with reflect.DeepEqual is very slow, |
| 21 | // so use bytes.Equal if actual and expected are both byte slices. |
| 22 | if actualByteSlice, ok := actual.([]byte); ok { |
| 23 | if expectedByteSlice, ok := matcher.Expected.([]byte); ok { |
| 24 | return bytes.Equal(actualByteSlice, expectedByteSlice), nil |
| 25 | } |
| 26 | } |
| 27 | return reflect.DeepEqual(actual, matcher.Expected), nil |
| 28 | } |
| 29 | |
| 30 | func (matcher *EqualMatcher) FailureMessage(actual interface{}) (message string) { |
| 31 | actualString, actualOK := actual.(string) |
| 32 | expectedString, expectedOK := matcher.Expected.(string) |
| 33 | if actualOK && expectedOK { |
| 34 | return format.MessageWithDiff(actualString, "to equal", expectedString) |
| 35 | } |
| 36 | |
| 37 | return format.Message(actual, "to equal", matcher.Expected) |
| 38 | } |
| 39 | |
| 40 | func (matcher *EqualMatcher) NegatedFailureMessage(actual interface{}) (message string) { |
| 41 | return format.Message(actual, "not to equal", matcher.Expected) |
| 42 | } |