-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobservable_test.go
127 lines (107 loc) · 2.24 KB
/
observable_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
119
120
121
122
123
124
125
126
127
package observable
import (
"math/rand"
"sync"
"testing"
"time"
)
func TestObservable(t *testing.T) {
GroupId := ID(rand.Intn(1000))
MagicWord := rand.Intn(10000)
obs := NewGroup[int]()
var waitGroup sync.WaitGroup
sub1 := obs.Subscribe(GroupId)
waitGroup.Add(1)
go func() {
defer waitGroup.Done()
for i := range sub1.Observe() {
if i != MagicWord {
t.Errorf("expected %d, got %d", MagicWord, i)
}
sub1.Unsubscribe()
}
}()
sub2 := obs.Subscribe(GroupId)
waitGroup.Add(1)
go func() {
defer waitGroup.Done()
for i := range sub2.Observe() {
if i != MagicWord {
t.Errorf("expected %d, got %d", MagicWord, i)
}
sub2.Unsubscribe()
}
}()
obs.Send(GroupId, MagicWord, SendOption{
Timeout: time.Second,
})
done := make(chan struct{}, 1)
go func() {
waitGroup.Wait()
done <- struct{}{}
}()
select {
case <-done:
close(done)
case <-time.After(30 * time.Second):
t.Fatalf("timeout")
}
if count, ok := obs.SubscriptionCount(GroupId); ok {
if count != 0 {
t.Errorf("expected 0, got %d", count)
}
} else {
t.Error("expected true, got false")
}
}
func TestTimeout(t *testing.T) {
GroupId := ID(rand.Intn(1000))
MagicWord := rand.Intn(10000)
obs := NewGroup[int]()
sub1 := obs.Subscribe(GroupId)
go func() {
for i := range sub1.Observe() {
if i != MagicWord {
t.Errorf("expected %d, got %d", MagicWord, i)
}
}
}()
sub2 := obs.Subscribe(GroupId)
go func() {
for range sub2.Observe() {
for i := range sub2.Observe() {
if i != MagicWord {
t.Errorf("expected %d, got %d", MagicWord, i)
}
}
}
}()
obs.Subscribe(GroupId)
if count, ok := obs.SubscriptionCount(GroupId); ok {
if count != 3 {
t.Errorf("expected 3, got %d", count)
}
} else {
t.Error("expected true, got false")
}
obs.Send(GroupId, MagicWord, SendOption{
Timeout: time.Second,
})
time.Sleep(3 * time.Second)
if count, ok := obs.SubscriptionCount(GroupId); ok {
if count != 2 {
t.Errorf("expected 2, got %d", count)
}
} else {
t.Error("expected true, got false")
}
sub1.Unsubscribe()
sub2.Unsubscribe()
if count, ok := obs.SubscriptionCount(GroupId); ok {
if count != 0 {
t.Errorf("expected 0, got %d", count)
}
} else {
t.Error("expected true, got false")
}
}