Created
October 20, 2018 23:30
-
-
Save jaslong/8852fb0ae5367484957dc9b6c33924d3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package testing | |
import ( | |
"fmt" | |
"github.com/google/go-cmp/cmp" | |
"github.com/onsi/gomega/format" | |
"github.com/onsi/gomega/types" | |
) | |
// EqualCmp is a more powerful and safer alternative to gomega.Equal for comparing whether two | |
// values are semantically equal. | |
func EqualCmp(expected interface{}, options ...cmp.Option) types.GomegaMatcher { | |
return &equalCmpMatcher{ | |
expected: expected, | |
options: options, | |
} | |
} | |
type equalCmpMatcher struct { | |
expected interface{} | |
options cmp.Options | |
} | |
func (matcher *equalCmpMatcher) Match(actual interface{}) (success bool, err error) { | |
if actual == nil && matcher.expected == nil { | |
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") | |
} | |
return cmp.Equal(actual, matcher.expected, matcher.options), nil | |
} | |
func (matcher *equalCmpMatcher) FailureMessage(actual interface{}) (message string) { | |
actualString, actualOK := actual.(string) | |
expectedString, expectedOK := matcher.expected.(string) | |
if actualOK && expectedOK { | |
return format.MessageWithDiff(actualString, "to equal", expectedString) | |
} | |
diff := cmp.Diff(actual, matcher.expected, matcher.options) | |
return format.Message(actual, "to equal", matcher.expected) + | |
"\n\nDiff:\n" + format.IndentString(diff, 1) | |
} | |
func (matcher *equalCmpMatcher) NegatedFailureMessage(actual interface{}) (message string) { | |
diff := cmp.Diff(actual, matcher.expected, matcher.options) | |
return format.Message(actual, "not to equal", matcher.expected) + | |
"\n\nDiff:\n" + format.IndentString(diff, 1) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment