-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcontroller_test.go
438 lines (369 loc) · 10 KB
/
controller_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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
package fir
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"strings"
"sync"
"testing"
"time"
"github.com/gorilla/websocket"
"github.com/hashicorp/go-cleanhttp"
"github.com/livefir/fir/internal/dom"
"github.com/livefir/fir/pubsub"
"github.com/redis/go-redis/v9"
"github.com/testcontainers/testcontainers-go"
redisContainer "github.com/testcontainers/testcontainers-go/modules/redis"
)
type doubleRequest struct {
Num int `json:"num"`
}
func doubler() RouteOptions {
return RouteOptions{
ID("doubler"),
Content(
`<div @fir:double:ok="$fir.replace()">{{ .num }}</div>`),
OnLoad(func(ctx RouteContext) error {
return ctx.KV("num", 0)
}),
OnEvent("double", func(ctx RouteContext) error {
req := new(doubleRequest)
if err := ctx.Bind(req); err != nil {
return err
}
return ctx.KV("num", req.Num*2)
}),
}
}
var testCases = []struct {
name string
options []ControllerOption
routeFunc RouteFunc
}{
// Test cases here
{
name: "doubler",
routeFunc: doubler,
// options: []ControllerOption{DevelopmentMode(true)},
},
}
type testInput struct {
serverURL string
num int
wssend int
wsrecv int
event Event
conn *websocket.Conn
closeWs bool
sync.RWMutex
}
func (ti *testInput) incWssend() {
ti.Lock()
defer ti.Unlock()
ti.wssend += 1
}
func (ti *testInput) incWsrecv() {
ti.Lock()
defer ti.Unlock()
ti.wsrecv += 1
}
func (ti *testInput) getWssend() int {
ti.RLock()
defer ti.RUnlock()
return ti.wssend
}
func (ti *testInput) getWsrecv() int {
ti.RLock()
defer ti.RUnlock()
return ti.wsrecv
}
func eventPayload(tb testing.TB, ti *testInput) Event {
// Make a request to the test server
req, err := http.NewRequest("GET", ti.serverURL, nil)
if err != nil {
tb.Fatal(err)
}
resp, err := cleanhttp.DefaultClient().Do(req)
if err != nil {
tb.Fatal(err)
}
defer resp.Body.Close()
var firSession string
for _, cookie := range resp.Cookies() {
if cookie.Name == "_fir_session_" {
firSession = cookie.Value
break
}
}
data, err := json.Marshal(&doubleRequest{Num: ti.num})
if err != nil {
tb.Fatal(err)
}
event := Event{
ID: "double",
IsForm: false,
Params: data,
SessionID: &firSession,
Timestamp: time.Now().UTC().UnixMilli(),
}
return event
}
func runPostEventTest(tb testing.TB, ti *testInput) {
event := eventPayload(tb, ti)
// post event to the test server
payload := new(bytes.Buffer)
err := json.NewEncoder(payload).Encode(event)
if err != nil {
tb.Fatal(err)
}
req, err := http.NewRequest("POST", ti.serverURL, payload)
if err != nil {
tb.Fatal(err)
}
req.AddCookie(&http.Cookie{Name: "_fir_session_", Value: *event.SessionID})
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-FIR-MODE", "event")
resp, err := cleanhttp.DefaultClient().Do(req)
if err != nil {
tb.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
tb.Fatalf("expected status code 200, got %d", resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
tb.Fatal(err)
}
// decode response body to []dom.Event
var domEvents []dom.Event
err = json.Unmarshal(body, &domEvents)
if err != nil {
tb.Fatal(err)
}
if len(domEvents) != 1 {
tb.Fatalf("expected 1 event, got %d", len(domEvents))
}
expectedHTML := fmt.Sprintf("%d", ti.num*2)
if removeSpace(domEvents[0].Detail.HTML) != expectedHTML {
tb.Fatalf("expected: %s, got: %s", expectedHTML, domEvents[0].Detail.HTML)
}
}
func dialWebSocket(tb testing.TB, ti *testInput, event Event) *websocket.Conn {
wsURLString := strings.Replace(ti.serverURL, "http", "ws", 1)
wsDialer := websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
HandshakeTimeout: 45 * time.Second,
// EnableCompression: true,
// Jar: jar, // jar doesnät work but adding a Cookie header does
}
header := http.Header{}
header.Set("Cookie", fmt.Sprintf("_fir_session_=%s", *event.SessionID))
ws, _, err := wsDialer.Dial(wsURLString, header)
if err != nil {
tb.Fatal(err)
}
return ws
}
func runWebsocketEventTest(tb testing.TB, ti *testInput) {
event := ti.event
if event.SessionID == nil {
event = eventPayload(tb, ti)
}
ws := ti.conn
if ws == nil {
ws = dialWebSocket(tb, ti, event)
}
if ti.closeWs {
defer ws.Close()
}
ti.incWssend()
err := ws.WriteJSON(event)
if err != nil {
tb.Fatal(err)
}
ws.SetReadDeadline(time.Now().Add(1000 * time.Millisecond))
var message []byte
_, message, err = ws.ReadMessage()
if err != nil {
tb.Fatal(err)
}
ti.incWsrecv()
var domEvents []dom.Event
err = json.Unmarshal(message, &domEvents)
if err != nil {
tb.Fatal(err)
}
if len(domEvents) != 1 {
tb.Fatalf("expected 1 event, got %d", len(domEvents))
}
expectedHTML := fmt.Sprintf("%d", ti.num*2)
if removeSpace(domEvents[0].Detail.HTML) != expectedHTML {
tb.Fatalf("expected: %s, got: %s", expectedHTML, domEvents[0].Detail.HTML)
}
if !ti.closeWs {
return
}
err = ws.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
if err != nil {
tb.Fatal(err)
}
}
func BenchmarkControllerWebsocktDisabled(b *testing.B) {
for _, tc := range testCases {
tc.options = append(tc.options, WithDisableWebsocket())
controller := NewController(tc.name, tc.options...)
// Create a test HTTP server
server := httptest.NewServer(controller.RouteFunc(tc.routeFunc))
defer server.Close()
ti := &testInput{serverURL: server.URL, num: 10}
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
runPostEventTest(b, ti)
}
})
b.ReportAllocs()
}
}
func TestControllerWebsocketDisabled(t *testing.T) {
for _, tc := range testCases {
tc.options = append(tc.options, WithDisableWebsocket())
controller := NewController(tc.name, tc.options...)
// Create a test HTTP server
server := httptest.NewServer(controller.RouteFunc(tc.routeFunc))
defer server.Close()
ti := &testInput{serverURL: server.URL, num: 10}
t.Parallel()
t.Run(tc.name, func(t *testing.T) {
runPostEventTest(t, ti)
})
}
}
func BenchmarkControllerWebsocktEnabled(b *testing.B) {
for _, tc := range testCases {
controller := NewController(tc.name, tc.options...)
// Create a test HTTP server
server := httptest.NewServer(controller.RouteFunc(tc.routeFunc))
defer server.Close()
ti := &testInput{serverURL: server.URL, num: 10, closeWs: true}
b.Cleanup(func() {
fmt.Printf("ws send: %d, ws recv: %d\n", ti.getWssend(), ti.getWsrecv())
})
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
runWebsocketEventTest(b, ti)
}
})
b.ReportMetric(float64(ti.getWssend()), "total_sends")
b.ReportMetric(float64(ti.getWsrecv()), "total_receives")
b.ReportAllocs()
}
}
func TestControllerWebsocktEnabledMultiEvent(t *testing.T) {
for _, tc := range testCases {
controller := NewController(tc.name, tc.options...)
// Create a test HTTP server
server := httptest.NewServer(controller.RouteFunc(tc.routeFunc))
defer server.Close()
ti := &testInput{serverURL: server.URL, num: 10}
ti.event = eventPayload(t, ti)
ti.conn = dialWebSocket(t, ti, ti.event)
t.Cleanup(func() {
err := ti.conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
if err != nil {
t.Fatal(err)
}
time.Sleep(500 * time.Millisecond)
ti.conn.Close()
})
for i := 0; i < 20; i++ {
time.Sleep(251 * time.Millisecond)
ti.event.Timestamp = time.Now().UTC().UnixMilli()
runWebsocketEventTest(t, ti)
}
if ti.getWssend() != ti.getWsrecv() {
t.Fatalf("expected ws send: %d, ws recv: %d", ti.getWssend(), ti.getWsrecv())
}
}
}
func TestControllerWebsocketEnabled(t *testing.T) {
for _, tc := range testCases {
controller := NewController(tc.name, tc.options...)
// Create a test HTTP server
server := httptest.NewServer(controller.RouteFunc(tc.routeFunc))
defer server.Close()
ti := &testInput{serverURL: server.URL, num: 10}
t.Parallel()
t.Run(tc.name, func(t *testing.T) {
runWebsocketEventTest(t, ti)
})
}
}
func BenchmarkControllerWebsocktEnabledRedis(b *testing.B) {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password set
DB: 0, // use default DB
})
pubsubAdapter := pubsub.NewRedis(client)
for _, tc := range testCases {
tc.options = append(tc.options, WithPubsubAdapter(pubsubAdapter))
controller := NewController(tc.name, tc.options...)
// Create a test HTTP server
server := httptest.NewServer(controller.RouteFunc(tc.routeFunc))
defer server.Close()
ti := &testInput{serverURL: server.URL, num: 10}
b.Cleanup(func() {
fmt.Printf("ws send: %d, ws recv: %d\n", ti.getWssend(), ti.getWsrecv())
})
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
runWebsocketEventTest(b, ti)
}
})
b.ReportMetric(float64(ti.getWssend()), "total_sends")
b.ReportMetric(float64(ti.getWsrecv()), "total_receives")
b.ReportAllocs()
}
}
func TestControllerWebsocketEnabledRedis(t *testing.T) {
if os.Getenv("DOCKER") != "1" {
t.Skip("Skipping testing since docker is not present")
}
ctx := context.Background()
redisContainer, err := redisContainer.RunContainer(ctx,
testcontainers.WithImage("docker.io/redis:7"),
)
if err != nil {
t.Fatalf("failed to start container: %s", err)
}
// Clean up the container
defer func() {
if err := redisContainer.Terminate(ctx); err != nil {
t.Fatalf("failed to terminate container: %s", err)
}
}()
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password set
DB: 0, // use default DB
})
pubsubAdapter := pubsub.NewRedis(client)
for _, tc := range testCases {
tc.options = append(tc.options, WithPubsubAdapter(pubsubAdapter))
controller := NewController(tc.name, tc.options...)
// Create a test HTTP server
server := httptest.NewServer(controller.RouteFunc(tc.routeFunc))
defer server.Close()
ti := &testInput{serverURL: server.URL, num: 10}
t.Parallel()
t.Run(tc.name, func(t *testing.T) {
runWebsocketEventTest(t, ti)
})
}
}