Skip to content
Open
Show file tree
Hide file tree
Changes from 3 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
28 changes: 23 additions & 5 deletions assert/assertions.go
Original file line number Diff line number Diff line change
Expand Up @@ -187,11 +187,29 @@ func ObjectsAreEqualValues(expected, actual interface{}) bool {
// 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
}

return expectedValue.Convert(actualType).Interface() == actual
fromType := actualType
toType := expectedType
fromValue := actualValue
toValue := expectedValue
if expectedType.Size() < actualType.Size() {
fromType = expectedType
toType = actualType
fromValue = expectedValue
toValue = actualValue
}

// If we are converting from float32 to float64, the converted value will
// have trailing non zero decimals due to binary representation differences
// For example: float64(float32(10.1)) = 10.100000381469727
// To remove the trailing decimals we can round the 64-bit value to
// expected precision of 32-bit which is 6 decimal places
newValue := fromValue.Convert(toType).Interface()
if fromType.Kind() == reflect.Float32 && toType.Kind() == reflect.Float64 {
scale := math.Pow(10, 6)
newValue = math.Round(newValue.(float64)*scale) / scale
}

return newValue == toValue.Interface()
Comment thread
ccoVeille marked this conversation as resolved.
Outdated
Comment thread
ccoVeille marked this conversation as resolved.
Outdated
}

// isNumericType returns true if the type is one of:
Expand Down
5 changes: 5 additions & 0 deletions assert/assertions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,11 @@ 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},
{float32(10.1), float64(10.1), true},
{float64(10.1), float32(10.1), true},
{float32(10.123456), float64(10.12345600), true},
{float32(10.123456), float64(10.12345678), false},
{float32(1.0 / 3.0), float64(1.0 / 3.0), false},
Comment thread
ccoVeille marked this conversation as resolved.
}

for _, c := range cases {
Expand Down