Skip to content

Commit

Permalink
Use reflect.Value.Pointer() to compare pointers
Browse files Browse the repository at this point in the history
Fixes #1076
  • Loading branch information
AlexanderYastrebov committed Oct 16, 2023
1 parent 4ae48e9 commit 2f1c840
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 8 deletions.
12 changes: 4 additions & 8 deletions assert/assertions.go
Expand Up @@ -489,17 +489,13 @@ func NotSame(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}
// they point to the same object
func samePointers(first, second interface{}) bool {
firstPtr, secondPtr := reflect.ValueOf(first), reflect.ValueOf(second)
if firstPtr.Kind() != reflect.Ptr || secondPtr.Kind() != reflect.Ptr {
return false
}

firstType, secondType := reflect.TypeOf(first), reflect.TypeOf(second)
if firstType != secondType {
switch firstPtr.Kind() {
case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.Slice:
return firstPtr.Kind() == secondPtr.Kind() && firstPtr.Pointer() == secondPtr.Pointer()
default:
return false
}

// compare pointer addresses
return first == second
}

// formatUnequalValues takes two values of arbitrary types and returns string
Expand Down
55 changes: 55 additions & 0 deletions assert/assertions_test.go
Expand Up @@ -547,6 +547,11 @@ func TestNotSame(t *testing.T) {

func Test_samePointers(t *testing.T) {
p := ptr(2)
c1, c2 := make(chan int), make(chan int)
f1, f2 := func() {}, func() {}
m1, m2 := map[int]int{1: 2}, map[int]int{1: 2}
p1, p2 := ptr(3), ptr(3)
s1, s2 := []int{4, 5}, []int{4, 5}

type args struct {
first interface{}
Expand Down Expand Up @@ -582,6 +587,56 @@ func Test_samePointers(t *testing.T) {
args: args{first: [2]int{1, 2}, second: []int{1, 2}},
assertion: False,
},
{
name: "chan(1) == chan(1)",
args: args{first: c1, second: c1},
assertion: True,
},
{
name: "func(1) == func(1)",
args: args{first: f1, second: f1},
assertion: True,
},
{
name: "map(1) == map(1)",
args: args{first: m1, second: m1},
assertion: True,
},
{
name: "ptr(1) == ptr(1)",
args: args{first: p1, second: p1},
assertion: True,
},
{
name: "slice(1) == slice(1)",
args: args{first: s1, second: s1},
assertion: True,
},
{
name: "chan(1) != chan(2)",
args: args{first: c1, second: c2},
assertion: False,
},
{
name: "func(1) != func(2)",
args: args{first: f1, second: f2},
assertion: False,
},
{
name: "map(1) != map(2)",
args: args{first: m1, second: m2},
assertion: False,
},
{
name: "ptr(1) != ptr(2)",
args: args{first: p1, second: p2},
assertion: False,
},
{
name: "slice(1) != slice(2)",
args: args{first: s1, second: s2},
assertion: False,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down

0 comments on commit 2f1c840

Please sign in to comment.