-
-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathbus_test.go
127 lines (97 loc) · 1.96 KB
/
bus_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 messagebus
import (
"errors"
"fmt"
"runtime"
"sync"
"testing"
)
func TestNew(t *testing.T) {
bus := New(runtime.NumCPU())
if bus == nil {
t.Fail()
}
}
func TestSubscribe(t *testing.T) {
bus := New(runtime.NumCPU())
if bus.Subscribe("test", func() {}) != nil {
t.Fail()
}
if bus.Subscribe("test", 2) == nil {
t.Fail()
}
}
func TestUnsubscribe(t *testing.T) {
bus := New(runtime.NumCPU())
handler := func() {}
if err := bus.Subscribe("test", handler); err != nil {
t.Fatal(err)
}
if err := bus.Unsubscribe("test", handler); err != nil {
fmt.Println(err)
t.Fail()
}
if err := bus.Unsubscribe("non-existed", func() {}); err == nil {
fmt.Println(err)
t.Fail()
}
}
func TestClose(t *testing.T) {
bus := New(runtime.NumCPU())
handler := func() {}
if err := bus.Subscribe("test", handler); err != nil {
t.Fatal(err)
}
original, ok := bus.(*messageBus)
if !ok {
fmt.Println("Could not cast message bus to its original type")
t.Fail()
}
if 0 == len(original.handlers) {
fmt.Println("Did not subscribed handler to topic")
t.Fail()
}
bus.Close("test")
if 0 != len(original.handlers) {
fmt.Println("Did not unsubscribed handlers from topic")
t.Fail()
}
}
func TestPublish(t *testing.T) {
bus := New(runtime.NumCPU())
var wg sync.WaitGroup
wg.Add(2)
first := false
second := false
if err := bus.Subscribe("topic", func(v bool) {
defer wg.Done()
first = v
}); err != nil {
t.Fatal(err)
}
if err := bus.Subscribe("topic", func(v bool) {
defer wg.Done()
second = v
}); err != nil {
t.Fatal(err)
}
bus.Publish("topic", true)
wg.Wait()
if first == false || second == false {
t.Fail()
}
}
func TestHandleError(t *testing.T) {
bus := New(runtime.NumCPU())
if err := bus.Subscribe("topic", func(out chan<- error) {
out <- errors.New("I do throw error")
}); err != nil {
t.Fatal(err)
}
out := make(chan error)
defer close(out)
bus.Publish("topic", out)
if <-out == nil {
t.Fail()
}
}