-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrex_test.go
1325 lines (1057 loc) · 28.7 KB
/
rex_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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package rex_test
import (
"bytes"
"context"
"embed"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"reflect"
"strconv"
"strings"
"testing"
"text/template"
"time"
"github.com/abiiranathan/rex"
)
func TestRouterServeHTTP(t *testing.T) {
r := rex.NewRouter()
r.GET("/test", func(c *rex.Context) error {
return c.String("test")
})
r.GET("/test2", func(c *rex.Context) error {
return c.String("test2")
})
r.GET("/test3", func(c *rex.Context) error {
return c.String("test3")
})
r.POST("/test4", func(c *rex.Context) error {
return c.String("test4")
})
r.PUT("/test5", func(c *rex.Context) error {
return c.String("test5")
})
r.DELETE("/test6", func(c *rex.Context) error {
return c.String("test6")
})
r.PATCH("/test7", func(c *rex.Context) error {
return c.String("test7")
})
r.OPTIONS("/test8", func(c *rex.Context) error {
return c.String("test8")
})
r.HEAD("/test9", func(c *rex.Context) error {
return c.String("test9")
})
r.CONNECT("/test10", func(c *rex.Context) error {
return c.String("test10")
})
r.TRACE("/test11", func(c *rex.Context) error {
return c.String("test11")
})
tests := []struct {
name string
method string
path string
expected string
}{
{"GET", "GET", "/test", "test"},
{"GET", "GET", "/test2", "test2"},
{"GET", "GET", "/test3", "test3"},
{"POST", "POST", "/test4", "test4"},
{"PUT", "PUT", "/test5", "test5"},
{"DELETE", "DELETE", "/test6", "test6"},
{"PATCH", "PATCH", "/test7", "test7"},
{"OPTIONS", "OPTIONS", "/test8", "test8"},
{"HEAD", "HEAD", "/test9", "test9"},
{"CONNECT", "CONNECT", "/test10", "test10"},
{"TRACE", "TRACE", "/test11", "test11"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
w := httptest.NewRecorder()
req := httptest.NewRequest(tt.method, tt.path, nil)
r.ServeHTTP(w, req)
if w.Body.String() != tt.expected {
t.Errorf("expected %s, got %s", tt.expected, w.Body.String())
}
})
}
}
// test 404
func TestRouterNotFound(t *testing.T) {
r := rex.NewRouter()
r.GET("/path", func(c *rex.Context) error {
return c.String("test")
})
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/notfound", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusNotFound {
t.Errorf("expected status 404, got %d", w.Code)
}
}
// Use a derived type. Form processing should still pass.
type Age int
type User struct {
Name string `form:"name"`
Age Age `form:"age"`
}
// test sending and reading form data
func TestRouterUrlEncodedFormData(t *testing.T) {
r := rex.NewRouter()
r.POST("/urlencoded", func(c *rex.Context) error {
u := User{}
err := c.BodyParser(&u)
if err != nil {
return c.String(err.Error())
}
return c.String(u.Name)
})
form := url.Values{}
form.Add("name", "Abiira Nathan")
form.Add("age", "23")
w := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/urlencoded"+"?"+form.Encode(), nil)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d", w.Code)
}
if w.Body.String() != "Abiira Nathan" {
t.Errorf("expected Abiira Nathan, got %s", w.Body.String())
}
}
// test sending and reading json data
func TestRouterJSONData(t *testing.T) {
r := rex.NewRouter()
r.POST("/json", func(c *rex.Context) error {
u := User{}
err := c.BodyParser(&u)
if err != nil {
return c.String(err.Error())
}
return c.JSON(u)
})
u := User{
Name: "Abiira Nathan",
Age: 23,
}
body, err := json.Marshal(u)
if err != nil {
t.Error(err)
}
w := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/json", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d", w.Code)
}
var u2 User
json.NewDecoder(w.Body).Decode(&u2)
if !reflect.DeepEqual(u, u2) {
t.Errorf("expected %v, got %v", u, u2)
}
}
func TestBodyParserDerivedTypes(t *testing.T) {
r := rex.NewRouter()
r.POST("/json", func(c *rex.Context) error {
u := User{}
err := c.BodyParser(&u)
if err != nil {
return c.String(err.Error())
}
return c.JSON(u)
})
u := User{
Name: "Abiira Nathan",
Age: 23,
}
body, err := json.Marshal(u)
if err != nil {
t.Error(err)
}
w := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/json", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d", w.Code)
}
var u2 User
json.NewDecoder(w.Body).Decode(&u2)
if !reflect.DeepEqual(u, u2) {
t.Errorf("expected %v, got %v", u, u2)
}
}
// multipart/form-data
func TestRouterMultipartFormData(t *testing.T) {
r := rex.NewRouter()
r.POST("/multipart", func(c *rex.Context) error {
u := User{}
err := c.BodyParser(&u)
if err != nil {
return c.String(err.Error())
}
return c.String(u.Name)
})
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
writer.WriteField("name", "Abiira Nathan")
writer.WriteField("age", "23")
writer.Close()
w := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/multipart", body)
req.Header.Set("Content-Type", writer.FormDataContentType())
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d", w.Code)
}
if w.Body.String() != "Abiira Nathan" {
t.Errorf("expected Abiira Nathan, got %s", w.Body.String())
}
}
// multipart/form-data with file
func TestRouterMultipartFormDataWithFile(t *testing.T) {
r := rex.NewRouter()
r.POST("/upload", func(c *rex.Context) error {
c.Request.ParseMultipartForm(c.Request.ContentLength)
_, fileHeader, err := c.Request.FormFile("file")
if err != nil {
return c.String(err.Error())
}
mpf, err := fileHeader.Open()
if err != nil {
return c.String(err.Error())
}
defer mpf.Close()
buf := &bytes.Buffer{}
_, err = buf.ReadFrom(mpf)
if err != nil {
return c.String(err.Error())
}
_, err = c.Write(buf.Bytes())
return err
})
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile("file", "test.txt")
if err != nil {
t.Error(err)
}
_, err = part.Write([]byte("hello world"))
if err != nil {
t.Error(err)
}
// close writer before creating request
writer.Close()
w := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/upload", body)
req.Header.Set("Content-Type", writer.FormDataContentType())
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d", w.Code)
}
data, err := io.ReadAll(w.Body)
if err != nil {
t.Error(err)
}
if string(data) != "hello world" {
t.Errorf("expected hello world, got %s", string(data))
}
}
type contextType string
const authContextKey contextType = "auth"
// test route middleware
func TestRouterMiddleware(t *testing.T) {
r := rex.NewRouter()
r.Use(func(hf rex.HandlerFunc) rex.HandlerFunc {
return func(c *rex.Context) error {
c.Set(authContextKey, "johndoe")
return hf(c)
}
})
r.GET("/middleware", func(c *rex.Context) error {
auth, ok := c.Get(authContextKey)
if !ok {
c.WriteHeader(http.StatusUnauthorized)
return c.String("no auth")
}
return c.String(auth.(string))
})
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/middleware", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d", w.Code)
}
if w.Body.String() != "johndoe" {
t.Errorf("expected johndoe, got %s", w.Body.String())
}
}
func TestWrapMiddleware(t *testing.T) {
httpMiddleware := func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
*r = *r.WithContext(context.WithValue(r.Context(), "X-Test", "test"))
next.ServeHTTP(w, r)
})
}
r := rex.NewRouter()
r.Use(r.WrapMiddleware(httpMiddleware))
r.GET("/wrap", func(c *rex.Context) error {
return c.String(c.Request.Context().Value("X-Test").(string))
})
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/wrap", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d", w.Code)
}
if w.Body.String() != "test" {
t.Errorf("expected test, got %s", w.Body.String())
}
}
type customResponseWriter struct {
http.ResponseWriter
status int
}
func (w *customResponseWriter) WriteHeader(status int) {
w.status = status
w.ResponseWriter.WriteHeader(status)
}
func (w *customResponseWriter) Status() int {
return w.status
}
func (w *customResponseWriter) Write(b []byte) (int, error) {
if w.status == 0 {
w.status = http.StatusOK
}
return w.ResponseWriter.Write(b)
}
// Test Wrap middleware with custom http.ResponseWriter
func TestWrapMiddlewareWithCustomResponseWriter(t *testing.T) {
logger := func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cw := &customResponseWriter{ResponseWriter: w}
next.ServeHTTP(cw, r)
fmt.Printf("%s %s %d\n", r.Method, r.URL.Path, cw.Status())
})
}
r := rex.NewRouter()
r.Use(r.WrapMiddleware(logger))
r.GET("/wrap", func(c *rex.Context) error {
return c.String("test")
})
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/wrap", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d", w.Code)
}
if w.Body.String() != "test" {
t.Errorf("expected test, got %s", w.Body.String())
}
}
const msgKey contextType = "message"
// test chaining of middlewares
func TestRouterChainMiddleware(t *testing.T) {
r := rex.NewRouter()
r.Use(func(next rex.HandlerFunc) rex.HandlerFunc {
return func(c *rex.Context) error {
c.Set(msgKey, "first")
return next(c)
}
})
r.Use(func(next rex.HandlerFunc) rex.HandlerFunc {
return func(c *rex.Context) error {
message, ok := c.Get(msgKey)
if !ok {
c.WriteHeader(http.StatusInternalServerError)
return c.String("no message")
}
c.Set(msgKey, message.(string)+" second")
return next(c)
}
})
r.GET("/chain", func(c *rex.Context) error {
message, ok := c.Get(msgKey)
if !ok {
c.WriteHeader(http.StatusInternalServerError)
return c.String("no message")
}
return c.String(message.(string))
}, func(next rex.HandlerFunc) rex.HandlerFunc {
return func(c *rex.Context) error {
message, ok := c.Get(msgKey)
if !ok {
c.WriteHeader(http.StatusInternalServerError)
return c.String("no message")
}
c.Set(msgKey, message.(string)+" third")
return next(c)
}
})
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/chain", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d", w.Code)
}
if w.Body.String() != "first second third" {
t.Errorf("expected first second third, got %s", w.Body.String())
}
}
// test render with a base layout
func TestRouterRenderWithBaseLayout(t *testing.T) {
templ, err := rex.ParseTemplates(
"cmd/server/templates",
template.FuncMap{"upper": strings.ToUpper},
".html",
)
if err != nil {
panic(err)
}
options := []rex.RouterOption{
rex.BaseLayout("base.html"),
rex.WithTemplates(templ),
rex.PassContextToViews(true),
rex.ContentBlock("Content"),
}
r := rex.NewRouter(options...)
r.GET("/home_page", func(c *rex.Context) error {
return c.Render("home.html", rex.Map{
"Title": "Home Page",
"Body": "Welcome to the home page",
})
})
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/home_page", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d", w.Code)
}
}
func CopyDir(src, dst string) error {
// create the destination directory
err := os.MkdirAll(dst, 0755)
if err != nil {
return err
}
// get a list of all the files in the source directory
files, err := os.ReadDir(src)
if err != nil {
return err
}
// copy each file to the destination directory
for _, file := range files {
srcFile := filepath.Join(src, file.Name())
dstFile := filepath.Join(dst, file.Name())
// if the file is a directory, copy it recursively
if file.IsDir() {
err = CopyDir(srcFile, dstFile)
if err != nil {
return err
}
} else {
// copy the file
input, err := os.ReadFile(srcFile)
if err != nil {
return err
}
err = os.WriteFile(dstFile, input, 0644)
if err != nil {
return err
}
}
}
return nil
}
func TestRouterStatic(t *testing.T) {
dirname, err := os.MkdirTemp("", "static")
if err != nil {
t.Fatalf("could not create temp dir: %v", err)
}
defer os.RemoveAll(dirname)
file := filepath.Join(dirname, "test.txt")
err = os.WriteFile(file, []byte("hello world"), 0644)
if err != nil {
t.Fatal(err)
}
r := rex.NewRouter()
r.Static("/static", dirname)
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/static/notfound.txt", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusNotFound {
t.Errorf("expected status 404, got %d", w.Code)
}
w = httptest.NewRecorder()
req = httptest.NewRequest("GET", "/static/test.txt", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected status 200, got %d", w.Code)
}
data, err := io.ReadAll(w.Body)
if err != nil {
t.Fatal(err)
}
if string(data) != "hello world" {
t.Errorf("expected hello world, got %s", string(data))
}
}
func TestRouterStaticFS(t *testing.T) {
dirname, err := os.MkdirTemp("", "assests")
if err != nil {
t.Fatalf("could not create temp dir: %v", err)
}
defer os.RemoveAll(dirname)
file := filepath.Join(dirname, "test.txt")
err = os.WriteFile(file, []byte("hello world"), 0644)
if err != nil {
t.Fatal(err)
}
r := rex.NewRouter()
r.StaticFS("/static", http.Dir(dirname))
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/static/notfound.txt", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusNotFound {
t.Errorf("expected status 404, got %d", w.Code)
}
w = httptest.NewRecorder()
req = httptest.NewRequest("GET", "/static/test.txt", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected status 200, got %d", w.Code)
}
data, err := io.ReadAll(w.Body)
if err != nil {
t.Fatal(err)
}
if string(data) != "hello world" {
t.Errorf("expected hello world, got %s", string(data))
}
}
func TestRouterFile(t *testing.T) {
// create a temporary directory for the views
dirname, err := os.MkdirTemp("", "static")
if err != nil {
t.Fatalf("could not create temp dir: %v", err)
}
defer os.RemoveAll(dirname)
file := filepath.Join(dirname, "test.txt")
err = os.WriteFile(file, []byte("hello world"), 0644)
if err != nil {
t.Fatal(err)
}
r := rex.NewRouter()
r.File("/static/test.txt", file)
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/static/test.txt", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d", w.Code)
}
data, err := io.ReadAll(w.Body)
if err != nil {
t.Fatal(err)
}
if string(data) != "hello world" {
t.Errorf("expected hello world, got %s", string(data))
}
}
// test rex.Redirect
func TestRouterRedirect(t *testing.T) {
r := rex.NewRouter()
r.GET("/redirect1", func(c *rex.Context) error {
return c.Redirect("/redirect2", http.StatusFound)
})
r.GET("/redirect2", func(c *rex.Context) error {
return c.String("redirect2")
})
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/redirect1", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusFound {
t.Errorf("expected status 302, got %d", w.Code)
}
// test redirect with params and query
r.GET("/redirect3", func(c *rex.Context) error {
return c.RedirectRoute("/redirect/{name}", rex.RedirectOptions{
Status: http.StatusFound,
Params: map[string]string{"name": "redirect3"},
QueryParams: map[string]string{"name": "abiira"},
})
})
r.GET("/redirect/{name}", func(c *rex.Context) error {
nameParam := c.Param("name") // Loaded from the redirect route params
nameQuery := c.Query("name") // Loaded from the redirect query params
if nameParam != "redirect3" {
t.Errorf("expected redirect3, got %s", nameParam)
}
if nameQuery != "abiira" {
t.Errorf("expected abiira, got %s", nameQuery)
}
return c.String("redirect3")
})
w = httptest.NewRecorder()
req = httptest.NewRequest("GET", "/redirect3", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusFound {
t.Errorf("expected status 302, got %d", w.Code)
}
body := w.Body.String()
if body != "redirect3" {
t.Errorf("expected redirect3, got %s", body)
}
}
// test redirect route
func TestRouterRedirectRoute(t *testing.T) {
r := rex.NewRouter()
r.GET("/redirect_route1", func(c *rex.Context) error {
return c.RedirectRoute("/redirect_route2", rex.RedirectOptions{Status: http.StatusFound})
})
r.GET("/redirect_route2", func(c *rex.Context) error {
status := c.Status()
if status != http.StatusFound {
t.Errorf("expected status 302, got %d", status)
}
return c.String("redirect_route2")
})
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/redirect_route1", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusFound {
t.Errorf("expected status 302, got %d", w.Code)
}
}
// test Query
func TestRouterQuery(t *testing.T) {
r := rex.NewRouter()
r.GET("/query", func(c *rex.Context) error {
return c.String(c.Query("name", "default"))
})
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/query?name=abiira", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d", w.Code)
}
if w.Body.String() != "abiira" {
t.Errorf("expected abiira, got %s", w.Body.String())
}
}
// test QueryInt
func TestRouterQueryInt(t *testing.T) {
r := rex.NewRouter()
r.GET("/queryint", func(c *rex.Context) error {
return c.String(strconv.Itoa(c.QueryInt("age", 0)))
})
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/queryint?age=23", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d", w.Code)
}
if w.Body.String() != "23" {
t.Errorf("expected 23, got %s", w.Body.String())
}
}
// test ParamInt
func TestRouterParamInt(t *testing.T) {
r := rex.NewRouter()
r.GET("/paramint/{age}", func(c *rex.Context) error {
return c.String(c.Param("age"))
})
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/paramint/30", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d", w.Code)
}
if w.Body.String() != "30" {
t.Errorf("expected 30, got %s", w.Body.String())
}
}
// Write a benchmark test for the router
func BenchmarkRouter(b *testing.B) {
r := rex.NewRouter()
r.GET("/benchmark", func(c *rex.Context) error {
return c.String("Hello World!")
})
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/benchmark", nil)
for i := 0; i < b.N; i++ {
r.ServeHTTP(w, req)
}
}
// bench mark full request/response cycle
func BenchmarkRouterFullCycle(b *testing.B) {
r := rex.NewRouter()
r.GET("/benchmark-cycle", func(c *rex.Context) error {
return c.String("Hello World!")
})
ts := httptest.NewServer(r)
defer ts.Close()
for i := 0; i < b.N; i++ {
res, err := http.Get(ts.URL + "/benchmark-cycle")
if err != nil {
b.Fatal(err)
}
if res.StatusCode != http.StatusOK {
b.Fatalf("expected status 200, got %d", res.StatusCode)
}
}
}
func TestRouterExecuteTemplate(t *testing.T) {
templ, err := rex.ParseTemplates("cmd/server/templates",
template.FuncMap{"upper": strings.ToUpper}, ".html")
if err != nil {
panic(err)
}
r := rex.NewRouter(rex.WithTemplates(templ))
r.GET("/template", func(c *rex.Context) error {
data := rex.Map{
"Title": "Template",
"Body": "Welcome to the template page",
}
err := c.ExecuteTemplate("home.html", data)
if err != nil {
t.Errorf("execute template failed")
return err
}
// Test lookup template
templ, err = c.LookupTemplate("home.html")
if err != nil {
t.Errorf("expected to find home.html template")
return err
}
out := new(bytes.Buffer)
err = templ.Execute(out, map[string]any{
"Title": "Template",
"Body": "Named Template",
})
if err != nil {
t.Errorf("execute template failed")
return err
}
if !strings.Contains(out.String(), "Named Template") {
t.Errorf("expected 'Named Template' in templated page, got %s", out.String())
}
return nil
})
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/template", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d", w.Code)
}
// check body
if !strings.Contains(w.Body.String(), "Welcome to the template page") {
t.Errorf("expected Welcome to the template page, got %s", w.Body.String())
}
}
func TestRouterFileFS(t *testing.T) {
dirname, err := os.MkdirTemp("", "assets")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dirname)
file := filepath.Join(dirname, "test.txt")
err = os.WriteFile(file, []byte("hello world"), 0644)
if err != nil {
t.Fatal(err)
}
r := rex.NewRouter()
r.FileFS(http.Dir(dirname), "/static", "test.txt")
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/static", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected status 200, got %d", w.Code)
}
data, err := io.ReadAll(w.Body)
if err != nil {
t.Fatal(err)
}
if string(data) != "hello world" {
t.Errorf("expected hello world, got %s", string(data))
}
}
func TestRouterFaviconFS(t *testing.T) {
dirname, err := os.MkdirTemp("", "assets")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dirname)
file := filepath.Join(dirname, "favicon.ico")
err = os.WriteFile(file, []byte("hello world"), 0644)
if err != nil {
t.Fatal(err)
}
r := rex.NewRouter()
r.FaviconFS(http.Dir(dirname), "favicon.ico")