-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathserver_test.go
313 lines (246 loc) · 8.14 KB
/
server_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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
package sse_test
import (
"context"
"errors"
"fmt"
"io"
"log"
"math/rand"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"github.com/tmaxmax/go-sse"
"github.com/tmaxmax/go-sse/internal/tests"
)
type mockProvider struct {
SubError error
Closed chan struct{}
Pub *sse.Message
PubTopics []string
Sub sse.Subscription
Subscribed bool
Stopped bool
Published bool
}
func (m *mockProvider) Subscribe(ctx context.Context, sub sse.Subscription) error {
m.Subscribed = true
if m.SubError != nil {
return m.SubError
}
defer close(m.Closed)
m.Sub = sub
e := &sse.Message{}
e.AppendData("hello")
if err := sub.Client.Send(e); err != nil {
return fmt.Errorf("send failed: %w", err)
}
if err := sub.Client.Flush(); err != nil {
return fmt.Errorf("flush failed: %w", err)
}
<-ctx.Done()
return nil
}
func (m *mockProvider) Publish(msg *sse.Message, topics []string) error {
m.Pub = msg
m.PubTopics = topics
m.Published = true
return nil
}
func (m *mockProvider) Shutdown(_ context.Context) error {
m.Stopped = true
return nil
}
var _ sse.Provider = (*mockProvider)(nil)
func newMockProvider(tb testing.TB, subErr error) *mockProvider {
tb.Helper()
return &mockProvider{Closed: make(chan struct{}), SubError: subErr}
}
type logger struct {
l *log.Logger
}
func quoteString(s string) string {
if strings.ContainsAny(s, " \n\t") || s == "" {
return strconv.Quote(s)
}
return s
}
func (l logger) Log(_ context.Context, level sse.LogLevel, msg string, data map[string]any) {
levelStr := ""
switch level {
case sse.LogLevelInfo:
levelStr = "INFO"
case sse.LogLevelWarn:
levelStr = "WARN"
case sse.LogLevelError:
levelStr = "ERROR"
}
output := fmt.Sprintf("level=%s msg=%q", levelStr, msg)
if e, ok := data["err"]; ok {
output += fmt.Sprintf(" err=%s", quoteString(e.(error).Error()))
}
if ts, ok := data["topics"]; ok {
topics := ts.([]string)
for i, t := range topics {
topics[i] = quoteString(t)
}
output += fmt.Sprintf(" topics=%s", strings.Join(topics, ","))
}
if id, ok := data["lastEventID"]; ok {
output += fmt.Sprintf(" lastEventID=%s", quoteString(id.(sse.EventID).String()))
}
l.l.Println(output)
}
func newMockLogger(w io.Writer) sse.Logger {
return logger{l: log.New(w, "", 0)}
}
func TestServer_ShutdownPublish(t *testing.T) {
t.Parallel()
p := &mockProvider{}
s := &sse.Server{Provider: p}
_ = s.Publish(&sse.Message{})
tests.Expect(t, p.Published, "Publish wasn't called")
tests.DeepEqual(t, []any{*p.Pub, p.PubTopics}, []any{sse.Message{}, []string{sse.DefaultTopic}}, "incorrect message")
p.Published = false
_ = s.Publish(&sse.Message{}, "topic")
tests.Expect(t, p.Published, "Publish wasn't called")
tests.DeepEqual(t, []any{*p.Pub, p.PubTopics}, []any{sse.Message{}, []string{"topic"}}, "incorrect message")
_ = s.Shutdown(context.Background())
tests.Expect(t, p.Stopped, "Stop wasn't called")
}
func request(tb testing.TB, method, address string, body io.Reader) (*http.Request, context.CancelFunc) { //nolint
tb.Helper()
r := httptest.NewRequest(method, address, body)
ctx, cancel := context.WithCancel(r.Context())
return r.WithContext(ctx), cancel
}
func TestServer_ServeHTTP(t *testing.T) {
t.Parallel()
rec := httptest.NewRecorder()
req, cancel := request(t, "", "http://localhost", nil)
defer cancel()
p := newMockProvider(t, nil)
req.Header.Set("Last-Event-ID", "5")
go cancel()
sb := &strings.Builder{}
(&sse.Server{Provider: p, Logger: newMockLogger(sb)}).ServeHTTP(rec, req)
tests.Expect(t, p.Subscribed, "Subscribe wasn't called")
tests.Equal(t, p.Sub.LastEventID, sse.ID("5"), "Invalid last event ID received")
tests.Equal(t, rec.Body.String(), "data: hello\n\n", "Invalid response body")
tests.Equal(t, rec.Code, http.StatusOK, "invalid response code")
tests.Equal(t, sb.String(), "level=INFO msg=\"sse: starting new session\"\nlevel=INFO msg=\"sse: subscribing session\" topics=\"\" lastEventID=5\nlevel=INFO msg=\"sse: session ended\"\n", "invalid log output")
}
type noFlusher struct {
http.ResponseWriter
}
func TestServer_ServeHTTP_unsupportedRespWriter(t *testing.T) {
t.Parallel()
rec := httptest.NewRecorder()
req, cancel := request(t, "", "http://localhost", nil)
defer cancel()
p := newMockProvider(t, nil)
sb := &strings.Builder{}
(&sse.Server{Provider: p, Logger: newMockLogger(sb)}).ServeHTTP(noFlusher{rec}, req)
tests.Equal(t, rec.Code, http.StatusInternalServerError, "invalid response code")
tests.Equal(t, rec.Body.String(), "Server-sent events unsupported\n", "invalid response body")
tests.Equal(t, sb.String(), "level=INFO msg=\"sse: starting new session\"\nlevel=ERROR msg=\"sse: unsupported\" err=\"go-sse.server: upgrade unsupported\"\n", "invalid log output")
}
func TestServer_ServeHTTP_subscribeError(t *testing.T) {
t.Parallel()
rec := httptest.NewRecorder()
req, _ := http.NewRequest("", "http://localhost", http.NoBody)
p := newMockProvider(t, errors.New("can't subscribe"))
sb := &strings.Builder{}
(&sse.Server{Provider: p, Logger: newMockLogger(sb)}).ServeHTTP(rec, req)
tests.Equal(t, rec.Body.String(), p.SubError.Error()+"\n", "invalid response body")
tests.Equal(t, rec.Code, http.StatusInternalServerError, "invalid response code")
tests.Equal(t, sb.String(), "level=INFO msg=\"sse: starting new session\"\nlevel=INFO msg=\"sse: subscribing session\" topics=\"\" lastEventID=\"\"\nlevel=ERROR msg=\"sse: subscribe error\" err=\"can't subscribe\"\n", "invalid log output")
}
func TestServer_OnSession(t *testing.T) {
t.Parallel()
t.Run("Invalid", func(t *testing.T) {
rec := httptest.NewRecorder()
req := httptest.NewRequest("", "/", http.NoBody)
p := newMockProvider(t, nil)
sb := &strings.Builder{}
(&sse.Server{
Provider: p,
Logger: newMockLogger(sb),
OnSession: func(s *sse.Session) (sse.Subscription, bool) {
http.Error(s.Res, "this is invalid", http.StatusBadRequest)
return sse.Subscription{}, false
},
}).ServeHTTP(rec, req)
tests.Equal(t, rec.Body.String(), "this is invalid\n", "invalid response body")
tests.Equal(t, rec.Code, http.StatusBadRequest, "invalid response code")
tests.Equal(t, sb.String(), "level=INFO msg=\"sse: starting new session\"\nlevel=WARN msg=\"sse: invalid subscription\"\n", "invalid log output")
})
}
type flushResponseWriter interface {
http.Flusher
http.ResponseWriter
}
type responseWriterErr struct {
flushResponseWriter
}
func (r *responseWriterErr) Write(p []byte) (int, error) {
n, _ := r.flushResponseWriter.Write(p)
return n, errors.New("")
}
func TestServer_ServeHTTP_connectionError(t *testing.T) {
t.Parallel()
rec := httptest.NewRecorder()
req, _ := http.NewRequest("", "http://localhost", http.NoBody)
p := newMockProvider(t, nil)
(&sse.Server{Provider: p}).ServeHTTP(&responseWriterErr{rec}, req)
_, ok := <-p.Closed
tests.Expect(t, !ok, "request error should not block server")
}
func getMessage(tb testing.TB) *sse.Message {
tb.Helper()
m := &sse.Message{
ID: sse.ID(strconv.Itoa(rand.Int())),
Type: sse.Type("test"),
}
m.AppendData("Hello world!", "Nice to see you all.")
return m
}
type discardResponseWriter struct {
w io.Writer
h http.Header
c int
}
func (d *discardResponseWriter) Header() http.Header { return d.h }
func (d *discardResponseWriter) Write(b []byte) (int, error) { return d.w.Write(b) }
func (d *discardResponseWriter) WriteHeader(code int) { d.c = code }
func (d *discardResponseWriter) Flush() {}
func getRequest(tb testing.TB) (w *discardResponseWriter, r *http.Request) {
tb.Helper()
w = &discardResponseWriter{w: io.Discard, h: make(http.Header)}
r = httptest.NewRequest("", "http://localhost", http.NoBody)
return
}
func benchmarkServer(b *testing.B, conns int) {
b.Helper()
s := &sse.Server{}
b.Cleanup(func() { _ = s.Shutdown(context.Background()) })
m := getMessage(b)
for i := 0; i < conns; i++ {
w, r := getRequest(b)
go s.ServeHTTP(w, r)
}
b.ResetTimer()
b.ReportAllocs()
for n := 0; n < b.N; n++ {
_ = s.Publish(m)
}
}
func BenchmarkServer(b *testing.B) {
conns := [...]int{10, 100, 1000, 10000, 20000, 50000, 100000}
for _, c := range conns {
b.Run(strconv.Itoa(c), func(b *testing.B) {
benchmarkServer(b, c)
})
}
}