-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpine_test.go
553 lines (448 loc) · 13.5 KB
/
pine_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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
package pine
import (
"net/http"
"net/http/httptest"
"os"
"testing"
"time"
)
func Mock_Ctx() *Ctx {
ctx := Ctx{
params: map[string]string{"id": "42"},
}
ctx.Request = httptest.NewRequest(http.MethodGet, "/?query=queryValue", nil)
ctx.Response = &responseWriterWrapper{
httptest.NewRecorder(),
0,
nil,
}
return &ctx
}
func TestNewServer_DefaultConfig(t *testing.T) {
server := New()
// Assert default config values
if server.config.BodyLimit != 5*1024*1024 { // 5 MB
t.Errorf("expected BodyLimit to be %d, got %d", 5*1024*1024, server.config.BodyLimit)
}
if server.config.ReadTimeout != 5*time.Second {
t.Errorf("expected ReadTimeout to be 5s, got %s", server.config.ReadTimeout)
}
if server.config.WriteTimeout != 5*time.Second {
t.Errorf("expected WriteTimeout to be 5s, got %s", server.config.WriteTimeout)
}
if server.config.DisableKeepAlive != false {
t.Errorf("expected DisableKeepAlive to be false, got %v", server.config.DisableKeepAlive)
}
if server.config.UploadPath != "./uploads/" {
t.Errorf("expected UploadPath to be './uploads/', got '%s'", server.config.UploadPath)
}
if server.config.JSONEncoder == nil {
t.Error("expected JSONEncoder to be set")
}
if server.config.JSONDecoder == nil {
t.Error("expected JSONDecoder to be set")
}
if len(server.config.RequestMethods) == 0 {
t.Error("expected RequestMethods to not be empty")
}
}
func TestNewServer_CustomConfig(t *testing.T) {
customConfig := Config{
BodyLimit: 10 * 1024 * 1024, // 10 MB
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
DisableKeepAlive: true,
UploadPath: "./custom_uploads/",
}
server := New(customConfig)
// Assert custom config values
if server.config.BodyLimit != 10*1024*1024 {
t.Errorf("expected BodyLimit to be %d, got %d", 10*1024*1024, server.config.BodyLimit)
}
if server.config.ReadTimeout != 10*time.Second {
t.Errorf("expected ReadTimeout to be 10s, got %s", server.config.ReadTimeout)
}
if server.config.WriteTimeout != 10*time.Second {
t.Errorf("expected WriteTimeout to be 10s, got %s", server.config.WriteTimeout)
}
if server.config.DisableKeepAlive != true {
t.Errorf("expected DisableKeepAlive to be true, got %v", server.config.DisableKeepAlive)
}
if server.config.UploadPath != "./custom_uploads/" {
t.Errorf("expected UploadPath to be './custom_uploads/', got '%s'", server.config.UploadPath)
}
}
func TestNewServer_MissingConfigValues(t *testing.T) {
// Test with an empty config
server := New(Config{})
// Assert that default values are used
if server.config.BodyLimit != 5*1024*1024 {
t.Errorf("expected BodyLimit to be %d, got %d", 5*1024*1024, server.config.BodyLimit)
}
if server.config.ReadTimeout != 5*time.Second {
t.Errorf("expected ReadTimeout to be 5s, got %s", server.config.ReadTimeout)
}
if server.config.WriteTimeout != 5*time.Second {
t.Errorf("expected WriteTimeout to be 5s, got %s", server.config.WriteTimeout)
}
}
func TestNewServer_Logger(t *testing.T) {
server := New()
// Check if errorLog is initialized properly
if server.errorLog == nil {
t.Error("expected errorLog to be initialized")
}
// Check if logger writes to stderr
if server.errorLog.Writer() != os.Stderr {
t.Error("expected errorLog to write to stderr")
}
}
func TestNewServer_TLSConfig(t *testing.T) {
customTLSConfig := Config{
TLSConfig: TLSConfig{ServeTLS: true},
}
server := New(customTLSConfig)
// Assert that the TLS configuration is set correctly
if !server.config.TLSConfig.ServeTLS {
t.Error("expected ServeTLS to be true")
}
}
func TestAddRoute_ValidMethod(t *testing.T) {
server := New()
handler := func(c *Ctx) error { return nil }
// Add a valid GET route
server.AddRoute("GET", "/test", handler)
// Verify that the route was added correctly
methodIndex := server.methodInt("GET")
if len(server.stack[methodIndex]) == 0 {
t.Error("expected at least one route to be added for GET")
}
// Verify the route details
route := server.stack[methodIndex][0]
if route.Path != "/test" {
t.Errorf("expected route path to be '/test', got '%s'", route.Path)
}
if route.Method != "GET" {
t.Errorf("expected route method to be 'GET', got '%s'", route.Method)
}
if len(route.Handlers) == 0 {
t.Error("expected at least one handler to be added")
}
}
func TestAddRoute_InvalidMethod(t *testing.T) {
server := New()
handler := func(c *Ctx) error { return nil }
// Attempt to add a route with an invalid method
server.AddRoute("INVALID", "/test", handler)
// read the error console to check if the error log was called
// Since logging is not easily captured, you could check the log output manually or use a mock logger in real tests
// TODO: Find a way to capture the error log in tests
}
func TestGet(t *testing.T) {
server := New()
handler := func(c *Ctx) error { return nil }
// Add a GET route
server.Get("/test", handler)
// Verify that the route was added correctly
methodIndex := server.methodInt("GET")
if len(server.stack[methodIndex]) == 0 {
t.Error("expected at least one route to be added for GET")
}
}
func TestPost(t *testing.T) {
server := New()
handler := func(c *Ctx) error { return nil }
// Add a POST route
server.Post("/test", handler)
// Verify that the route was added correctly
methodIndex := server.methodInt("POST")
if len(server.stack[methodIndex]) == 0 {
t.Error("expected at least one route to be added for POST")
}
}
func TestPut(t *testing.T) {
server := New()
handler := func(c *Ctx) error { return nil }
// Add a PUT route
server.Put("/test", handler)
// Verify that the route was added correctly
methodIndex := server.methodInt("PUT")
if len(server.stack[methodIndex]) == 0 {
t.Error("expected at least one route to be added for PUT")
}
}
func TestPatch(t *testing.T) {
server := New()
handler := func(c *Ctx) error { return nil }
// Add a PATCH route
server.Patch("/test", handler)
// Verify that the route was added correctly
methodIndex := server.methodInt("PATCH")
if len(server.stack[methodIndex]) == 0 {
t.Error("expected at least one route to be added for PATCH")
}
}
func TestDelete(t *testing.T) {
server := New()
handler := func(c *Ctx) error { return nil }
// Add a DELETE route
server.Delete("/test", handler)
// Verify that the route was added correctly
methodIndex := server.methodInt("DELETE")
if len(server.stack[methodIndex]) == 0 {
t.Error("expected at least one route to be added for DELETE")
}
}
func TestOptions(t *testing.T) {
server := New()
handler := func(c *Ctx) error { return nil }
// Add an OPTIONS route
server.Options("/test", handler)
// Verify that the route was added correctly
methodIndex := server.methodInt("OPTIONS")
if len(server.stack[methodIndex]) == 0 {
t.Error("expected at least one route to be added for OPTIONS")
}
}
func TestMatchRoute_ExactMatch(t *testing.T) {
routePath := "/user/123"
requestPath := "/user/123"
matched, params := matchRoute(routePath, requestPath)
if !matched {
t.Error("expected match to be true for exact path")
}
if len(params) != 0 {
t.Error("expected params to be empty for exact match")
}
}
func TestMatchRoute_WithParams(t *testing.T) {
routePath := "/user/:id"
requestPath := "/user/123"
matched, params := matchRoute(routePath, requestPath)
if !matched {
t.Error("expected match to be true for parameterized path")
}
if params["id"] != "123" {
t.Errorf("expected param 'id' to be '123', got '%s'", params["id"])
}
}
func TestMatchRoute_NoMatch(t *testing.T) {
routePath := "/user/:id"
requestPath := "/profile/123"
matched, _ := matchRoute(routePath, requestPath)
if matched {
t.Error("expected match to be false for non-matching path")
}
}
func TestStart_HTTPServer(t *testing.T) {
server := New() // Assuming New initializes your server
address := ":8080"
handler := func(c *Ctx) error {
return c.SendString("Hello, World!")
}
server.Get("/test", handler)
go func() {
if err := server.Start(address); err != nil {
t.Errorf("failed to start server: %v", err)
}
}()
// Create a test request
resp, err := http.Get("http://localhost:8080/test") // Use a valid route
if err != nil {
t.Errorf("failed to send request: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("expected status OK, got: %s", resp.Status)
}
}
func TestServeHTTP_MatchedRoute(t *testing.T) {
server := New()
handler := func(c *Ctx) error {
return c.SendString("Hello, World!")
}
server.Get("/hello/:name", handler)
req, err := http.NewRequest("GET", "/hello/John", nil)
if err != nil {
t.Fatal(err)
}
rr := httptest.NewRecorder()
server.ServeHTTP(rr, req)
if status := rr.Code; status != http.StatusOK {
t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK)
}
expected := "Hello, World!"
if rr.Body.String() != expected {
t.Errorf("handler returned unexpected body: got %v want %v", rr.Body.String(), expected)
}
}
func TestServeHTTP_MethodNotAllowed(t *testing.T) {
server := New()
handler := func(c *Ctx) error {
return c.SendString("Hello, World!")
}
server.Get("/test", handler)
req, err := http.NewRequest("POST", "/test", nil)
if err != nil {
t.Fatal(err)
}
rr := httptest.NewRecorder()
server.ServeHTTP(rr, req)
if status := rr.Code; status != http.StatusMethodNotAllowed {
t.Errorf("expected status 405 Method Not Allowed, got: %v", status)
}
}
func TestServeHTTP_NotFound(t *testing.T) {
server := New()
handler := func(c *Ctx) error {
return c.SendString("Hello, World!")
}
server.Get("/test", handler)
req, err := http.NewRequest("GET", "/unknown", nil)
if err != nil {
t.Fatal(err)
}
rr := httptest.NewRecorder()
server.ServeHTTP(rr, req)
if status := rr.Code; status != http.StatusNotFound {
t.Errorf("expected status 404 Not Found, got: %v", status)
}
}
func TestUse_AddsMiddleware(t *testing.T) {
server := New() // Assuming New initializes your server
middleware := func(next Handler) Handler {
return func(c *Ctx) error {
c.SendString("Middleware applied. ")
return next(c)
}
}
server.Use(middleware)
// Adding a test route
server.Get("/test", func(c *Ctx) error {
return c.SendString("Hello, World!")
})
req, err := http.NewRequest("GET", "/test", nil)
if err != nil {
t.Fatal(err)
}
rr := httptest.NewRecorder()
server.ServeHTTP(rr, req)
expected := "Middleware applied. Hello, World!"
if rr.Body.String() != expected {
t.Errorf("expected '%s', got '%s'", expected, rr.Body.String())
}
}
func TestApplyMiddleware_OrdersMiddleware(t *testing.T) {
server := New() // Assuming New initializes your server
middleware1 := func(next Handler) Handler {
return func(c *Ctx) error {
c.SendString("First Middleware. ")
return next(c)
}
}
middleware2 := func(next Handler) Handler {
return func(c *Ctx) error {
c.SendString("Second Middleware. ")
return next(c)
}
}
server.Use(middleware1)
server.Use(middleware2)
// Adding a test route
server.Get("/test", func(c *Ctx) error {
return c.SendString("Final Response.")
})
req, err := http.NewRequest("GET", "/test", nil)
if err != nil {
t.Fatal(err)
}
rr := httptest.NewRecorder()
server.ServeHTTP(rr, req)
expected := "First Middleware. Second Middleware. Final Response."
if rr.Body.String() != expected {
t.Errorf("expected '%s', got '%s'", expected, rr.Body.String())
}
}
func TestUse_AppliesMiddlewareToExistingRoutes(t *testing.T) {
server := New()
// Initial middleware
middleware := func(next Handler) Handler {
return func(c *Ctx) error {
c.SendString("Initial Middleware. ")
return next(c)
}
}
// Adding a route before using middleware
server.Get("/test", func(c *Ctx) error {
return c.SendString("Hello!")
})
// Applying middleware
server.Use(middleware)
req, err := http.NewRequest("GET", "/test", nil)
if err != nil {
t.Fatal(err)
}
rr := httptest.NewRecorder()
server.ServeHTTP(rr, req)
expected := "Initial Middleware. Hello!"
if rr.Body.String() != expected {
t.Errorf("expected '%s', got '%s'", expected, rr.Body.String())
}
}
func TestUse_WithMultipleRoutes(t *testing.T) {
server := New()
middleware := func(next Handler) Handler {
return func(c *Ctx) error {
c.SendString("Middleware active. ")
return next(c)
}
}
server.Use(middleware)
// Adding multiple test routes
server.Get("/route1", func(c *Ctx) error {
return c.SendString("Route 1.")
})
server.Get("/route2", func(c *Ctx) error {
return c.SendString("Route 2.")
})
// Test route 1
req1, err := http.NewRequest("GET", "/route1", nil)
if err != nil {
t.Fatal(err)
}
rr1 := httptest.NewRecorder()
server.ServeHTTP(rr1, req1)
expected1 := "Middleware active. Route 1."
if rr1.Body.String() != expected1 {
t.Errorf("expected '%s', got '%s'", expected1, rr1.Body.String())
}
// Test route 2
req2, err := http.NewRequest("GET", "/route2", nil)
if err != nil {
t.Fatal(err)
}
rr2 := httptest.NewRecorder()
server.ServeHTTP(rr2, req2)
expected2 := "Middleware active. Route 2."
if rr2.Body.String() != expected2 {
t.Errorf("expected '%s', got '%s'", expected2, rr2.Body.String())
}
}
func TestReadCookie(t *testing.T) {
ctx := &Ctx{Request: &http.Request{
Header: map[string][]string{
"Cookie": {"testCookie=testValue"},
},
}}
cookie, err := ctx.ReadCookie("testCookie")
if err != nil {
t.Fatal(err)
}
expected := "testValue"
if cookie.Value != expected {
t.Errorf("expected '%s', got '%s'", expected, cookie.Value)
}
}
// TODO: Add tests involving responseWriterWrapper. As of now, such tests cannot
// be verified as I have not figured out how to mock the responseWriterWrapper.
// If you have any ideas, please feel free to share them.