Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 31 additions & 3 deletions assert/assertions.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,21 +178,49 @@ func ObjectsAreEqualValues(expected, actual interface{}) bool {
return false
}

// Attempt conversion of expected to actual type
// This handles more cases than just the ConvertibleTo check above
if !expectedValue.CanConvert(actualType) {
// Types are not convertible, so they cannot be equal
// This prevents panics when calling [reflect.Value.Convert]
return false
}

expectedConverted := expectedValue.Convert(actualType)
if !expectedConverted.CanInterface() {
// Cannot interface after conversion, so cannot be equal
// This prevents panics when calling [reflect.Value.Interface]
return false
}

if !isNumericType(expectedType) || !isNumericType(actualType) {
// Attempt comparison after type conversion
return reflect.DeepEqual(
expectedValue.Convert(actualType).Interface(), actual,
expectedConverted.Interface(), actual,
)
}

// If BOTH values are numeric, there are chances of false positives due
// to overflow or underflow. So, we need to make sure to always convert
// the smaller type to a larger type before comparing.
if expectedType.Size() >= actualType.Size() {
return actualValue.Convert(expectedType).Interface() == expected
if !actualValue.CanConvert(expectedType) {
// Cannot convert actual to the expected type, so cannot be equal
// This is a hypothetical case to prevent panics when calling [reflect.Value.Convert]
return false
}

actualConverted := actualValue.Convert(expectedType)
if !actualConverted.CanInterface() {
// Cannot interface after conversion, so cannot be equal
// This is a hypothetical case to prevent panics when calling [reflect.Value.Convert]
return false
}

return actualConverted.Interface() == expected
}

return expectedValue.Convert(actualType).Interface() == actual
return expectedConverted.Interface() == actual
}

// isNumericType returns true if the type is one of:
Expand Down
4 changes: 4 additions & 0 deletions assert/assertions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,10 @@ func TestObjectsAreEqualValues(t *testing.T) {
{3.14, complex128(1e+100 + 1e+100i), false},
{complex128(1e+10 + 1e+10i), complex64(1e+10 + 1e+10i), true},
{complex64(1e+10 + 1e+10i), complex128(1e+10 + 1e+10i), true},

// panics should be caught and treated as inequality
// https://github.com/stretchr/testify/issues/1699
{[]int{1, 2}, (*[3]int)(nil), false},
}

for _, c := range cases {
Expand Down