aboutsummaryrefslogtreecommitdiff
path: root/jsonrpc/client/message_dispatcher_test.go
blob: 7cc1366e76c2069322462bf36a242688c4822dfb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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
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
package client

import (
	// "sync"
	// "sync/atomic"

	"sync"
	"sync/atomic"
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestDispatchToChannel(t *testing.T) {

	messageDispatcher := newMessageDispatcher[int, int](10)

	chanKey := 1
	rx := messageDispatcher.register(chanKey)

	chanKey2 := 2
	rx2 := messageDispatcher.register(chanKey2)

	var wg sync.WaitGroup

	wg.Add(1)
	go func() {
		for i := 0; i < 50; i++ {
			err := messageDispatcher.disptach(chanKey, i)
			assert.Nil(t, err)
		}

		messageDispatcher.unregister(chanKey)
		wg.Done()
	}()

	wg.Add(1)
	go func() {
		for i := 0; i < 50; i++ {
			err := messageDispatcher.disptach(chanKey2, i)
			assert.Nil(t, err)
		}

		messageDispatcher.unregister(chanKey2)
		wg.Done()
	}()

	var receivedItem atomic.Int32

	wg.Add(1)
	go func() {
		for range rx {
			receivedItem.Add(1)
		}
		wg.Done()
	}()

	wg.Add(1)
	go func() {
		for range rx2 {
			receivedItem.Add(1)
		}
		wg.Done()
	}()

	wg.Wait()
	assert.Equal(t, receivedItem.Load(), int32(100))
}

func TestUnregisterChannel(t *testing.T) {
	messageDispatcher := newMessageDispatcher[int, int](1)

	chanKey := 1
	rx := messageDispatcher.register(chanKey)

	messageDispatcher.unregister(chanKey)
	assert.Equal(t, messageDispatcher.length(), 0, "channels should be empty")

	_, ok := <-rx
	assert.False(t, ok, "chan closed")

	err := messageDispatcher.disptach(chanKey, 1)
	assert.NotNil(t, err)
}

func TestClearChannels(t *testing.T) {

	messageDispatcher := newMessageDispatcher[int, int](1)

	chanKey := 1
	rx := messageDispatcher.register(chanKey)

	messageDispatcher.clear()
	assert.Equal(t, messageDispatcher.length(), 0, "channels should be empty")

	_, ok := <-rx
	assert.False(t, ok, "chan closed")

	err := messageDispatcher.disptach(chanKey, 1)
	assert.NotNil(t, err)
}