testify
testify copied to clipboard
Assert equal pointers
I try to test some properties of zap log and I got this:
assert.Same(t, zapcore.ISO8601TimeEncoder, got.EncoderConfig.EncodeTime)
Error: Not same:
expected: 0x6bb840 (func(time.Time, zapcore.PrimitiveArrayEncoder))(0x6bb840)
actual : 0x6bb840 (zapcore.TimeEncoder)(0x6bb840)
In this test the object types are different, but the pointer (address) are same.
Internally the function Same call function samePointers, but this function compare two object pointers and not if the address of each object are equal.
https://github.com/stretchr/testify/blob/6241f9ab994219cafb009b160a20acf4a62063aa/assert/assertions.go#L409
For me its ok this behavior, but I propose a new assert, something like assert.SameAddress(t TestingT, referenceObject, actualObject interface{})
This new assert just check if de uintptr is the same value of referenceObject and actualObject using the function reflect.ValueOf(i interface{}).Pointer()
go-testdeep allows this: https://go.dev/play/p/6QAY0tfAOoQ
https://pkg.go.dev/reflect#Value.Pointer says
It panics if v's Kind is not Chan, Func, Map, Pointer, Slice, or UnsafePointer.
Also assert.SameAddress adds new exported API.
An improvement without adding new API might be to change samePointers to use Value.Pointer for Chan, Func, Map, Pointer, Slice, or UnsafePointer and == for others like before.
I've created #1296
OTOH it works as documented
// Same asserts that two pointers reference the same object.
//
// assert.Same(t, ptr1, ptr2)
//
// Both arguments must be pointer variables. Pointer variable sameness is
// determined based on the equality of both type and value.
and users may always do
assert.Equal(t, reflect.ValueOf(expected).Pointer(), reflect.ValueOf(actual).Pointer())
https://go.dev/play/p/6P1wnqKl4TV