mattermost/server/public/model/websocket_message_test.go
Jesse Hallam 67568d558f
Some checks are pending
API / build (push) Waiting to run
Server CI / Compute Go Version (push) Waiting to run
Server CI / Check mocks (push) Blocked by required conditions
Server CI / Check go mod tidy (push) Blocked by required conditions
Server CI / check-style (push) Blocked by required conditions
Server CI / Check serialization methods for hot structs (push) Blocked by required conditions
Server CI / Vet API (push) Blocked by required conditions
Server CI / Check migration files (push) Blocked by required conditions
Server CI / Generate email templates (push) Blocked by required conditions
Server CI / Check store layers (push) Blocked by required conditions
Server CI / Check mmctl docs (push) Blocked by required conditions
Server CI / Postgres with binary parameters (push) Blocked by required conditions
Server CI / Postgres (push) Blocked by required conditions
Server CI / Postgres (FIPS) (push) Blocked by required conditions
Server CI / Generate Test Coverage (push) Blocked by required conditions
Server CI / Run mmctl tests (push) Blocked by required conditions
Server CI / Run mmctl tests (FIPS) (push) Blocked by required conditions
Server CI / Build mattermost server app (push) Blocked by required conditions
Web App CI / check-lint (push) Waiting to run
Web App CI / check-i18n (push) Waiting to run
Web App CI / check-types (push) Waiting to run
Web App CI / test (push) Waiting to run
Web App CI / build (push) Waiting to run
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 13:16:59 -03:00

257 lines
6.6 KiB
Go

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package model
import (
"bytes"
"encoding/json"
"io"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestWebSocketEvent(t *testing.T) {
userId := NewId()
m := NewWebSocketEvent("some_event", NewId(), NewId(), userId, nil, "")
m.Add("RootId", NewId())
user := &User{
Id: userId,
}
m.Add("user", user)
json, err := m.ToJSON()
require.NoError(t, err)
result, err := WebSocketEventFromJSON(bytes.NewReader(json))
require.NoError(t, err)
require.True(t, m.IsValid(), "should be valid")
require.Equal(t, m.GetBroadcast().TeamId, result.GetBroadcast().TeamId, "Team ids do not match")
require.Equal(t, m.GetData()["RootId"], result.GetData()["RootId"], "Root ids do not match")
require.Equal(t, m.GetData()["user"].(*User).Id, result.GetData()["user"].(*User).Id, "User ids do not match")
}
func TestWebSocketEventImmutable(t *testing.T) {
m := NewWebSocketEvent(WebsocketEventPostEdited, NewId(), NewId(), NewId(), nil, "")
newM := m.SetEvent(WebsocketEventPostDeleted)
if newM == m {
require.Fail(t, "pointers should not be the same")
}
require.NotEqual(t, m.EventType(), newM.EventType())
require.Equal(t, newM.EventType(), WebsocketEventPostDeleted)
newM = m.SetSequence(45)
if newM == m {
require.Fail(t, "pointers should not be the same")
}
require.NotEqual(t, m.GetSequence(), newM.GetSequence())
require.Equal(t, newM.GetSequence(), int64(45))
broadcast := &WebsocketBroadcast{}
newM = m.SetBroadcast(broadcast)
if newM == m {
require.Fail(t, "pointers should not be the same")
}
require.NotEqual(t, m.GetBroadcast(), newM.GetBroadcast())
require.Equal(t, newM.GetBroadcast(), broadcast)
data := map[string]any{
"key": "val",
"key2": "val2",
}
newM = m.SetData(data)
if newM == m {
require.Fail(t, "pointers should not be the same")
}
require.NotEqual(t, m, newM)
require.Equal(t, newM.data, data)
require.Equal(t, newM.data, newM.GetData())
mCopy := m.Copy()
if mCopy == m {
require.Fail(t, "pointers should not be the same")
}
require.Equal(t, m, mCopy)
}
func TestWebSocketEventFromJSON(t *testing.T) {
ev, err := WebSocketEventFromJSON(bytes.NewReader([]byte("junk")))
require.Error(t, err)
require.Nil(t, ev, "should not have parsed")
data := []byte(`{"event": "typing", "data": {"key": "val"}, "seq": 45, "broadcast": {"user_id": "userid"}}`)
ev, err = WebSocketEventFromJSON(bytes.NewReader(data))
require.NoError(t, err)
require.NotNil(t, ev, "should have parsed")
require.Equal(t, ev.EventType(), WebsocketEventTyping)
require.Equal(t, ev.GetSequence(), int64(45))
require.Equal(t, ev.data, map[string]any{"key": "val"})
require.Equal(t, ev.GetBroadcast(), &WebsocketBroadcast{UserId: "userid"})
}
func TestWebSocketResponse(t *testing.T) {
m := NewWebSocketResponse("OK", 1, map[string]any{})
e := NewWebSocketError(1, &AppError{})
m.Add("RootId", NewId())
json, err := m.ToJSON()
require.NoError(t, err)
result, err := WebSocketResponseFromJSON(bytes.NewReader(json))
require.NoError(t, err)
json2, err := e.ToJSON()
require.NoError(t, err)
WebSocketResponseFromJSON(bytes.NewReader(json2))
badresult, err := WebSocketResponseFromJSON(bytes.NewReader([]byte("junk")))
require.Error(t, err)
require.Nil(t, badresult, "should not have parsed")
require.True(t, m.IsValid(), "should be valid")
require.Equal(t, m.Data["RootId"], result.Data["RootId"], "Ids do not match")
}
func TestWebSocketEvent_PrecomputeJSON(t *testing.T) {
event := NewWebSocketEvent(WebsocketEventPosted, "foo", "bar", "baz", nil, "")
event = event.SetSequence(7)
before, err := event.ToJSON()
require.NoError(t, err)
event.PrecomputeJSON()
after, err := event.ToJSON()
require.NoError(t, err)
assert.Equal(t, before, after)
}
var stringSink []byte
func BenchmarkWebSocketEvent_ToJSON(b *testing.B) {
event := NewWebSocketEvent(WebsocketEventPosted, "foo", "bar", "baz", nil, "")
for range 100 {
event.GetData()[NewId()] = NewId()
}
b.Run("SerializedNTimes", func(b *testing.B) {
for b.Loop() {
stringSink, _ = event.ToJSON()
}
})
b.Run("PrecomputedNTimes", func(b *testing.B) {
for b.Loop() {
event.PrecomputeJSON()
}
})
b.Run("PrecomputedAndSerializedNTimes", func(b *testing.B) {
for b.Loop() {
event.PrecomputeJSON()
stringSink, _ = event.ToJSON()
}
})
event.PrecomputeJSON()
b.Run("PrecomputedOnceAndSerializedNTimes", func(b *testing.B) {
for b.Loop() {
stringSink, _ = event.ToJSON()
}
})
}
func TestWebsocketBroadcastCopy(t *testing.T) {
w := &WebsocketBroadcast{}
require.Equal(t, w, w.copy())
w = nil
require.Equal(t, w, w.copy())
w = &WebsocketBroadcast{
OmitUsers: map[string]bool{
"aaa": true,
"bbb": true,
"ccc": false,
},
UserId: "aaa",
ChannelId: "bbb",
TeamId: "ccc",
ContainsSanitizedData: true,
ContainsSensitiveData: true,
}
require.Equal(t, w, w.copy())
}
func TestPrecomputedWebSocketEventJSONCopy(t *testing.T) {
p := &precomputedWebSocketEventJSON{}
require.Equal(t, p, p.copy())
p = nil
require.Equal(t, p, p.copy())
p = &precomputedWebSocketEventJSON{
Event: []byte{},
Data: []byte{},
Broadcast: []byte{},
}
require.Equal(t, p, p.copy())
p = &precomputedWebSocketEventJSON{
Event: []byte{'a', 'b', 'c'},
Data: []byte{'d', 'e', 'f'},
Broadcast: []byte{'g', 'h', 'i'},
}
require.Equal(t, p, p.copy())
}
func TestWebSocketEventDeepCopy(t *testing.T) {
omitUsers := map[string]bool{
"user1": true,
"user2": false,
}
broadcast := &WebsocketBroadcast{
OmitUsers: omitUsers,
UserId: "aaa",
ChannelId: "bbb",
TeamId: "ccc",
ContainsSanitizedData: true,
ContainsSensitiveData: true,
OmitConnectionId: "ddd",
}
ev := NewWebSocketEvent("test", "team", "channel", "user", omitUsers, "ddd")
ev.Add("post", &Post{})
ev.SetBroadcast(broadcast)
ev = ev.PrecomputeJSON()
evCopy := ev.DeepCopy()
require.Equal(t, ev, evCopy)
AssertNotSameMap(t, ev.data, evCopy.data)
require.NotSame(t, ev.broadcast, evCopy.broadcast)
require.NotSame(t, ev.precomputedJSON, evCopy.precomputedJSON)
ev.Add("post", &Post{
Id: "test",
})
require.NotEqual(t, ev.data, evCopy.data)
}
var err error
func BenchmarkEncodeJSON(b *testing.B) {
message := NewWebSocketEvent(WebsocketEventUserAdded, "", "channelID", "", nil, "")
message.Add("user_id", "userID")
message.Add("team_id", "teamID")
ev := message.PrecomputeJSON()
var seq int64
enc := json.NewEncoder(io.Discard)
for b.Loop() {
ev = ev.SetSequence(seq)
err = ev.Encode(enc, io.Discard)
seq++
}
}