Add assert.EqualValues, which attempts to convert types to test equality. Fixes #129

pull/130/head
Paul Querna 2015-02-10 16:51:45 -08:00
parent 43d0eed245
commit e73f5c7e39
3 changed files with 49 additions and 0 deletions

View File

@ -45,6 +45,23 @@ func ObjectsAreEqual(expected, actual interface{}) bool {
}
func ObjectsAreEqualValues(expected, actual interface{}) bool {
if ObjectsAreEqual(expected, actual) {
return true
}
actualType := reflect.TypeOf(actual)
expectedValue := reflect.ValueOf(expected)
if expectedValue.Type().ConvertibleTo(actualType) {
// Attempt comparison after type conversion
if reflect.DeepEqual(actual, expectedValue.Convert(actualType).Interface()) {
return true
}
}
return false
}
/* CallerInfo is necessary because the assert functions use the testing object
internally, causing it to print the file:line of the assert method, rather than where
the problem actually occured in calling code.*/
@ -189,6 +206,23 @@ func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{})
}
// EqualValues asserts that two objects are equal or convertable to the same types
// and equal.
//
// assert.EqualValues(t, uint32(123), int32(123), "123 and 123 should be equal")
//
// Returns whether the assertion was successful (true) or not (false).
func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
if !ObjectsAreEqualValues(expected, actual) {
return Fail(t, fmt.Sprintf("Not equal: %#v (expected)\n"+
" != %#v (actual)", expected, actual), msgAndArgs...)
}
return true
}
// Exactly asserts that two objects are equal is value and type.
//
// assert.Exactly(t, int32(123), int64(123), "123 and 123 should NOT be equal")

View File

@ -55,6 +55,12 @@ func TestObjectsAreEqual(t *testing.T) {
if ObjectsAreEqual(0.1, 0) {
t.Error("objectsAreEqual should return false")
}
if ObjectsAreEqual(uint32(10), int32(10)) {
t.Error("objectsAreEqual should return false")
}
if !ObjectsAreEqualValues(uint32(10), int32(10)) {
t.Error("ObjectsAreEqualValues should return true")
}
}

View File

@ -42,6 +42,15 @@ func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{})
}
}
// EqualValues asserts that two objects are equal or convertable to each other.
//
// require.EqualValues(t, uint32(123), int32(123), "123 and 123 should be equal")
func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) {
if !assert.EqualValues(t, expected, actual, msgAndArgs...) {
t.FailNow()
}
}
// Exactly asserts that two objects are equal is value and type.
//
// require.Exactly(t, int32(123), int64(123), "123 and 123 should NOT be equal")