-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathevents_test.go
118 lines (90 loc) · 2.1 KB
/
events_test.go
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package events
import (
"context"
"fmt"
"testing"
"time"
)
// Sequential write
func TestSequentialWrite(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
e := EventEmitter{}
expectedClients := 10
expectedEvents := 100
chs := make([]<-chan Event, expectedClients)
for i := 0; i < expectedClients; i++ {
chs[i] = e.Subscribe(ctx)
}
go func() {
for i := 0; i < expectedEvents; i++ {
e.Emit(ctx, fmt.Sprintf("%d", i))
}
}()
for i := 0; i < expectedClients; i++ {
for j := 0; j < expectedEvents; j++ {
var item interface{}
select {
case item = <-chs[i]:
case <-time.After(time.Second * 2):
t.Fatalf("timeout while waiting for event: %d %d", i, j)
}
s := item.(string)
if s != fmt.Sprintf("%d", j) {
t.Fatalf("%s should be equal to %d", s, j)
}
}
}
cancel()
<-time.After(time.Millisecond * 100)
for i := 0; i < expectedClients; i++ {
for range chs[i] {
t.Fatal("should not occur")
}
}
}
func TestMissingListeners(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
e := EventEmitter{}
expectedEvents := 10
go func() {
for i := 0; i < expectedEvents; i++ {
e.Emit(ctx, fmt.Sprintf("%d", i))
}
<-time.After(10 * time.Millisecond)
}()
<-time.After(100 * time.Millisecond)
}
func TestPartialListeners(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
e := EventEmitter{}
go func() {
for i := 0; i < 5; i++ {
e.Emit(ctx, fmt.Sprintf("%d", i))
}
}()
<-time.After(time.Millisecond * 100)
subCtx, subCancel := context.WithCancel(context.Background())
sub := e.Subscribe(subCtx)
<-time.After(time.Millisecond * 100)
for i := 5; i < 10; i++ {
e.Emit(ctx, fmt.Sprintf("%d", i))
}
<-time.After(time.Millisecond * 100)
for i := 5; i < 10; i++ {
item := <-sub
itemStr, ok := item.(string)
if !ok {
t.Fatalf("unable to cast")
}
if itemStr != fmt.Sprintf("%d", i) {
t.Errorf("(%s) should be equal to (%d)", itemStr, i)
}
}
<-time.After(time.Second)
subCancel()
for range sub {
t.Fatalf("this should not happen")
}
}