github.com/wgh-/mattermost-server@v4.8.0-rc2+incompatible/model/websocket_message_test.go (about) 1 // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. 2 // See License.txt for license information. 3 4 package model 5 6 import ( 7 "strings" 8 "testing" 9 10 "github.com/stretchr/testify/assert" 11 ) 12 13 func TestWebSocketEvent(t *testing.T) { 14 m := NewWebSocketEvent("some_event", NewId(), NewId(), NewId(), nil) 15 m.Add("RootId", NewId()) 16 json := m.ToJson() 17 result := WebSocketEventFromJson(strings.NewReader(json)) 18 19 badresult := WebSocketEventFromJson(strings.NewReader("junk")) 20 if badresult != nil { 21 t.Fatal("should not have parsed") 22 } 23 24 if !m.IsValid() { 25 t.Fatal("should be valid") 26 } 27 28 if m.Broadcast.TeamId != result.Broadcast.TeamId { 29 t.Fatal("Ids do not match") 30 } 31 32 if m.Data["RootId"] != result.Data["RootId"] { 33 t.Fatal("Ids do not match") 34 } 35 } 36 37 func TestWebSocketResponse(t *testing.T) { 38 m := NewWebSocketResponse("OK", 1, map[string]interface{}{}) 39 e := NewWebSocketError(1, &AppError{}) 40 m.Add("RootId", NewId()) 41 json := m.ToJson() 42 result := WebSocketResponseFromJson(strings.NewReader(json)) 43 json2 := e.ToJson() 44 WebSocketResponseFromJson(strings.NewReader(json2)) 45 46 badresult := WebSocketResponseFromJson(strings.NewReader("junk")) 47 if badresult != nil { 48 t.Fatal("should not have parsed") 49 } 50 51 if !m.IsValid() { 52 t.Fatal("should be valid") 53 } 54 55 if m.Data["RootId"] != result.Data["RootId"] { 56 t.Fatal("Ids do not match") 57 } 58 } 59 60 func TestWebSocketEvent_PrecomputeJSON(t *testing.T) { 61 event := NewWebSocketEvent(WEBSOCKET_EVENT_POSTED, "foo", "bar", "baz", nil) 62 event.Sequence = 7 63 64 before := event.ToJson() 65 event.PrecomputeJSON() 66 after := event.ToJson() 67 68 assert.JSONEq(t, before, after) 69 } 70 71 var stringSink string 72 73 func BenchmarkWebSocketEvent_ToJson(b *testing.B) { 74 event := NewWebSocketEvent(WEBSOCKET_EVENT_POSTED, "foo", "bar", "baz", nil) 75 for i := 0; i < 100; i++ { 76 event.Data[NewId()] = NewId() 77 } 78 79 b.Run("SerializedNTimes", func(b *testing.B) { 80 for i := 0; i < b.N; i++ { 81 stringSink = event.ToJson() 82 } 83 }) 84 85 b.Run("PrecomputedNTimes", func(b *testing.B) { 86 for i := 0; i < b.N; i++ { 87 event.PrecomputeJSON() 88 } 89 }) 90 91 b.Run("PrecomputedAndSerializedNTimes", func(b *testing.B) { 92 for i := 0; i < b.N; i++ { 93 event.PrecomputeJSON() 94 stringSink = event.ToJson() 95 } 96 }) 97 98 event.PrecomputeJSON() 99 b.Run("PrecomputedOnceAndSerializedNTimes", func(b *testing.B) { 100 for i := 0; i < b.N; i++ { 101 stringSink = event.ToJson() 102 } 103 }) 104 }