testify icon indicating copy to clipboard operation
testify copied to clipboard

How to assert the address of 2 pointers are (not) equal?

Open littledot opened this issue 6 years ago • 10 comments

According to the docs, pointers are considered equals as long as their ref'd values are equal.

// NotEqual asserts that the specified values are NOT equal.
//
//    assert.NotEqual(t, obj1, obj2)
//
// Pointer variable equality is determined based on the equality of the
// referenced values (as opposed to the memory addresses).

However, this can be difficult when testing clone functions because in addition to testing the referenced values, I also need to test the memory address are new and not the same.


type A struct {
	i int
}

func (a *A) Clone() *A {
	clone := *a
	return &clone
}

func TestClone(t *testing.T) {
	orig := &A{1}
	copy := orig.Clone()

	assert.Equal(t, *orig, *copy)
	assert.NotEqual(t, orig, copy) // Fail, how to compare memory address values?
}

Are there any functions that compares memory addresses values of pointers?

littledot avatar May 08 '18 00:05 littledot

@littledot As its a pointer, You could just use == operator to verify its different memory.

orig==copy is false and orig==orig is true.

devdinu avatar May 08 '18 07:05 devdinu

Yes I can do == with assert.True(), but the default error log for assert.True() is vague due to a lack of context. Hence I'd like to know if there is a dedicated assert function for comparing memory addresses? Which will also pretty print the pointers on assertion failures.

littledot avatar May 08 '18 08:05 littledot

What are your thoughts on a new assertion function assert.Same(*testing.T, interface{}, interface{}) that simply wraps the == check?

https://play.golang.org/p/ZEzrtMb7oQN

littledot avatar May 10 '18 21:05 littledot

looks good, we also have to check the types of the two pointers, and report properly if its different, and not just print the different address.

devdinu avatar May 11 '18 06:05 devdinu

Any updates on this?

ryanleecode avatar Nov 08 '18 06:11 ryanleecode

Was looking for this today so I took a stab at it based on @littledot's start

gavincabbage avatar Jan 10 '19 02:01 gavincabbage

NotSame would also be great.

juliaogris avatar Sep 09 '19 02:09 juliaogris

Can be closed, Same and NotSame are available.

piepmatz avatar Aug 31 '21 11:08 piepmatz

@devdinu This issue was resolved. Could you close the issue, please?

ilya-korotya avatar Nov 24 '22 17:11 ilya-korotya

Maybe you know how recursive doing Same or NotSame?

antsupovsa avatar Nov 30 '22 10:11 antsupovsa