-
-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathctx_helpers_test.go
More file actions
1540 lines (1272 loc) · 45.6 KB
/
Copy pathctx_helpers_test.go
File metadata and controls
1540 lines (1272 loc) · 45.6 KB
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
// ⚡️ Fiber is an Express inspired web framework written in Go with ☕️
// 🤖 GitHub Repository: https://github.com/gofiber/fiber
// 📌 API Documentation: https://docs.gofiber.io
package fiber
import (
"bytes"
"compress/gzip"
"io"
"net"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"time"
"github.com/gofiber/utils/v2"
"github.com/stretchr/testify/require"
"github.com/valyala/fasthttp"
)
// Splitting a handler into func(fiber.Req) and func(fiber.Res) and passing the
// same Ctx to both is the reason the split exists, so Ctx has to satisfy each.
// A name carried by Req and Res under different signatures breaks that on
// assignment, which no test of the concrete types would catch.
var (
_ Req = (*DefaultCtx)(nil)
_ Res = (*DefaultCtx)(nil)
_ Req = Ctx(nil)
_ Res = Ctx(nil)
)
func Test_Req_RequestHelpersOnReq(t *testing.T) {
t.Parallel()
app := New()
fctx := &fasthttp.RequestCtx{}
fctx.Request.SetRequestURI("/path/here?q=1")
fctx.Request.Header.SetMethod(MethodPost)
fctx.Request.Header.SetHost("example.com")
fctx.Request.Header.SetUserAgent("fiber-test")
fctx.Request.Header.SetReferer("https://referer.example")
fctx.Request.Header.Set(HeaderAcceptLanguage, "en-US, de")
fctx.Request.Header.Set(HeaderAcceptEncoding, "gzip, br")
fctx.Request.Header.Set(HeaderAccept, MIMEApplicationJSON)
fctx.Request.Header.SetContentType(MIMEApplicationJSON + "; charset=utf-8")
fctx.Request.SetBody([]byte(`{"a":1}`))
c := app.AcquireCtx(fctx)
t.Cleanup(func() { app.ReleaseCtx(c) })
r := c.Req()
require.Equal(t, "http://example.com/path/here?q=1", r.FullURL())
require.Equal(t, "fiber-test", r.UserAgent())
require.Equal(t, "https://referer.example", r.Referer())
require.Equal(t, "en-US, de", r.AcceptLanguage())
require.Equal(t, "gzip, br", r.AcceptEncoding())
require.True(t, r.HasHeader(HeaderUserAgent))
require.False(t, r.HasHeader("X-Absent"))
require.Equal(t, MIMEApplicationJSON, r.MediaType()) //nolint:testifylint // this is comparing content-type strings, not JSON content
require.Equal(t, "utf-8", r.Charset())
require.True(t, r.IsJSON())
require.False(t, r.IsForm())
require.False(t, r.IsMultipart())
require.True(t, r.AcceptsJSON())
require.False(t, r.AcceptsHTML())
require.False(t, r.AcceptsXML())
require.False(t, r.AcceptsEventStream())
require.Equal(t, "/path/here", r.Path())
require.False(t, r.Secure())
require.False(t, r.XHR())
require.True(t, r.HasBody())
require.False(t, r.IsWebSocket())
require.False(t, r.IsPreflight())
require.Equal(t, r.FullURL(), c.FullURL())
require.Equal(t, r.UserAgent(), c.UserAgent())
require.Equal(t, r.MediaType(), c.MediaType())
require.Equal(t, r.Path(), c.Path())
require.Equal(t, r.HasBody(), c.HasBody())
require.Equal(t, r.IsPreflight(), c.IsPreflight())
}
func Test_Req_PathOverride(t *testing.T) {
t.Parallel()
app := New()
fctx := &fasthttp.RequestCtx{}
fctx.Request.SetRequestURI("/original")
c := app.AcquireCtx(fctx)
t.Cleanup(func() { app.ReleaseCtx(c) })
require.Equal(t, "/original", c.Req().Path())
require.Equal(t, "/rewritten", c.Req().Path("/rewritten"))
require.Equal(t, "/rewritten", c.Path())
require.Equal(t, "/rewritten", string(c.Request().URI().Path()))
}
func Test_Req_GetAll(t *testing.T) {
t.Parallel()
app := New()
fctx := &fasthttp.RequestCtx{}
fctx.Request.Header.Add("X-Test", "first")
fctx.Request.Header.Add("X-Test", "second")
c := app.AcquireCtx(fctx)
t.Cleanup(func() { app.ReleaseCtx(c) })
require.Equal(t, []string{"first", "second"}, c.Req().GetAll("X-Test"))
require.Equal(t, []string{"first", "second"}, c.Req().GetAll("x-test"))
require.Equal(t, "first", c.Req().Get("X-Test"))
require.Nil(t, c.Req().GetAll("X-Absent"))
}
func Test_Req_ContentLength(t *testing.T) {
t.Parallel()
app := New()
var length int
app.Post("/", func(c Ctx) error {
length = c.Req().ContentLength()
return nil
})
_, err := app.Test(httptest.NewRequest(MethodPost, "/", strings.NewReader("0123456789")))
require.NoError(t, err)
require.Equal(t, 10, length)
chunked := &fasthttp.RequestCtx{}
chunked.Request.Header.SetContentLength(-1)
cc := app.AcquireCtx(chunked)
t.Cleanup(func() { app.ReleaseCtx(cc) })
require.Equal(t, -1, cc.Req().ContentLength(), "chunked bodies report an unknown length")
require.True(t, cc.Req().HasBody(), "an unknown length still means there is a body")
var bodyless int
app.Get("/", func(c Ctx) error {
bodyless = c.Req().ContentLength()
return nil
})
_, err = app.Test(httptest.NewRequest(MethodGet, "/", http.NoBody))
require.NoError(t, err)
require.Equal(t, -2, bodyless)
}
func Test_Req_GetAll_AbsentSlottedHeaders(t *testing.T) {
t.Parallel()
app := New()
var got map[string][]string
var has map[string]bool
app.Get("/", func(c Ctx) error {
got = map[string][]string{}
has = map[string]bool{}
for _, key := range []string{HeaderContentLength, HeaderTrailer, "X-Absent"} {
got[key] = c.Req().GetAll(key)
has[key] = c.Req().HasHeader(key)
}
return nil
})
_, err := app.Test(httptest.NewRequest(MethodGet, "/", http.NoBody))
require.NoError(t, err)
for key, lines := range got {
require.Nil(t, lines, key)
require.False(t, has[key], key)
require.Equal(t, has[key], len(lines) > 0, "GetAll and HasHeader must agree on %s", key)
}
}
func Test_Req_ContentType(t *testing.T) {
t.Parallel()
app := New()
fctx := &fasthttp.RequestCtx{}
fctx.Request.Header.SetContentType(MIMEApplicationJSON + "; charset=utf-8")
c := app.AcquireCtx(fctx)
t.Cleanup(func() { app.ReleaseCtx(c) })
require.Equal(t, MIMEApplicationJSONCharsetUTF8, c.Req().ContentType()) //nolint:testifylint // this is comparing content-type headers, not JSON content
require.Equal(t, MIMEApplicationJSON, c.Req().MediaType(), "MediaType drops the parameters") //nolint:testifylint // same
require.Equal(t, "utf-8", c.Req().Charset())
require.NoError(t, c.SendString("hi"))
c.Type("html")
require.Equal(t, c.Req().ContentType(), c.ContentType())
require.Equal(t, MIMETextHTMLCharsetUTF8, c.Res().ContentType())
}
func Test_Req_BodyStream(t *testing.T) {
t.Parallel()
app := New()
buffered := &fasthttp.RequestCtx{}
buffered.Request.SetBody([]byte("buffered"))
bc := app.AcquireCtx(buffered)
t.Cleanup(func() { app.ReleaseCtx(bc) })
require.Nil(t, bc.Req().BodyStream(), "a buffered body is not a stream")
streamed := &fasthttp.RequestCtx{}
streamed.Request.SetBodyStream(strings.NewReader("streamed"), 8)
sc := app.AcquireCtx(streamed)
t.Cleanup(func() { app.ReleaseCtx(sc) })
stream := sc.Req().BodyStream()
require.NotNil(t, stream)
body, err := io.ReadAll(stream)
require.NoError(t, err)
require.Equal(t, "streamed", string(body))
}
func Test_Req_URI(t *testing.T) {
t.Parallel()
app := New()
fctx := &fasthttp.RequestCtx{}
fctx.Request.SetRequestURI("/search?q=fiber#frag")
fctx.Request.Header.SetHost("example.com")
c := app.AcquireCtx(fctx)
t.Cleanup(func() { app.ReleaseCtx(c) })
uri := c.Req().URI()
require.NotNil(t, uri)
require.Equal(t, "/search", string(uri.Path()))
require.Equal(t, "q=fiber", string(uri.QueryString()))
require.Equal(t, "frag", string(uri.Hash()))
require.Equal(t, "example.com", string(uri.Host()))
}
func Test_Req_Origin(t *testing.T) {
t.Parallel()
app := New()
fctx := &fasthttp.RequestCtx{}
fctx.Request.Header.Set(HeaderOrigin, "https://example.com")
c := app.AcquireCtx(fctx)
t.Cleanup(func() { app.ReleaseCtx(c) })
require.Equal(t, "https://example.com", c.Req().Origin())
bare := app.AcquireCtx(&fasthttp.RequestCtx{})
t.Cleanup(func() { app.ReleaseCtx(bare) })
require.Empty(t, bare.Req().Origin())
}
func Test_Req_Authorization(t *testing.T) {
t.Parallel()
app := New()
tests := []struct {
name string
header string
scheme string
credentials string
bearer string
}{
{name: "absent"},
{name: "bearer", header: "Bearer abc123", scheme: "Bearer", credentials: "abc123", bearer: "abc123"},
{name: "bearer lowercase scheme", header: "bearer abc123", scheme: "bearer", credentials: "abc123", bearer: "abc123"},
{name: "basic", header: "Basic dXNlcjpwYXNz", scheme: "Basic", credentials: "dXNlcjpwYXNz"},
{name: "auth-param list", header: `Digest username="u", realm="r"`, scheme: "Digest", credentials: `username="u", realm="r"`},
{name: "extra whitespace", header: " Bearer abc123 ", scheme: "Bearer", credentials: "abc123", bearer: "abc123"},
{name: "tab separator", header: "Bearer\tabc123", scheme: "Bearer", credentials: "abc123", bearer: "abc123"},
{name: "scheme only", header: "Negotiate", scheme: "Negotiate"},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
fctx := &fasthttp.RequestCtx{}
if tc.header != "" {
fctx.Request.Header.Set(HeaderAuthorization, tc.header)
}
c := app.AcquireCtx(fctx)
t.Cleanup(func() { app.ReleaseCtx(c) })
scheme, credentials := c.Req().Authorization()
require.Equal(t, tc.scheme, scheme)
require.Equal(t, tc.credentials, credentials)
require.Equal(t, tc.bearer, c.Req().Bearer())
})
}
}
func Test_Req_IsSafe_IsIdempotent(t *testing.T) {
t.Parallel()
app := New()
tests := []struct {
method string
safe bool
idempotent bool
}{
{method: MethodGet, safe: true, idempotent: true},
{method: MethodHead, safe: true, idempotent: true},
{method: MethodOptions, safe: true, idempotent: true},
{method: MethodTrace, safe: true, idempotent: true},
{method: MethodPut, safe: false, idempotent: true},
{method: MethodDelete, safe: false, idempotent: true},
{method: MethodPost, safe: false, idempotent: false},
{method: MethodPatch, safe: false, idempotent: false},
}
for _, tc := range tests {
t.Run(tc.method, func(t *testing.T) {
t.Parallel()
fctx := &fasthttp.RequestCtx{}
fctx.Request.Header.SetMethod(tc.method)
c := app.AcquireCtx(fctx)
t.Cleanup(func() { app.ReleaseCtx(c) })
require.Equal(t, tc.safe, c.Req().IsSafe())
require.Equal(t, tc.idempotent, c.Req().IsIdempotent())
})
}
}
func Test_Req_CookieNames_AllCookies(t *testing.T) {
t.Parallel()
app := New()
fctx := &fasthttp.RequestCtx{}
fctx.Request.Header.SetCookie("session", "abc")
fctx.Request.Header.SetCookie("theme", "dark")
c := app.AcquireCtx(fctx)
t.Cleanup(func() { app.ReleaseCtx(c) })
require.ElementsMatch(t, []string{"session", "theme"}, c.Req().CookieNames())
require.Equal(t, map[string]string{"session": "abc", "theme": "dark"}, c.Req().AllCookies())
shadowed := &fasthttp.RequestCtx{}
shadowed.Request.Header.Set(HeaderCookie, "a=first; a=second")
sc := app.AcquireCtx(shadowed)
t.Cleanup(func() { app.ReleaseCtx(sc) })
require.Equal(t, "first", sc.Req().Cookies("a"))
require.Equal(t, "first", sc.Req().AllCookies()["a"])
require.Equal(t, []string{"a", "a"}, sc.Req().CookieNames(), "the repetition itself stays visible")
bare := app.AcquireCtx(&fasthttp.RequestCtx{})
t.Cleanup(func() { app.ReleaseCtx(bare) })
require.Empty(t, bare.Req().CookieNames())
require.Empty(t, bare.Req().AllCookies())
}
func Test_Req_IfNoneMatch(t *testing.T) {
t.Parallel()
app := New()
tests := []struct {
name string
header string
want []string
}{
{name: "absent"},
{name: "single", header: `"abc"`, want: []string{`"abc"`}},
{name: "list", header: `"a", W/"b"`, want: []string{`"a"`, `W/"b"`}},
{name: "wildcard", header: "*", want: []string{"*"}},
{name: "comma inside tag", header: `"v1,v2"`, want: []string{`"v1,v2"`}},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
fctx := &fasthttp.RequestCtx{}
if tc.header != "" {
fctx.Request.Header.Set(HeaderIfNoneMatch, tc.header)
}
c := app.AcquireCtx(fctx)
t.Cleanup(func() { app.ReleaseCtx(c) })
require.Equal(t, tc.want, c.Req().IfNoneMatch())
})
}
}
func Test_Req_IfNoneMatch_MultipleFieldLines(t *testing.T) {
t.Parallel()
app := New()
fctx := &fasthttp.RequestCtx{}
fctx.Request.Header.Add(HeaderIfNoneMatch, `"a"`)
fctx.Request.Header.Add(HeaderIfNoneMatch, `"b"`)
c := app.AcquireCtx(fctx)
t.Cleanup(func() { app.ReleaseCtx(c) })
require.Equal(t, []string{`"a"`, `"b"`}, c.Req().IfNoneMatch())
}
func Test_Req_IfModifiedSince(t *testing.T) {
t.Parallel()
app := New()
bare := app.AcquireCtx(&fasthttp.RequestCtx{})
t.Cleanup(func() { app.ReleaseCtx(bare) })
_, err := bare.Req().IfModifiedSince()
require.ErrorIs(t, err, ErrHeaderNotFound)
fctx := &fasthttp.RequestCtx{}
fctx.Request.Header.Set(HeaderIfModifiedSince, "Wed, 21 Oct 2015 07:28:00 GMT")
c := app.AcquireCtx(fctx)
t.Cleanup(func() { app.ReleaseCtx(c) })
got, err := c.Req().IfModifiedSince()
require.NoError(t, err)
require.True(t, got.Equal(time.Date(2015, time.October, 21, 7, 28, 0, 0, time.UTC)))
malformed := &fasthttp.RequestCtx{}
malformed.Request.Header.Set(HeaderIfModifiedSince, "not a date")
mc := app.AcquireCtx(malformed)
t.Cleanup(func() { app.ReleaseCtx(mc) })
_, err = mc.Req().IfModifiedSince()
require.Error(t, err)
require.NotErrorIs(t, err, ErrHeaderNotFound, "a malformed date is not an absent header")
}
func Test_Res_StatusCode(t *testing.T) {
t.Parallel()
app := New()
c := app.AcquireCtx(&fasthttp.RequestCtx{})
t.Cleanup(func() { app.ReleaseCtx(c) })
require.Equal(t, StatusOK, c.Res().StatusCode(), "an untouched response reports 200")
c.Status(StatusTeapot)
require.Equal(t, StatusTeapot, c.Res().StatusCode())
require.Equal(t, c.Response().StatusCode(), c.Res().StatusCode())
}
func Test_Res_Body_ResetBody_Written(t *testing.T) {
t.Parallel()
app := New()
c := app.AcquireCtx(&fasthttp.RequestCtx{})
t.Cleanup(func() { app.ReleaseCtx(c) })
require.Empty(t, c.Res().Body())
require.False(t, c.Res().Written())
c.Status(StatusCreated)
require.False(t, c.Res().Written())
require.NoError(t, c.SendString("hello"))
require.Equal(t, "hello", string(c.Res().Body()))
require.True(t, c.Res().Written())
c.Res().ResetBody()
require.Empty(t, c.Res().Body())
require.False(t, c.Res().Written())
require.Equal(t, StatusCreated, c.Res().StatusCode(), "ResetBody keeps the status")
}
func Test_Res_Written_BodyStream(t *testing.T) {
t.Parallel()
app := New()
c := app.AcquireCtx(&fasthttp.RequestCtx{})
t.Cleanup(func() { app.ReleaseCtx(c) })
require.NoError(t, c.SendStream(strings.NewReader("streamed"), 8))
require.True(t, c.Res().Written())
require.True(t, c.Response().IsBodyStream())
}
func Test_Res_Del(t *testing.T) {
t.Parallel()
app := New()
c := app.AcquireCtx(&fasthttp.RequestCtx{})
t.Cleanup(func() { app.ReleaseCtx(c) })
c.Set("X-Custom", "value")
require.Equal(t, "value", c.Res().Get("X-Custom"))
c.Res().Del("x-custom")
require.Empty(t, c.Res().Get("X-Custom"))
require.NotPanics(t, func() { c.Res().Del("X-Absent") })
c.Res().Add("X-Multi", "a")
c.Res().Add("X-Multi", "b")
require.Len(t, c.Response().Header.PeekAll("X-Multi"), 2)
c.Res().Del("X-Multi")
require.Empty(t, c.Response().Header.PeekAll("X-Multi"))
c.Cookie(&Cookie{Name: "a", Value: "1"})
require.NotEmpty(t, c.Res().GetCookies())
c.Res().Del(HeaderSetCookie)
require.Empty(t, c.Res().GetCookies())
}
func Test_Res_Add(t *testing.T) {
t.Parallel()
app := New()
c := app.AcquireCtx(&fasthttp.RequestCtx{})
t.Cleanup(func() { app.ReleaseCtx(c) })
c.Res().Add(HeaderWWWAuthenticate, `Basic realm="one"`)
c.Res().Add(HeaderWWWAuthenticate, `Bearer realm="two"`)
lines := c.Response().Header.PeekAll(HeaderWWWAuthenticate)
require.Len(t, lines, 2, "Add keeps challenges on separate field lines")
require.Equal(t, `Basic realm="one"`, string(lines[0]))
require.Equal(t, `Bearer realm="two"`, string(lines[1]))
c.Append("X-Folded", "a")
c.Append("X-Folded", "b")
require.Len(t, c.Response().Header.PeekAll("X-Folded"), 1)
require.Equal(t, "a, b", c.Res().Get("X-Folded"))
}
func Test_Res_ContentType_ContentLength(t *testing.T) {
t.Parallel()
app := New()
c := app.AcquireCtx(&fasthttp.RequestCtx{})
t.Cleanup(func() { app.ReleaseCtx(c) })
require.Equal(t, MIMETextPlainCharsetUTF8, c.Res().ContentType(), "an untouched response reports fasthttp's default")
require.NoError(t, c.JSON(Map{"a": 1}))
require.Equal(t, MIMEApplicationJSONCharsetUTF8, c.Res().ContentType()) //nolint:testifylint // this is comparing content-type headers, not JSON content
c.Type("html")
require.Equal(t, MIMETextHTMLCharsetUTF8, c.Res().ContentType(), "ContentType reads back what Type set")
require.NotEmpty(t, c.Res().Body())
require.Equal(t, 0, c.Res().ContentLength())
c.Set(HeaderContentLength, "42")
require.Equal(t, 42, c.Res().ContentLength())
}
func Test_Res_GetCookie_Cookies(t *testing.T) {
t.Parallel()
app := New()
c := app.AcquireCtx(&fasthttp.RequestCtx{})
t.Cleanup(func() { app.ReleaseCtx(c) })
_, ok := c.Res().GetCookie("absent")
require.False(t, ok)
require.Empty(t, c.Res().GetCookies())
expires := time.Now().Add(time.Hour).UTC().Truncate(time.Second)
c.Cookie(&Cookie{
Name: "session",
Value: "abc",
Path: "/scoped",
Domain: "example.com",
MaxAge: 60,
Expires: expires,
Secure: true,
HTTPOnly: true,
SameSite: CookieSameSiteStrictMode,
})
got, ok := c.Res().GetCookie("session")
require.True(t, ok)
require.Equal(t, "session", got.Name)
require.Equal(t, "abc", got.Value)
require.Equal(t, "/scoped", got.Path)
require.Equal(t, "example.com", got.Domain)
require.Equal(t, 60, got.MaxAge)
require.True(t, got.Secure)
require.True(t, got.HTTPOnly)
require.Equal(t, CookieSameSiteStrictMode, got.SameSite)
require.False(t, got.SessionOnly)
c.Cookie(&Cookie{Name: "flash", Value: "x", SessionOnly: true})
flash, ok := c.Res().GetCookie("flash")
require.True(t, ok)
require.True(t, flash.SessionOnly)
require.Zero(t, flash.MaxAge)
require.True(t, flash.Expires.IsZero())
cookies := c.Res().GetCookies()
require.Len(t, cookies, 2)
names := make([]string, 0, len(cookies))
for _, cookie := range cookies {
names = append(names, cookie.Name)
}
require.ElementsMatch(t, []string{"session", "flash"}, names)
got.Value = "tampered"
again, ok := c.Res().GetCookie("session")
require.True(t, ok)
require.Equal(t, "abc", again.Value)
}
func Test_Res_Cookies_RepeatedNames(t *testing.T) {
t.Parallel()
app := New()
c := app.AcquireCtx(&fasthttp.RequestCtx{})
t.Cleanup(func() { app.ReleaseCtx(c) })
c.Cookie(&Cookie{Name: "sid", Value: "app", Path: "/app"})
c.Res().Add(HeaderSetCookie, "sid=admin; path=/admin")
c.Cookie(&Cookie{Name: "other", Value: "z"})
cookies := c.Res().GetCookies()
require.Len(t, cookies, 3)
type pair struct{ value, path string }
got := make([]pair, 0, len(cookies))
for _, cookie := range cookies {
got = append(got, pair{cookie.Value, cookie.Path})
}
require.ElementsMatch(t, []pair{{"app", "/app"}, {"admin", "/admin"}, {"z", "/"}}, got)
first, ok := c.Res().GetCookie("sid")
require.True(t, ok)
require.Equal(t, "app", first.Value)
over := New()
over.Get("/", func(c Ctx) error {
c.Cookie(&Cookie{Name: "sid", Value: "app", Path: "/app"})
c.Res().Add(HeaderSetCookie, "sid=admin; path=/admin")
c.Cookie(&Cookie{Name: "other", Value: "z"})
return nil
})
resp, err := over.Test(httptest.NewRequest(MethodGet, "/", http.NoBody))
require.NoError(t, err)
require.Len(t, resp.Header.Values(HeaderSetCookie), 3)
}
func Test_Res_GetCookie_Deletion(t *testing.T) {
t.Parallel()
app := New()
c := app.AcquireCtx(&fasthttp.RequestCtx{})
t.Cleanup(func() { app.ReleaseCtx(c) })
c.Cookie(&Cookie{Name: "session", Value: "v", MaxAge: -1})
require.Contains(t, string(c.Response().Header.Peek(HeaderSetCookie)), "max-age=0")
got, ok := c.Res().GetCookie("session")
require.True(t, ok)
require.False(t, got.SessionOnly, "an explicit max-age=0 is a deletion, not a session cookie")
require.Negative(t, got.MaxAge)
got.Domain = "example.com"
c.Cookie(got)
require.Contains(t, string(c.Response().Header.Peek(HeaderSetCookie)), "max-age=0")
rewritten, ok := c.Res().GetCookie("session")
require.True(t, ok)
require.False(t, rewritten.SessionOnly)
require.Equal(t, "example.com", rewritten.Domain)
}
func Test_Res_Body_DoesNotDrainStream(t *testing.T) {
t.Parallel()
app := New()
c := app.AcquireCtx(&fasthttp.RequestCtx{})
t.Cleanup(func() { app.ReleaseCtx(c) })
require.NoError(t, c.SendStream(strings.NewReader("streamed"), 8))
require.True(t, c.Res().Written())
require.Nil(t, c.Res().Body(), "a streamed body is not materialized")
require.True(t, c.Response().IsBodyStream(), "and it is still a stream afterwards")
}
func Test_Res_Add_SpecialHeaders(t *testing.T) {
t.Parallel()
app := New()
c := app.AcquireCtx(&fasthttp.RequestCtx{})
t.Cleanup(func() { app.ReleaseCtx(c) })
c.Set(HeaderContentType, MIMEApplicationJSON)
c.Res().Add(HeaderContentType, MIMETextPlain)
require.Equal(t, MIMETextPlain, c.Res().ContentType(), "Content-Type is replaced, not appended")
require.Len(t, c.Response().Header.PeekAll(HeaderContentType), 1)
c.Res().Add(HeaderLink, "</a>; rel=preload")
c.Res().Add(HeaderLink, "</b>; rel=preload")
require.Len(t, c.Response().Header.PeekAll(HeaderLink), 2)
}
func Test_Res_GetCookie_RoundTrip(t *testing.T) {
t.Parallel()
app := New()
c := app.AcquireCtx(&fasthttp.RequestCtx{})
t.Cleanup(func() { app.ReleaseCtx(c) })
c.Cookie(&Cookie{Name: "session", Value: "plain", Path: "/app", HTTPOnly: true, SameSite: CookieSameSiteLaxMode})
cookie, ok := c.Res().GetCookie("session")
require.True(t, ok)
cookie.Value = "encrypted"
c.Cookie(cookie)
rewritten, ok := c.Res().GetCookie("session")
require.True(t, ok)
require.Equal(t, "encrypted", rewritten.Value)
require.Equal(t, "/app", rewritten.Path, "the other attributes survive the round trip")
require.True(t, rewritten.HTTPOnly)
require.Equal(t, CookieSameSiteLaxMode, rewritten.SameSite)
require.Len(t, c.Res().GetCookies(), 1, "rewriting replaces the cookie rather than adding one")
}
func Test_Res_NoContent(t *testing.T) {
t.Parallel()
app := New()
c := app.AcquireCtx(&fasthttp.RequestCtx{})
t.Cleanup(func() { app.ReleaseCtx(c) })
require.NoError(t, c.JSON(Map{"a": 1}))
require.NotEmpty(t, c.Res().Body())
require.NoError(t, c.Res().NoContent())
require.Equal(t, StatusNoContent, c.Res().StatusCode())
require.Empty(t, c.Res().Body())
require.False(t, c.Res().Written())
require.NotEqual(t, MIMEApplicationJSONCharsetUTF8, c.Res().ContentType(),
"the handler's Content-Type is gone; Test_Res_NoContent_OverHTTP pins that none is sent")
}
func Test_Res_NoContent_OverHTTP(t *testing.T) {
t.Parallel()
app := New()
app.Delete("/item", func(c Ctx) error {
return c.Res().NoContent()
})
resp, err := app.Test(httptest.NewRequest(MethodDelete, "/item", http.NoBody))
require.NoError(t, err)
require.Equal(t, StatusNoContent, resp.StatusCode)
require.Empty(t, resp.Header.Get(HeaderContentType))
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Empty(t, body)
}
func Test_Res_NoContent_DiffersFromSendStatus(t *testing.T) {
t.Parallel()
app := New()
app.Get("/sendstatus", func(c Ctx) error {
c.Type("json")
return c.SendStatus(StatusNoContent)
})
app.Get("/nocontent", func(c Ctx) error {
c.Type("json")
return c.Res().NoContent()
})
sent, err := app.Test(httptest.NewRequest(MethodGet, "/sendstatus", http.NoBody))
require.NoError(t, err)
require.Equal(t, StatusNoContent, sent.StatusCode)
require.NotEmpty(t, sent.Header.Get(HeaderContentType))
none, err := app.Test(httptest.NewRequest(MethodGet, "/nocontent", http.NoBody))
require.NoError(t, err)
require.Equal(t, StatusNoContent, none.StatusCode)
require.Empty(t, none.Header.Get(HeaderContentType))
}
func Test_Ctx_BodyContentLengthCookiesPreferRequest(t *testing.T) {
t.Parallel()
app := New()
fctx := &fasthttp.RequestCtx{}
fctx.Request.SetBody([]byte("request body"))
fctx.Request.Header.SetContentLength(len("request body"))
fctx.Request.Header.SetCookie("who", "client")
c := app.AcquireCtx(fctx)
t.Cleanup(func() { app.ReleaseCtx(c) })
require.NoError(t, c.SendString("response body"))
c.Cookie(&Cookie{Name: "who", Value: "server"})
require.Equal(t, "request body", string(c.Body()))
require.Equal(t, "request body", string(c.Req().Body()))
require.Equal(t, "response body", string(c.Res().Body()))
require.Equal(t, len("request body"), c.ContentLength())
require.Equal(t, len("request body"), c.Req().ContentLength())
require.Equal(t, "client", c.Cookies("who"))
require.Equal(t, "client", c.Req().Cookies("who"))
require.Equal(t, "fallback", c.Cookies("absent", "fallback"))
serverCookies := c.Res().GetCookies()
require.Len(t, serverCookies, 1)
require.Equal(t, "server", serverCookies[0].Value)
require.Equal(t, c.Req().ContentType(), c.ContentType())
}
func Test_Ctx_ID_StartTime_Elapsed(t *testing.T) {
t.Parallel()
app := New()
var (
id uint64
stable bool
start time.Time
elapsed time.Duration
)
app.Get("/", func(c Ctx) error {
id = c.ID()
stable = c.ID() == id
start = c.StartTime()
elapsed = c.Elapsed()
return nil
})
_, err := app.Test(httptest.NewRequest(MethodGet, "/", http.NoBody))
require.NoError(t, err)
require.NotZero(t, id)
require.True(t, stable, "ID is stable within a request")
require.False(t, start.IsZero())
require.GreaterOrEqual(t, elapsed, time.Duration(0))
require.Less(t, elapsed, time.Minute, "Elapsed measures from StartTime, not from the epoch")
}
func Test_Ctx_LocalAddr_RemoteAddr(t *testing.T) {
t.Parallel()
app := New()
var local, remote net.Addr
app.Get("/", func(c Ctx) error {
local = c.LocalAddr()
remote = c.RemoteAddr()
return nil
})
_, err := app.Test(httptest.NewRequest(MethodGet, "/", http.NoBody))
require.NoError(t, err)
require.NotNil(t, local)
require.NotNil(t, remote)
require.NotEmpty(t, remote.Network())
}
func Test_Ctx_Hijack(t *testing.T) {
t.Parallel()
app := New()
c := app.AcquireCtx(&fasthttp.RequestCtx{})
t.Cleanup(func() { app.ReleaseCtx(c) })
require.False(t, c.Hijacked())
c.Hijack(func(net.Conn) {})
require.True(t, c.Hijacked())
}
func Test_Ctx_RouteName(t *testing.T) {
t.Parallel()
app := New()
var mwName, handlerName string
app.Use(func(c Ctx) error {
mwName = c.RouteName()
return c.Next()
})
app.Get("/home", func(c Ctx) error {
handlerName = c.RouteName()
return nil
}).Name("home")
_, err := app.Test(httptest.NewRequest(MethodGet, "/home", http.NoBody))
require.NoError(t, err)
require.Equal(t, "home", handlerName)
require.Empty(t, mwName, "middleware reports its own unnamed route, not the endpoint's")
}
func Test_Ctx_RouteName_Unmatched(t *testing.T) {
t.Parallel()
app := New()
c := app.AcquireCtx(&fasthttp.RequestCtx{})
t.Cleanup(func() { app.ReleaseCtx(c) })
require.NotPanics(t, func() { require.Empty(t, c.RouteName()) })
}
func Test_Ctx_IsFinal(t *testing.T) {
t.Parallel()
app := New()
var (
inGlobalMW bool
inRouteMW bool
inHandler bool
)
app.Use(func(c Ctx) error {
inGlobalMW = c.IsFinal()
return c.Next()
})
app.Get("/chain", func(c Ctx) error {
inRouteMW = c.IsFinal()
return c.Next()
}, func(c Ctx) error {
inHandler = c.IsFinal()
return nil
})
_, err := app.Test(httptest.NewRequest(MethodGet, "/chain", http.NoBody))
require.NoError(t, err)
require.False(t, inGlobalMW)
require.False(t, inRouteMW, "a route handler with another after it is not final")
require.True(t, inHandler)
c := app.AcquireCtx(&fasthttp.RequestCtx{})
t.Cleanup(func() { app.ReleaseCtx(c) })
require.False(t, c.IsFinal())
require.False(t, c.IsMiddleware())
}
func Test_Ctx_IsFinal_ScopedToTheRoute(t *testing.T) {
t.Parallel()
terminal := New()
var inUse bool
terminal.Use(func(c Ctx) error {
inUse = c.IsFinal()
return c.SendString("done")
})
_, err := terminal.Test(httptest.NewRequest(MethodGet, "/anything", http.NoBody))
require.NoError(t, err)
require.False(t, inUse, "a Use route is middleware by registration, whatever its position")
overlapping := New()
var inSpecific, inCatchAll bool
overlapping.Get("/specific", func(c Ctx) error {
inSpecific = c.IsFinal()
return c.Next()
})
overlapping.Get("/*", func(_ Ctx) error {
inCatchAll = true
return nil
})
_, err = overlapping.Test(httptest.NewRequest(MethodGet, "/specific", http.NoBody))
require.NoError(t, err)
require.True(t, inSpecific, "it is the last handler of its own route")
require.True(t, inCatchAll, "but another route still matched after it")
}
func Test_Ctx_MountPath(t *testing.T) {
t.Parallel()
micro := New()
var mounted, mountedPath string
micro.Get("/doe", func(c Ctx) error {
mounted = c.MountPath()
mountedPath = strings.Clone(c.Path())
return nil
})
app := New()
var top string
app.Get("/top", func(c Ctx) error {
top = c.MountPath()
return nil
})
app.Use("/john", micro)
_, err := app.Test(httptest.NewRequest(MethodGet, "/john/doe", http.NoBody))
require.NoError(t, err)
_, err = app.Test(httptest.NewRequest(MethodGet, "/top", http.NoBody))
require.NoError(t, err)
var standalone string
micro.Get("/solo", func(c Ctx) error {
standalone = c.MountPath()
return nil
})
_, err = micro.Test(httptest.NewRequest(MethodGet, "/solo", http.NoBody))
require.NoError(t, err)
require.Empty(t, standalone)
require.Equal(t, "/john", micro.MountPath(), "App.MountPath still reports the mount")
require.Equal(t, "/john", mounted)
require.Equal(t, "/john/doe", mountedPath,
"Fiber bakes the prefix into the cloned route, so Path is not relative to the mount")
require.True(t, strings.HasPrefix(mountedPath, mounted), "the served path lives under MountPath")
require.Empty(t, top, "the top-level app is not mounted under anything")
}
func Test_Ctx_Error(t *testing.T) {
t.Parallel()