-
Notifications
You must be signed in to change notification settings - Fork 8k
/
context_test.go
3125 lines (2596 loc) · 91.5 KB
/
context_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
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package gin
import (
"bytes"
"context"
"errors"
"fmt"
"html/template"
"io"
"io/fs"
"mime/multipart"
"net"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"reflect"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/gin-contrib/sse"
"github.com/gin-gonic/gin/binding"
testdata "github.com/gin-gonic/gin/testdata/protoexample"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/proto"
)
var _ context.Context = (*Context)(nil)
var errTestRender = errors.New("TestRender")
// Unit tests TODO
// func (c *Context) File(filepath string) {
// func (c *Context) Negotiate(code int, config Negotiate) {
// BAD case: func (c *Context) Render(code int, render render.Render, obj ...any) {
// test that information is not leaked when reusing Contexts (using the Pool)
func createMultipartRequest() *http.Request {
boundary := "--testboundary"
body := new(bytes.Buffer)
mw := multipart.NewWriter(body)
defer mw.Close()
must(mw.SetBoundary(boundary))
must(mw.WriteField("foo", "bar"))
must(mw.WriteField("bar", "10"))
must(mw.WriteField("bar", "foo2"))
must(mw.WriteField("array", "first"))
must(mw.WriteField("array", "second"))
must(mw.WriteField("id", ""))
must(mw.WriteField("time_local", "31/12/2016 14:55"))
must(mw.WriteField("time_utc", "31/12/2016 14:55"))
must(mw.WriteField("time_location", "31/12/2016 14:55"))
must(mw.WriteField("names[a]", "thinkerou"))
must(mw.WriteField("names[b]", "tianou"))
req, err := http.NewRequest(http.MethodPost, "/", body)
must(err)
req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)
return req
}
func must(err error) {
if err != nil {
panic(err.Error())
}
}
func TestContextFormFile(t *testing.T) {
buf := new(bytes.Buffer)
mw := multipart.NewWriter(buf)
w, err := mw.CreateFormFile("file", "test")
require.NoError(t, err)
_, err = w.Write([]byte("test"))
require.NoError(t, err)
mw.Close()
c, _ := CreateTestContext(httptest.NewRecorder())
c.Request, _ = http.NewRequest(http.MethodPost, "/", buf)
c.Request.Header.Set("Content-Type", mw.FormDataContentType())
f, err := c.FormFile("file")
require.NoError(t, err)
assert.Equal(t, "test", f.Filename)
require.NoError(t, c.SaveUploadedFile(f, "test"))
}
func TestContextFormFileFailed(t *testing.T) {
buf := new(bytes.Buffer)
mw := multipart.NewWriter(buf)
mw.Close()
c, _ := CreateTestContext(httptest.NewRecorder())
c.Request, _ = http.NewRequest(http.MethodPost, "/", nil)
c.Request.Header.Set("Content-Type", mw.FormDataContentType())
c.engine.MaxMultipartMemory = 8 << 20
f, err := c.FormFile("file")
require.Error(t, err)
assert.Nil(t, f)
}
func TestContextMultipartForm(t *testing.T) {
buf := new(bytes.Buffer)
mw := multipart.NewWriter(buf)
require.NoError(t, mw.WriteField("foo", "bar"))
w, err := mw.CreateFormFile("file", "test")
require.NoError(t, err)
_, err = w.Write([]byte("test"))
require.NoError(t, err)
mw.Close()
c, _ := CreateTestContext(httptest.NewRecorder())
c.Request, _ = http.NewRequest(http.MethodPost, "/", buf)
c.Request.Header.Set("Content-Type", mw.FormDataContentType())
f, err := c.MultipartForm()
require.NoError(t, err)
assert.NotNil(t, f)
require.NoError(t, c.SaveUploadedFile(f.File["file"][0], "test"))
}
func TestSaveUploadedOpenFailed(t *testing.T) {
buf := new(bytes.Buffer)
mw := multipart.NewWriter(buf)
mw.Close()
c, _ := CreateTestContext(httptest.NewRecorder())
c.Request, _ = http.NewRequest(http.MethodPost, "/", buf)
c.Request.Header.Set("Content-Type", mw.FormDataContentType())
f := &multipart.FileHeader{
Filename: "file",
}
require.Error(t, c.SaveUploadedFile(f, "test"))
}
func TestSaveUploadedCreateFailed(t *testing.T) {
buf := new(bytes.Buffer)
mw := multipart.NewWriter(buf)
w, err := mw.CreateFormFile("file", "test")
require.NoError(t, err)
_, err = w.Write([]byte("test"))
require.NoError(t, err)
mw.Close()
c, _ := CreateTestContext(httptest.NewRecorder())
c.Request, _ = http.NewRequest(http.MethodPost, "/", buf)
c.Request.Header.Set("Content-Type", mw.FormDataContentType())
f, err := c.FormFile("file")
require.NoError(t, err)
assert.Equal(t, "test", f.Filename)
require.Error(t, c.SaveUploadedFile(f, "/"))
}
func TestSaveUploadedFileWithPermission(t *testing.T) {
buf := new(bytes.Buffer)
mw := multipart.NewWriter(buf)
w, err := mw.CreateFormFile("file", "permission_test")
require.NoError(t, err)
_, err = w.Write([]byte("permission_test"))
require.NoError(t, err)
mw.Close()
c, _ := CreateTestContext(httptest.NewRecorder())
c.Request, _ = http.NewRequest("POST", "/", buf)
c.Request.Header.Set("Content-Type", mw.FormDataContentType())
f, err := c.FormFile("file")
require.NoError(t, err)
assert.Equal(t, "permission_test", f.Filename)
var mode fs.FileMode = 0o755
require.NoError(t, c.SaveUploadedFile(f, "permission_test", mode))
info, err := os.Stat(filepath.Dir("permission_test"))
require.NoError(t, err)
assert.Equal(t, info.Mode().Perm(), mode)
}
func TestSaveUploadedFileWithPermissionFailed(t *testing.T) {
buf := new(bytes.Buffer)
mw := multipart.NewWriter(buf)
w, err := mw.CreateFormFile("file", "permission_test")
require.NoError(t, err)
_, err = w.Write([]byte("permission_test"))
require.NoError(t, err)
mw.Close()
c, _ := CreateTestContext(httptest.NewRecorder())
c.Request, _ = http.NewRequest("POST", "/", buf)
c.Request.Header.Set("Content-Type", mw.FormDataContentType())
f, err := c.FormFile("file")
require.NoError(t, err)
assert.Equal(t, "permission_test", f.Filename)
var mode fs.FileMode = 0o644
require.Error(t, c.SaveUploadedFile(f, "test/permission_test", mode))
}
func TestContextReset(t *testing.T) {
router := New()
c := router.allocateContext(0)
assert.Equal(t, c.engine, router)
c.index = 2
c.Writer = &responseWriter{ResponseWriter: httptest.NewRecorder()}
c.Params = Params{Param{}}
c.Error(errors.New("test")) //nolint: errcheck
c.Set("foo", "bar")
c.reset()
assert.False(t, c.IsAborted())
assert.Nil(t, c.Keys)
assert.Nil(t, c.Accepted)
assert.Empty(t, c.Errors)
assert.Empty(t, c.Errors.Errors())
assert.Empty(t, c.Errors.ByType(ErrorTypeAny))
assert.Empty(t, c.Params)
assert.EqualValues(t, c.index, -1)
assert.Equal(t, c.Writer.(*responseWriter), &c.writermem)
}
func TestContextHandlers(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
assert.Nil(t, c.handlers)
assert.Nil(t, c.handlers.Last())
c.handlers = HandlersChain{}
assert.NotNil(t, c.handlers)
assert.Nil(t, c.handlers.Last())
f := func(c *Context) {}
g := func(c *Context) {}
c.handlers = HandlersChain{f}
compareFunc(t, f, c.handlers.Last())
c.handlers = HandlersChain{f, g}
compareFunc(t, g, c.handlers.Last())
}
// TestContextSetGet tests that a parameter is set correctly on the
// current context and can be retrieved using Get.
func TestContextSetGet(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
c.Set("foo", "bar")
value, err := c.Get("foo")
assert.Equal(t, "bar", value)
assert.True(t, err)
value, err = c.Get("foo2")
assert.Nil(t, value)
assert.False(t, err)
assert.Equal(t, "bar", c.MustGet("foo"))
assert.Panics(t, func() { c.MustGet("no_exist") })
}
func TestContextSetGetValues(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
c.Set("string", "this is a string")
c.Set("int32", int32(-42))
c.Set("int64", int64(42424242424242))
c.Set("uint64", uint64(42))
c.Set("float32", float32(4.2))
c.Set("float64", 4.2)
var a any = 1
c.Set("intInterface", a)
assert.Exactly(t, "this is a string", c.MustGet("string").(string))
assert.Exactly(t, c.MustGet("int32").(int32), int32(-42))
assert.Exactly(t, int64(42424242424242), c.MustGet("int64").(int64))
assert.Exactly(t, uint64(42), c.MustGet("uint64").(uint64))
assert.InDelta(t, float32(4.2), c.MustGet("float32").(float32), 0.01)
assert.InDelta(t, 4.2, c.MustGet("float64").(float64), 0.01)
assert.Exactly(t, 1, c.MustGet("intInterface").(int))
}
func TestContextGetString(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
c.Set("string", "this is a string")
assert.Equal(t, "this is a string", c.GetString("string"))
}
func TestContextSetGetBool(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
c.Set("bool", true)
assert.True(t, c.GetBool("bool"))
}
func TestContextGetInt(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
c.Set("int", 1)
assert.Equal(t, 1, c.GetInt("int"))
}
func TestContextGetInt8(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
key := "int8"
value := int8(0x7F)
c.Set(key, value)
assert.Equal(t, value, c.GetInt8(key))
}
func TestContextGetInt16(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
key := "int16"
value := int16(0x7FFF)
c.Set(key, value)
assert.Equal(t, value, c.GetInt16(key))
}
func TestContextGetInt32(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
key := "int32"
value := int32(0x7FFFFFFF)
c.Set(key, value)
assert.Equal(t, value, c.GetInt32(key))
}
func TestContextGetInt64(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
c.Set("int64", int64(42424242424242))
assert.Equal(t, int64(42424242424242), c.GetInt64("int64"))
}
func TestContextGetUint(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
c.Set("uint", uint(1))
assert.Equal(t, uint(1), c.GetUint("uint"))
}
func TestContextGetUint8(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
key := "uint8"
value := uint8(0xFF)
c.Set(key, value)
assert.Equal(t, value, c.GetUint8(key))
}
func TestContextGetUint16(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
key := "uint16"
value := uint16(0xFFFF)
c.Set(key, value)
assert.Equal(t, value, c.GetUint16(key))
}
func TestContextGetUint32(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
key := "uint32"
value := uint32(0xFFFFFFFF)
c.Set(key, value)
assert.Equal(t, value, c.GetUint32(key))
}
func TestContextGetUint64(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
c.Set("uint64", uint64(18446744073709551615))
assert.Equal(t, uint64(18446744073709551615), c.GetUint64("uint64"))
}
func TestContextGetFloat32(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
key := "float32"
value := float32(3.14)
c.Set(key, value)
assert.InDelta(t, value, c.GetFloat32(key), 0.01)
}
func TestContextGetFloat64(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
c.Set("float64", 4.2)
assert.InDelta(t, 4.2, c.GetFloat64("float64"), 0.01)
}
func TestContextGetTime(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
t1, _ := time.Parse("1/2/2006 15:04:05", "01/01/2017 12:00:00")
c.Set("time", t1)
assert.Equal(t, t1, c.GetTime("time"))
}
func TestContextGetDuration(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
c.Set("duration", time.Second)
assert.Equal(t, time.Second, c.GetDuration("duration"))
}
func TestContextGetIntSlice(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
key := "int-slice"
value := []int{1, 2}
c.Set(key, value)
assert.Equal(t, value, c.GetIntSlice(key))
}
func TestContextGetInt8Slice(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
key := "int8-slice"
value := []int8{1, 2}
c.Set(key, value)
assert.Equal(t, value, c.GetInt8Slice(key))
}
func TestContextGetInt16Slice(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
key := "int16-slice"
value := []int16{1, 2}
c.Set(key, value)
assert.Equal(t, value, c.GetInt16Slice(key))
}
func TestContextGetInt32Slice(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
key := "int32-slice"
value := []int32{1, 2}
c.Set(key, value)
assert.Equal(t, value, c.GetInt32Slice(key))
}
func TestContextGetInt64Slice(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
key := "int64-slice"
value := []int64{1, 2}
c.Set(key, value)
assert.Equal(t, value, c.GetInt64Slice(key))
}
func TestContextGetUintSlice(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
key := "uint-slice"
value := []uint{1, 2}
c.Set(key, value)
assert.Equal(t, value, c.GetUintSlice(key))
}
func TestContextGetUint8Slice(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
key := "uint8-slice"
value := []uint8{1, 2}
c.Set(key, value)
assert.Equal(t, value, c.GetUint8Slice(key))
}
func TestContextGetUint16Slice(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
key := "uint16-slice"
value := []uint16{1, 2}
c.Set(key, value)
assert.Equal(t, value, c.GetUint16Slice(key))
}
func TestContextGetUint32Slice(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
key := "uint32-slice"
value := []uint32{1, 2}
c.Set(key, value)
assert.Equal(t, value, c.GetUint32Slice(key))
}
func TestContextGetUint64Slice(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
key := "uint64-slice"
value := []uint64{1, 2}
c.Set(key, value)
assert.Equal(t, value, c.GetUint64Slice(key))
}
func TestContextGetFloat32Slice(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
key := "float32-slice"
value := []float32{1, 2}
c.Set(key, value)
assert.Equal(t, value, c.GetFloat32Slice(key))
}
func TestContextGetFloat64Slice(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
key := "float64-slice"
value := []float64{1, 2}
c.Set(key, value)
assert.Equal(t, value, c.GetFloat64Slice(key))
}
func TestContextGetStringSlice(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
c.Set("slice", []string{"foo"})
assert.Equal(t, []string{"foo"}, c.GetStringSlice("slice"))
}
func TestContextGetStringMap(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
m := make(map[string]any)
m["foo"] = 1
c.Set("map", m)
assert.Equal(t, m, c.GetStringMap("map"))
assert.Equal(t, 1, c.GetStringMap("map")["foo"])
}
func TestContextGetStringMapString(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
m := make(map[string]string)
m["foo"] = "bar"
c.Set("map", m)
assert.Equal(t, m, c.GetStringMapString("map"))
assert.Equal(t, "bar", c.GetStringMapString("map")["foo"])
}
func TestContextGetStringMapStringSlice(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
m := make(map[string][]string)
m["foo"] = []string{"foo"}
c.Set("map", m)
assert.Equal(t, m, c.GetStringMapStringSlice("map"))
assert.Equal(t, []string{"foo"}, c.GetStringMapStringSlice("map")["foo"])
}
func TestContextCopy(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
c.index = 2
c.Request, _ = http.NewRequest(http.MethodPost, "/hola", nil)
c.handlers = HandlersChain{func(c *Context) {}}
c.Params = Params{Param{Key: "foo", Value: "bar"}}
c.Set("foo", "bar")
c.fullPath = "/hola"
cp := c.Copy()
assert.Nil(t, cp.handlers)
assert.Nil(t, cp.writermem.ResponseWriter)
assert.Equal(t, &cp.writermem, cp.Writer.(*responseWriter))
assert.Equal(t, cp.Request, c.Request)
assert.Equal(t, abortIndex, cp.index)
assert.Equal(t, cp.Keys, c.Keys)
assert.Equal(t, cp.engine, c.engine)
assert.Equal(t, cp.Params, c.Params)
cp.Set("foo", "notBar")
assert.NotEqual(t, cp.Keys["foo"], c.Keys["foo"])
assert.Equal(t, cp.fullPath, c.fullPath)
}
func TestContextHandlerName(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
c.handlers = HandlersChain{func(c *Context) {}, handlerNameTest}
assert.Regexp(t, "^(.*/vendor/)?github.com/gin-gonic/gin.handlerNameTest$", c.HandlerName())
}
func TestContextHandlerNames(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
c.handlers = HandlersChain{func(c *Context) {}, nil, handlerNameTest, func(c *Context) {}, handlerNameTest2}
names := c.HandlerNames()
assert.Len(t, names, 4)
for _, name := range names {
assert.Regexp(t, `^(.*/vendor/)?(github\.com/gin-gonic/gin\.){1}(TestContextHandlerNames\.func.*){0,1}(handlerNameTest.*){0,1}`, name)
}
}
func handlerNameTest(c *Context) {
}
func handlerNameTest2(c *Context) {
}
var handlerTest HandlerFunc = func(c *Context) {
}
func TestContextHandler(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
c.handlers = HandlersChain{func(c *Context) {}, handlerTest}
assert.Equal(t, reflect.ValueOf(handlerTest).Pointer(), reflect.ValueOf(c.Handler()).Pointer())
}
func TestContextQuery(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
c.Request, _ = http.NewRequest(http.MethodGet, "http://example.com/?foo=bar&page=10&id=", nil)
value, ok := c.GetQuery("foo")
assert.True(t, ok)
assert.Equal(t, "bar", value)
assert.Equal(t, "bar", c.DefaultQuery("foo", "none"))
assert.Equal(t, "bar", c.Query("foo"))
value, ok = c.GetQuery("page")
assert.True(t, ok)
assert.Equal(t, "10", value)
assert.Equal(t, "10", c.DefaultQuery("page", "0"))
assert.Equal(t, "10", c.Query("page"))
value, ok = c.GetQuery("id")
assert.True(t, ok)
assert.Empty(t, value)
assert.Empty(t, c.DefaultQuery("id", "nada"))
assert.Empty(t, c.Query("id"))
value, ok = c.GetQuery("NoKey")
assert.False(t, ok)
assert.Empty(t, value)
assert.Equal(t, "nada", c.DefaultQuery("NoKey", "nada"))
assert.Empty(t, c.Query("NoKey"))
// postform should not mess
value, ok = c.GetPostForm("page")
assert.False(t, ok)
assert.Empty(t, value)
assert.Empty(t, c.PostForm("foo"))
}
func TestContextInitQueryCache(t *testing.T) {
validURL, err := url.Parse("https://github.com/gin-gonic/gin/pull/3969?key=value&otherkey=othervalue")
require.NoError(t, err)
tests := []struct {
testName string
testContext *Context
expectedQueryCache url.Values
}{
{
testName: "queryCache should remain unchanged if already not nil",
testContext: &Context{
queryCache: url.Values{"a": []string{"b"}},
Request: &http.Request{URL: validURL}, // valid request for evidence that values weren't extracted
},
expectedQueryCache: url.Values{"a": []string{"b"}},
},
{
testName: "queryCache should be empty when Request is nil",
testContext: &Context{Request: nil}, // explicit nil for readability
expectedQueryCache: url.Values{},
},
{
testName: "queryCache should be empty when Request.URL is nil",
testContext: &Context{Request: &http.Request{URL: nil}}, // explicit nil for readability
expectedQueryCache: url.Values{},
},
{
testName: "queryCache should be populated when it not yet populated and Request + Request.URL are non nil",
testContext: &Context{Request: &http.Request{URL: validURL}}, // explicit nil for readability
expectedQueryCache: url.Values{"key": []string{"value"}, "otherkey": []string{"othervalue"}},
},
}
for _, test := range tests {
t.Run(test.testName, func(t *testing.T) {
test.testContext.initQueryCache()
assert.Equal(t, test.expectedQueryCache, test.testContext.queryCache)
})
}
}
func TestContextDefaultQueryOnEmptyRequest(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder()) // here c.Request == nil
assert.NotPanics(t, func() {
value, ok := c.GetQuery("NoKey")
assert.False(t, ok)
assert.Empty(t, value)
})
assert.NotPanics(t, func() {
assert.Equal(t, "nada", c.DefaultQuery("NoKey", "nada"))
})
assert.NotPanics(t, func() {
assert.Empty(t, c.Query("NoKey"))
})
}
func TestContextQueryAndPostForm(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
body := bytes.NewBufferString("foo=bar&page=11&both=&foo=second")
c.Request, _ = http.NewRequest(http.MethodPost,
"/?both=GET&id=main&id=omit&array[]=first&array[]=second&ids[a]=hi&ids[b]=3.14", body)
c.Request.Header.Add("Content-Type", MIMEPOSTForm)
assert.Equal(t, "bar", c.DefaultPostForm("foo", "none"))
assert.Equal(t, "bar", c.PostForm("foo"))
assert.Empty(t, c.Query("foo"))
value, ok := c.GetPostForm("page")
assert.True(t, ok)
assert.Equal(t, "11", value)
assert.Equal(t, "11", c.DefaultPostForm("page", "0"))
assert.Equal(t, "11", c.PostForm("page"))
assert.Empty(t, c.Query("page"))
value, ok = c.GetPostForm("both")
assert.True(t, ok)
assert.Empty(t, value)
assert.Empty(t, c.PostForm("both"))
assert.Empty(t, c.DefaultPostForm("both", "nothing"))
assert.Equal(t, http.MethodGet, c.Query("both"), http.MethodGet)
value, ok = c.GetQuery("id")
assert.True(t, ok)
assert.Equal(t, "main", value)
assert.Equal(t, "000", c.DefaultPostForm("id", "000"))
assert.Equal(t, "main", c.Query("id"))
assert.Empty(t, c.PostForm("id"))
value, ok = c.GetQuery("NoKey")
assert.False(t, ok)
assert.Empty(t, value)
value, ok = c.GetPostForm("NoKey")
assert.False(t, ok)
assert.Empty(t, value)
assert.Equal(t, "nada", c.DefaultPostForm("NoKey", "nada"))
assert.Equal(t, "nothing", c.DefaultQuery("NoKey", "nothing"))
assert.Empty(t, c.PostForm("NoKey"))
assert.Empty(t, c.Query("NoKey"))
var obj struct {
Foo string `form:"foo"`
ID string `form:"id"`
Page int `form:"page"`
Both string `form:"both"`
Array []string `form:"array[]"`
}
require.NoError(t, c.Bind(&obj))
assert.Equal(t, "bar", obj.Foo, "bar")
assert.Equal(t, "main", obj.ID, "main")
assert.Equal(t, 11, obj.Page, 11)
assert.Empty(t, obj.Both)
assert.Equal(t, []string{"first", "second"}, obj.Array)
values, ok := c.GetQueryArray("array[]")
assert.True(t, ok)
assert.Equal(t, "first", values[0])
assert.Equal(t, "second", values[1])
values = c.QueryArray("array[]")
assert.Equal(t, "first", values[0])
assert.Equal(t, "second", values[1])
values = c.QueryArray("nokey")
assert.Empty(t, values)
values = c.QueryArray("both")
assert.Len(t, values, 1)
assert.Equal(t, http.MethodGet, values[0])
dicts, ok := c.GetQueryMap("ids")
assert.True(t, ok)
assert.Equal(t, "hi", dicts["a"])
assert.Equal(t, "3.14", dicts["b"])
dicts, ok = c.GetQueryMap("nokey")
assert.False(t, ok)
assert.Empty(t, dicts)
dicts, ok = c.GetQueryMap("both")
assert.False(t, ok)
assert.Empty(t, dicts)
dicts, ok = c.GetQueryMap("array")
assert.False(t, ok)
assert.Empty(t, dicts)
dicts = c.QueryMap("ids")
assert.Equal(t, "hi", dicts["a"])
assert.Equal(t, "3.14", dicts["b"])
dicts = c.QueryMap("nokey")
assert.Empty(t, dicts)
}
func TestContextPostFormMultipart(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
c.Request = createMultipartRequest()
var obj struct {
Foo string `form:"foo"`
Bar string `form:"bar"`
BarAsInt int `form:"bar"`
Array []string `form:"array"`
ID string `form:"id"`
TimeLocal time.Time `form:"time_local" time_format:"02/01/2006 15:04"`
TimeUTC time.Time `form:"time_utc" time_format:"02/01/2006 15:04" time_utc:"1"`
TimeLocation time.Time `form:"time_location" time_format:"02/01/2006 15:04" time_location:"Asia/Tokyo"`
BlankTime time.Time `form:"blank_time" time_format:"02/01/2006 15:04"`
}
require.NoError(t, c.Bind(&obj))
assert.Equal(t, "bar", obj.Foo)
assert.Equal(t, "10", obj.Bar)
assert.Equal(t, 10, obj.BarAsInt)
assert.Equal(t, []string{"first", "second"}, obj.Array)
assert.Empty(t, obj.ID)
assert.Equal(t, "31/12/2016 14:55", obj.TimeLocal.Format("02/01/2006 15:04"))
assert.Equal(t, time.Local, obj.TimeLocal.Location())
assert.Equal(t, "31/12/2016 14:55", obj.TimeUTC.Format("02/01/2006 15:04"))
assert.Equal(t, time.UTC, obj.TimeUTC.Location())
loc, _ := time.LoadLocation("Asia/Tokyo")
assert.Equal(t, "31/12/2016 14:55", obj.TimeLocation.Format("02/01/2006 15:04"))
assert.Equal(t, loc, obj.TimeLocation.Location())
assert.True(t, obj.BlankTime.IsZero())
value, ok := c.GetQuery("foo")
assert.False(t, ok)
assert.Empty(t, value)
assert.Empty(t, c.Query("bar"))
assert.Equal(t, "nothing", c.DefaultQuery("id", "nothing"))
value, ok = c.GetPostForm("foo")
assert.True(t, ok)
assert.Equal(t, "bar", value)
assert.Equal(t, "bar", c.PostForm("foo"))
value, ok = c.GetPostForm("array")
assert.True(t, ok)
assert.Equal(t, "first", value)
assert.Equal(t, "first", c.PostForm("array"))
assert.Equal(t, "10", c.DefaultPostForm("bar", "nothing"))
value, ok = c.GetPostForm("id")
assert.True(t, ok)
assert.Empty(t, value)
assert.Empty(t, c.PostForm("id"))
assert.Empty(t, c.DefaultPostForm("id", "nothing"))
value, ok = c.GetPostForm("nokey")
assert.False(t, ok)
assert.Empty(t, value)
assert.Equal(t, "nothing", c.DefaultPostForm("nokey", "nothing"))
values, ok := c.GetPostFormArray("array")
assert.True(t, ok)
assert.Equal(t, "first", values[0])
assert.Equal(t, "second", values[1])
values = c.PostFormArray("array")
assert.Equal(t, "first", values[0])
assert.Equal(t, "second", values[1])
values = c.PostFormArray("nokey")
assert.Empty(t, values)
values = c.PostFormArray("foo")
assert.Len(t, values, 1)
assert.Equal(t, "bar", values[0])
dicts, ok := c.GetPostFormMap("names")
assert.True(t, ok)
assert.Equal(t, "thinkerou", dicts["a"])
assert.Equal(t, "tianou", dicts["b"])
dicts, ok = c.GetPostFormMap("nokey")
assert.False(t, ok)
assert.Empty(t, dicts)
dicts = c.PostFormMap("names")
assert.Equal(t, "thinkerou", dicts["a"])
assert.Equal(t, "tianou", dicts["b"])
dicts = c.PostFormMap("nokey")
assert.Empty(t, dicts)
}
func TestContextSetCookie(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
c.SetSameSite(http.SameSiteLaxMode)
c.SetCookie("user", "gin", 1, "/", "localhost", true, true)
assert.Equal(t, "user=gin; Path=/; Domain=localhost; Max-Age=1; HttpOnly; Secure; SameSite=Lax", c.Writer.Header().Get("Set-Cookie"))
}
func TestContextSetCookiePathEmpty(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
c.SetSameSite(http.SameSiteLaxMode)
c.SetCookie("user", "gin", 1, "", "localhost", true, true)
assert.Equal(t, "user=gin; Path=/; Domain=localhost; Max-Age=1; HttpOnly; Secure; SameSite=Lax", c.Writer.Header().Get("Set-Cookie"))
}
func TestContextGetCookie(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
c.Request, _ = http.NewRequest(http.MethodGet, "/get", nil)
c.Request.Header.Set("Cookie", "user=gin")
cookie, _ := c.Cookie("user")
assert.Equal(t, "gin", cookie)
_, err := c.Cookie("nokey")
require.Error(t, err)
}
func TestContextBodyAllowedForStatus(t *testing.T) {
assert.False(t, false, bodyAllowedForStatus(http.StatusProcessing))
assert.False(t, false, bodyAllowedForStatus(http.StatusNoContent))
assert.False(t, false, bodyAllowedForStatus(http.StatusNotModified))
assert.True(t, true, bodyAllowedForStatus(http.StatusInternalServerError))
}
type TestRender struct{}
func (*TestRender) Render(http.ResponseWriter) error {
return errTestRender
}
func (*TestRender) WriteContentType(http.ResponseWriter) {}
func TestContextRenderIfErr(t *testing.T) {
w := httptest.NewRecorder()
c, _ := CreateTestContext(w)
c.Render(http.StatusOK, &TestRender{})
assert.Equal(t, errorMsgs{&Error{Err: errTestRender, Type: 1}}, c.Errors)
}
// Tests that the response is serialized as JSON
// and Content-Type is set to application/json
// and special HTML characters are escaped
func TestContextRenderJSON(t *testing.T) {
w := httptest.NewRecorder()
c, _ := CreateTestContext(w)
c.JSON(http.StatusCreated, H{"foo": "bar", "html": "<b>"})
assert.Equal(t, http.StatusCreated, w.Code)
assert.Equal(t, "{\"foo\":\"bar\",\"html\":\"\\u003cb\\u003e\"}", w.Body.String())
assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))
}
// Tests that the response is serialized as JSONP
// and Content-Type is set to application/javascript
func TestContextRenderJSONP(t *testing.T) {
w := httptest.NewRecorder()
c, _ := CreateTestContext(w)
c.Request, _ = http.NewRequest(http.MethodGet, "http://example.com/?callback=x", nil)
c.JSONP(http.StatusCreated, H{"foo": "bar"})
assert.Equal(t, http.StatusCreated, w.Code)
assert.Equal(t, "x({\"foo\":\"bar\"});", w.Body.String())
assert.Equal(t, "application/javascript; charset=utf-8", w.Header().Get("Content-Type"))
}
// Tests that the response is serialized as JSONP
// and Content-Type is set to application/json
func TestContextRenderJSONPWithoutCallback(t *testing.T) {
w := httptest.NewRecorder()
c, _ := CreateTestContext(w)
c.Request, _ = http.NewRequest(http.MethodGet, "http://example.com", nil)
c.JSONP(http.StatusCreated, H{"foo": "bar"})
assert.Equal(t, http.StatusCreated, w.Code)
assert.Equal(t, "{\"foo\":\"bar\"}", w.Body.String())
assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))
}
// Tests that no JSON is rendered if code is 204
func TestContextRenderNoContentJSON(t *testing.T) {
w := httptest.NewRecorder()
c, _ := CreateTestContext(w)
c.JSON(http.StatusNoContent, H{"foo": "bar"})
assert.Equal(t, http.StatusNoContent, w.Code)
assert.Empty(t, w.Body.String())
assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))
}
// Tests that the response is serialized as JSON
// we change the content-type before
func TestContextRenderAPIJSON(t *testing.T) {
w := httptest.NewRecorder()
c, _ := CreateTestContext(w)
c.Header("Content-Type", "application/vnd.api+json")
c.JSON(http.StatusCreated, H{"foo": "bar"})
assert.Equal(t, http.StatusCreated, w.Code)
assert.Equal(t, "{\"foo\":\"bar\"}", w.Body.String())
assert.Equal(t, "application/vnd.api+json", w.Header().Get("Content-Type"))
}
// Tests that no Custom JSON is rendered if code is 204
func TestContextRenderNoContentAPIJSON(t *testing.T) {
w := httptest.NewRecorder()
c, _ := CreateTestContext(w)
c.Header("Content-Type", "application/vnd.api+json")
c.JSON(http.StatusNoContent, H{"foo": "bar"})
assert.Equal(t, http.StatusNoContent, w.Code)
assert.Empty(t, w.Body.String())
assert.Equal(t, "application/vnd.api+json", w.Header().Get("Content-Type"))
}
// Tests that the response is serialized as JSON
// and Content-Type is set to application/json
func TestContextRenderIndentedJSON(t *testing.T) {
w := httptest.NewRecorder()
c, _ := CreateTestContext(w)
c.IndentedJSON(http.StatusCreated, H{"foo": "bar", "bar": "foo", "nested": H{"foo": "bar"}})
assert.Equal(t, http.StatusCreated, w.Code)