mattermost/server/public/model/map.go

13 lines
254 B
Go
Raw Permalink Normal View History

Introduce model.AssertNotSameMap (#34058) When we last bumped dependencies in https://github.com/mattermost/mattermost/pull/30005, `assert.NotSame` for maps started failing because of the change in https://github.com/stretchr/testify/issues/1661. The reality was that the previous assertion was silently skipped, and just now reporting as much. Here's an illustrative example: ```go package main import ( "maps" "testing" "github.com/stretchr/testify/assert" ) func TestClonedMapsAreNotSame(t *testing.T) { original := map[string]int{ "a": 1, "b": 2, "c": 3, } cloned := maps.Clone(original) assert.NotSame(t, original, cloned) } func TestSameMaps(t *testing.T) { original := map[string]int{ "a": 1, "b": 2, "c": 3, } cloned := original assert.Same(t, original, cloned) cloned["d"] = 4 assert.Same(t, original, cloned) } ``` which fails with the following after the original dependency update: ``` --- FAIL: TestClonedMapsAreNotSame (0.00s) main_test.go:19: Error Trace: /Users/jesse/tmp/testify/main_test.go:19 Error: Both arguments must be pointers Test: TestClonedMapsAreNotSame --- FAIL: TestSameMaps (0.00s) main_test.go:30: Error Trace: /Users/jesse/tmp/testify/main_test.go:30 Error: Both arguments must be pointers Test: TestSameMaps main_test.go:33: Error Trace: /Users/jesse/tmp/testify/main_test.go:33 Error: Both arguments must be pointers Test: TestSameMaps FAIL FAIL testassertequal 0.149s FAIL ``` However, instead of fixing the underlying issue, we took the address of those variables and kept using `assert.Same`. This isn't meaningful, since it doesn't directly compare the underlying pointers of the map objects in question, just the address of the pointers to those maps. Here's the output after taking the address (e.g. `&original` and `&cloned`): ``` --- FAIL: TestSameMaps (0.00s) main_test.go:30: Error Trace: /Users/jesse/tmp/testify/main_test.go:30 Error: Not same: expected: 0x14000070170 &map[string]int{"a":1, "b":2, "c":3} actual : 0x14000070178 &map[string]int{"a":1, "b":2, "c":3} Test: TestSameMaps main_test.go:33: Error Trace: /Users/jesse/tmp/testify/main_test.go:33 Error: Not same: expected: 0x14000070170 &map[string]int{"a":1, "b":2, "c":3, "d":4} actual : 0x14000070178 &map[string]int{"a":1, "b":2, "c":3, "d":4} Test: TestSameMaps FAIL FAIL testassertequal 0.157s FAIL ``` They are obviously the same map, since modifying `cloned` modified the original, yet `assert.Same` thinks they are different (because the pointe values are indeed different). (`assert.NotSame` "passes", but for the wrong reasons.) To fix this, introduce `model.AssertNotSameMap` to check this correctly.
2025-10-27 12:16:59 -04:00
package model
import (
"reflect"
"testing"
"github.com/stretchr/testify/assert"
)
func AssertNotSameMap[K comparable, V any](t *testing.T, a, b map[K]V) {
assert.False(t, reflect.ValueOf(a).UnsafePointer() == reflect.ValueOf(b).UnsafePointer())
}