testify icon indicating copy to clipboard operation
testify copied to clipboard

Assert equal pointers

Open rthier opened this issue 4 years ago • 4 comments

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()

rthier avatar May 18 '21 18:05 rthier

go-testdeep allows this: https://go.dev/play/p/6QAY0tfAOoQ

ypotest avatar Jan 09 '22 21:01 ypotest

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.

AlexanderYastrebov avatar Nov 08 '22 13:11 AlexanderYastrebov

I've created #1296

AlexanderYastrebov avatar Nov 08 '22 14:11 AlexanderYastrebov

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

AlexanderYastrebov avatar Nov 08 '22 22:11 AlexanderYastrebov