websocket_message_test.go 2.33 KB
Newer Older
1
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
2 3 4 5 6 7 8
// See License.txt for license information.

package model

import (
	"strings"
	"testing"
Chris's avatar
Chris committed
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 16 17 18 19 20 21 22 23 24 25 26 27
	m.Add("RootId", NewId())
	json := m.ToJson()
	result := WebSocketEventFromJson(strings.NewReader(json))

	badresult := WebSocketEventFromJson(strings.NewReader("junk"))
	if badresult != nil {
		t.Fatal("should not have parsed")
	}

	if !m.IsValid() {
		t.Fatal("should be valid")
	}

28
	if m.Broadcast.TeamId != result.Broadcast.TeamId {
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
		t.Fatal("Ids do not match")
	}

	if m.Data["RootId"] != result.Data["RootId"] {
		t.Fatal("Ids do not match")
	}
}

func TestWebSocketResponse(t *testing.T) {
	m := NewWebSocketResponse("OK", 1, map[string]interface{}{})
	e := NewWebSocketError(1, &AppError{})
	m.Add("RootId", NewId())
	json := m.ToJson()
	result := WebSocketResponseFromJson(strings.NewReader(json))
	json2 := e.ToJson()
	WebSocketResponseFromJson(strings.NewReader(json2))

	badresult := WebSocketResponseFromJson(strings.NewReader("junk"))
	if badresult != nil {
		t.Fatal("should not have parsed")
	}

	if !m.IsValid() {
		t.Fatal("should be valid")
	}

	if m.Data["RootId"] != result.Data["RootId"] {
		t.Fatal("Ids do not match")
	}
}
Chris's avatar
Chris committed
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104

func TestWebSocketEvent_PrecomputeJSON(t *testing.T) {
	event := NewWebSocketEvent(WEBSOCKET_EVENT_POSTED, "foo", "bar", "baz", nil)
	event.Sequence = 7

	before := event.ToJson()
	event.PrecomputeJSON()
	after := event.ToJson()

	assert.JSONEq(t, before, after)
}

var stringSink string

func BenchmarkWebSocketEvent_ToJson(b *testing.B) {
	event := NewWebSocketEvent(WEBSOCKET_EVENT_POSTED, "foo", "bar", "baz", nil)
	for i := 0; i < 100; i++ {
		event.Data[NewId()] = NewId()
	}

	b.Run("SerializedNTimes", func(b *testing.B) {
		for i := 0; i < b.N; i++ {
			stringSink = event.ToJson()
		}
	})

	b.Run("PrecomputedNTimes", func(b *testing.B) {
		for i := 0; i < b.N; i++ {
			event.PrecomputeJSON()
		}
	})

	b.Run("PrecomputedAndSerializedNTimes", func(b *testing.B) {
		for i := 0; i < b.N; i++ {
			event.PrecomputeJSON()
			stringSink = event.ToJson()
		}
	})

	event.PrecomputeJSON()
	b.Run("PrecomputedOnceAndSerializedNTimes", func(b *testing.B) {
		for i := 0; i < b.N; i++ {
			stringSink = event.ToJson()
		}
	})
}