-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgrouter_test.go
399 lines (355 loc) · 11.3 KB
/
grouter_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
package grouter
import (
"context"
"crypto/tls"
"fmt"
"net/http"
"testing"
)
const (
port = 8080
tlsPort = 8443
)
var testingContext = context.Background()
func TestSingletonServer(t *testing.T) {
server := GetServer(&testingContext, nil)
anotherServer := GetServer(&testingContext, nil)
if server != anotherServer {
t.Errorf("Expected server to be a singleton")
}
oldRouter := server.router
anotherServer = server.SetRouter(NewRouter(testingContext))
if oldRouter == anotherServer.router || server != anotherServer {
t.Errorf("Expected router change to not change server instance")
}
}
func TestServerUse(t *testing.T) {
server := GetServer(&testingContext, nil).SetRouter(NewRouter(testingContext))
server.Use("/test", GET, func(ctx context.Context, w *ResponseWriter, r *http.Request, next func()) error {
next()
return nil
})
route := server.router.trie.Get("/test")
if route == nil || len(route.(Route)[GET]) != 1 {
t.Errorf("Expected GET \"/test\" to be initialized")
}
server.Use("/test", GET, func(ctx context.Context, w *ResponseWriter, r *http.Request, next func()) error {
next()
return nil
})
route = server.router.trie.Get("/test")
if route == nil || len(route.(Route)[GET]) != 2 {
t.Errorf("Expected \"/test\" to be initialized")
}
if len(route.(Route)[POST]) > 0 {
t.Errorf("Expected POST \"/test\" to not be initialized")
}
}
func TestRoot(t *testing.T) {
server := GetServer(&testingContext, nil).SetRouter(NewRouter(testingContext))
server.Use("/", GET, func(ctx context.Context, w *ResponseWriter, r *http.Request, next func()) error {
next()
return nil
})
route := server.router.trie.Get("/")
if route == nil || len(route.(Route)[GET]) != 1 {
t.Errorf("Expected GET \"/\" to be initialized")
}
}
func TestHandlersForPath(t *testing.T) {
server := GetServer(&testingContext, nil).SetRouter(NewRouter(testingContext))
tracker := make(map[string]struct{})
server.Use("/test", GET, func(ctx context.Context, w *ResponseWriter, r *http.Request, next func()) error {
tracker["first"] = struct{}{}
next()
return nil
})
server.Use("/test", GET, func(ctx context.Context, w *ResponseWriter, r *http.Request, next func()) error {
tracker["second"] = struct{}{}
w.WriteHeader(http.StatusOK)
next()
return nil
})
GetClient(server, port, false, true, func(client *http.Client) {
res, err := client.Get(fmt.Sprintf("http://localhost:%d/test", port))
if err != nil {
t.Fatal(err)
}
if res.StatusCode != http.StatusOK {
t.Errorf("Expected status code 200, got %d", res.StatusCode)
}
if _, exists := tracker["first"]; !exists {
t.Errorf("Expected first handler to be called")
}
if _, exists := tracker["second"]; !exists {
t.Errorf("Expected second handler to be called")
}
})
}
func TestHandlersForPathNoHandlers(t *testing.T) {
server := GetServer(&testingContext, nil).SetRouter(NewRouter(testingContext))
GetClient(server, port, false, true, func(client *http.Client) {
res, err := client.Get(fmt.Sprintf("http://localhost:%d/test", port))
if err != nil {
t.Fatal(err)
}
if res.StatusCode != http.StatusNotFound {
t.Errorf("Expected status code 404, got %d", res.StatusCode)
}
})
}
func TestHandlersForPathNoHandlersForMethod(t *testing.T) {
server := GetServer(&testingContext, nil).SetRouter(NewRouter(testingContext))
server.Use("/test", GET, func(ctx context.Context, w *ResponseWriter, r *http.Request, next func()) error {
next()
return nil
})
GetClient(server, port, false, true, func(client *http.Client) {
res, err := client.Post(fmt.Sprintf("http://localhost:%d/test", port), "text/plain", nil)
if err != nil {
t.Fatal(err)
}
if res.StatusCode != http.StatusNotFound {
t.Errorf("Expected status code 404, got %d", res.StatusCode)
}
})
}
func TestHandlersForPathNoHandlersForPath(t *testing.T) {
server := GetServer(&testingContext, nil).SetRouter(NewRouter(testingContext))
server.Use("/test", GET, func(ctx context.Context, w *ResponseWriter, r *http.Request, next func()) error {
next()
return nil
})
GetClient(server, port, false, true, func(client *http.Client) {
res, err := client.Get(fmt.Sprintf("http://localhost:%d/test2", port))
if err != nil {
t.Fatal(err)
}
if res.StatusCode != http.StatusNotFound {
t.Errorf("Expected status code 404, got %d", res.StatusCode)
}
})
}
func TestHandlersForPathNoHandlersForPathNoHandlersForMethod(t *testing.T) {
server := GetServer(&testingContext, nil).SetRouter(NewRouter(testingContext))
server.Use("/test", GET, func(ctx context.Context, w *ResponseWriter, r *http.Request, next func()) error {
next()
return nil
})
GetClient(server, port, false, true, func(client *http.Client) {
res, err := client.Post(fmt.Sprintf("http://localhost:%d/test2", port), "text/plain", nil)
if err != nil {
t.Fatal(err)
}
if res.StatusCode != http.StatusNotFound {
t.Errorf("Expected status code 404, got %d", res.StatusCode)
}
})
}
func TestHandlersForPathNoResponse(t *testing.T) {
server := GetServer(&testingContext, nil).SetRouter(NewRouter(testingContext))
server.Use("/test", GET, func(ctx context.Context, w *ResponseWriter, r *http.Request, next func()) error {
next()
return nil
})
GetClient(server, port, false, true, func(client *http.Client) {
res, err := client.Get(fmt.Sprintf("http://localhost:%d/test", port))
if err != nil {
t.Fatal(err)
}
if res.StatusCode != http.StatusInternalServerError {
t.Errorf("Expected status code 500, got %d", res.StatusCode)
}
})
}
func TestGlobalHandlers(t *testing.T) {
server := GetServer(&testingContext, nil).SetRouter(NewRouter(testingContext))
tracker := make(map[string]int)
server.UseGlobal(func(ctx context.Context, w *ResponseWriter, r *http.Request, next func()) error {
tracker["before"] = 1
next()
return nil
}, nil)
server.UseGlobal(func(ctx context.Context, w *ResponseWriter, r *http.Request, next func()) error {
tracker["before"]++
next()
return nil
}, &GlobalRouteOptions{
afterAll: false,
ignoredPathRegexes: []string{"/test2"},
})
server.Use("/test", GET, func(ctx context.Context, w *ResponseWriter, r *http.Request, next func()) error {
tracker["test"] = 1
next()
return nil
})
server.UseGlobal(func(ctx context.Context, w *ResponseWriter, r *http.Request, next func()) error {
tracker["after"] = 1
w.WriteHeader(http.StatusOK)
next()
return nil
}, &GlobalRouteOptions{
afterAll: true,
ignoredPathRegexes: nil,
})
GetClient(server, port, false, true, func(client *http.Client) {
res, err := client.Get(fmt.Sprintf("http://localhost:%d/test", port))
if err != nil {
t.Fatal(err)
}
if res.StatusCode != http.StatusOK {
t.Errorf("Expected status code 200, got %d", res.StatusCode)
}
if val := tracker["before"]; val != 2 {
t.Errorf("Expected before handler to be called twice")
}
if val := tracker["test"]; val != 1 {
t.Errorf("Expected test handler to be called")
}
if val := tracker["after"]; val != 1 {
t.Errorf("Expected after handler to be called")
}
})
}
func TestGlobalHandlersIgnoredPaths(t *testing.T) {
server := GetServer(&testingContext, nil).SetRouter(NewRouter(testingContext))
tracker := make(map[string]int)
server.UseGlobal(func(ctx context.Context, w *ResponseWriter, r *http.Request, next func()) error {
tracker["before"] = 1
next()
return nil
}, nil)
server.UseGlobal(func(ctx context.Context, w *ResponseWriter, r *http.Request, next func()) error {
tracker["before"]++
next()
return nil
}, &GlobalRouteOptions{
afterAll: false,
ignoredPathRegexes: []string{"/test"},
})
server.Use("/test", GET, func(ctx context.Context, w *ResponseWriter, r *http.Request, next func()) error {
tracker["test"] = 1
next()
return nil
})
server.UseGlobal(func(ctx context.Context, w *ResponseWriter, r *http.Request, next func()) error {
tracker["after"] = 1
w.WriteHeader(http.StatusOK)
next()
return nil
}, &GlobalRouteOptions{
afterAll: true,
ignoredPathRegexes: nil,
})
GetClient(server, port, false, true, func(client *http.Client) {
res, err := client.Get(fmt.Sprintf("http://localhost:%d/test", port))
if err != nil {
t.Fatal(err)
}
if res.StatusCode != http.StatusOK {
t.Errorf("Expected status code 200, got %d", res.StatusCode)
}
if val := tracker["before"]; val != 1 {
t.Errorf("Expected before handler to be called once")
}
if val := tracker["test"]; val != 1 {
t.Errorf("Expected test handler to be called")
}
if val := tracker["after"]; val != 1 {
t.Errorf("Expected after handler to be called")
}
})
}
func TestGlobalHandlersCorrectOrder(t *testing.T) {
server := GetServer(&testingContext, nil).SetRouter(NewRouter(testingContext))
tracker := []string{}
server.UseGlobal(func(ctx context.Context, w *ResponseWriter, r *http.Request, next func()) error {
tracker = append(tracker, "before")
next()
return nil
}, nil)
server.Use("/test", GET, func(ctx context.Context, w *ResponseWriter, r *http.Request, next func()) error {
tracker = append(tracker, "test")
next()
return nil
})
server.UseGlobal(func(ctx context.Context, w *ResponseWriter, r *http.Request, next func()) error {
tracker = append(tracker, "after")
w.WriteHeader(http.StatusOK)
next()
return nil
}, &GlobalRouteOptions{
afterAll: true,
ignoredPathRegexes: nil,
})
GetClient(server, port, false, true, func(client *http.Client) {
res, err := client.Get(fmt.Sprintf("http://localhost:%d/test", port))
if err != nil {
t.Fatal(err)
}
if res.StatusCode != http.StatusOK {
t.Errorf("Expected status code 200, got %d", res.StatusCode)
}
if len(tracker) != 3 {
t.Errorf("Expected 3 handlers to be called")
}
expected := []string{"before", "test", "after"}
for i := 0; i < len(tracker); i++ {
if tracker[i] != expected[i] {
t.Errorf("Expected %s handler to be called", expected[i])
}
}
})
}
func TestTLSServer(t *testing.T) {
server := GetServer(&testingContext, &TLSConfig{
CertFilePath: "test.cert.pem",
KeyFilePath: "test.key.pem",
}).SetRouter(NewRouter(testingContext))
server.Use("/test", GET, func(ctx context.Context, w *ResponseWriter, r *http.Request, next func()) error {
_, err := w.Write([]byte("Hello, world!"))
if err != nil {
return err
}
next()
return nil
})
GetClient(server, tlsPort, true, false, func(client *http.Client) {
res, err := client.Get(fmt.Sprintf("https://localhost:%d/test", tlsPort))
if err != nil {
t.Fatalf("Failed to connect to server: %v", err)
}
if res.StatusCode != 200 {
t.Errorf("Expected status code 200, got %d", res.StatusCode)
}
})
}
func GetClient(server *Server, p int, useTLS bool, willRestart bool, testFunc func(*http.Client)) {
// Channel to signal when the server has started
started, ended := make(chan struct{}), make(chan struct{})
go func() {
// Start the server in a separate goroutine
err := server.Listen(p, started)
if err != nil && err != http.ErrServerClosed {
fmt.Println(err)
}
// Signal that the server has stopped
close(ended)
}()
// Wait for the server to start
<-started
var client *http.Client
if useTLS {
transport := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client = &http.Client{Transport: transport}
} else {
client = &http.Client{}
}
testFunc(client)
if err := server.Shutdown(willRestart); err != nil {
fmt.Println(err)
}
<-ended // Wait for the server to stop
}