-
Notifications
You must be signed in to change notification settings - Fork 0
/
broker_test.go
136 lines (105 loc) · 2.46 KB
/
broker_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
128
129
130
131
132
133
134
135
136
package gosse
import (
"bufio"
"context"
"fmt"
"github.com/go-redis/redis/v8"
"log"
"net/http"
"strings"
"testing"
"time"
)
/**
Tests should be run by running the script test.sh which will run a redis docker container.
*/
const httpPort = "48923"
var redisClientA = redis.NewClient(&redis.Options{
Addr: "127.0.0.1:44293",
})
var redisClientB = redis.NewClient(&redis.Options{
Addr: "127.0.0.1:44293",
})
var redisClientC = redis.NewClient(&redis.Options{
Addr: "127.0.0.1:44293",
})
func TestBroadcast(t *testing.T) {
a := NewBroker(redisClientA)
b := NewBroker(redisClientB)
c := NewBroker(redisClientC)
server := &http.Server{Addr: ":" + httpPort}
http.HandleFunc("/events", a.HttpHandler())
go func() {
err := server.ListenAndServe()
if err != nil {
log.Println(err)
}
}()
receivedEvent := make(chan string, 4)
resp, err := http.Get(fmt.Sprintf("http://localhost:%s/events?stream_id=aaa", httpPort))
if err != nil {
t.Fatal(err)
}
go func() {
scanner := bufio.NewScanner(resp.Body)
scanner.Split(doubleNewLineSplitFunc)
for {
hasData := scanner.Scan()
if !hasData {
break
}
receivedEvent <- scanner.Text()
}
}()
err = a.Broadcast("aaa", "my_event_1", "Yay. It works! 1")
if err != nil {
t.Fatal(err)
}
err = b.Broadcast("aaa", "my_event_2", "Yay. It works! 2")
if err != nil {
t.Fatal(err)
}
err = c.Broadcast("aaa", "my_event_3", "Yay. It works! 3")
if err != nil {
t.Fatal(err)
}
select {
case <-receivedEvent:
case <-time.After(time.Millisecond * 50):
t.Fatal("took too long to receive event first event")
}
select {
case <-receivedEvent:
case <-time.After(time.Millisecond * 50):
t.Fatal("took too long to receive second event")
}
select {
case <-receivedEvent:
case <-time.After(time.Millisecond * 50):
t.Fatal("took too long to receive third event")
}
err = resp.Body.Close()
if err != nil {
t.Fatal(err)
}
err = server.Shutdown(context.Background())
if err != nil {
t.Fatal(err)
}
}
// https://stackoverflow.com/a/33069759/6716264
func doubleNewLineSplitFunc(data []byte, atEOF bool) (advance int, token []byte, err error) {
// Return nothing if at end of file and no data passed
if atEOF && len(data) == 0 {
return 0, nil, nil
}
// Find the index of the input with 2 new lines
if i := strings.Index(string(data), "\n\n"); i >= 0 {
return i + 1, data[0:i], nil
}
// If at end of file with data return the data
if atEOF {
return len(data), data, nil
}
return
}