-
Notifications
You must be signed in to change notification settings - Fork 414
/
gorequest_test.go
2608 lines (2348 loc) · 83.5 KB
/
gorequest_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 gorequest
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"strconv"
"strings"
"sync"
"testing"
"time"
"mime/multipart"
"os"
"github.com/elazarl/goproxy"
)
type (
heyYou struct {
Hey string `json:"hey"`
}
testStruct struct {
String string
Int int
Btrue bool
Bfalse bool
Float float64
StringArray []string
IntArray []int
BoolArray []bool
FloatArray []float64
}
)
// Test for type constants.
func TestTypeConstants(t *testing.T) {
if TypeJSON != "json" {
t.Errorf("Expected TypeJSON -> json | but got %s", TypeJSON)
}
if TypeXML != "xml" {
t.Errorf("Expected TypeXML -> xml | but got %s", TypeXML)
}
if TypeForm != "form" {
t.Errorf("Expected TypeForm -> form | but got %s", TypeForm)
}
if TypeFormData != "form-data" {
t.Errorf("Expected TypeFormData -> form-data | but got %s", TypeFormData)
}
if TypeUrlencoded != "urlencoded" {
t.Errorf("Expected TypeUrlencoded -> urlencoded | but got %s", TypeUrlencoded)
}
if TypeHTML != "html" {
t.Errorf("Expected TypeHTML -> html | but got %s", TypeHTML)
}
if TypeText != "text" {
t.Errorf("Expected TypeText -> text | but got %s", TypeText)
}
if TypeMultipart != "multipart" {
t.Errorf("Expected TypeMultipart -> multipart | but got %s", TypeMultipart)
}
}
// Test for Types map.
func TestTypesMap(t *testing.T) {
if Types[TypeJSON] != "application/json" {
t.Errorf(`Expected Types["json"] -> "application/json" | but got %s`, Types[TypeJSON])
}
if Types[TypeXML] != "application/xml" {
t.Errorf(`Expected Types["xml"] -> "applicaion/xml" | but got %s`, Types[TypeXML])
}
if Types[TypeForm] != "application/x-www-form-urlencoded" {
t.Errorf(`Expected Types["form"] -> "application/x-www-form-urlencoded" | but got %s`, Types[TypeForm])
}
if Types[TypeFormData] != "application/x-www-form-urlencoded" {
t.Errorf(`Expected Types["form-data"] -> "application/x-www-form-urlencoded" | but got %s`, Types[TypeFormData])
}
if Types[TypeUrlencoded] != "application/x-www-form-urlencoded" {
t.Errorf(`Expected Types["urlencoded"] -> "application/x-www-form-urlencoded" | but got %s`, Types[TypeUrlencoded])
}
if Types[TypeHTML] != "text/html" {
t.Errorf(`Expected Types["html"] -> "text/html" | but got %s`, Types[TypeHTML])
}
if Types[TypeText] != "text/plain" {
t.Errorf(`Expected Types["text"] -> "text/plain" | but got %s`, Types[TypeText])
}
if Types[TypeMultipart] != "multipart/form-data" {
t.Errorf(`Expected Types["multipart"] -> "multipart/form-data" | but got %s`, Types[TypeMultipart])
}
}
// Test for changeMapToURLValues
func TestChangeMapToURLValues(t *testing.T) {
data := map[string]interface{}{
"s": "a string",
"i": 42,
"bt": true,
"bf": false,
"f": 12.345,
"sa": []string{"s1", "s2"},
"ia": []int{47, 73},
"fa": []float64{1.23, 4.56},
"ba": []bool{true, false},
}
urlValues := changeMapToURLValues(data)
var (
s string
sd string
)
if s := urlValues.Get("s"); s != data["s"] {
t.Errorf("Expected string %v, got %v", data["s"], s)
}
s = urlValues.Get("i")
sd = strconv.Itoa(data["i"].(int))
if s != sd {
t.Errorf("Expected int %v, got %v", sd, s)
}
s = urlValues.Get("bt")
sd = strconv.FormatBool(data["bt"].(bool))
if s != sd {
t.Errorf("Expected boolean %v, got %v", sd, s)
}
s = urlValues.Get("bf")
sd = strconv.FormatBool(data["bf"].(bool))
if s != sd {
t.Errorf("Expected boolean %v, got %v", sd, s)
}
s = urlValues.Get("f")
sd = strconv.FormatFloat(data["f"].(float64), 'f', -1, 64)
if s != sd {
t.Errorf("Expected float %v, got %v", data["f"], s)
}
// array cases
// "To access multiple values, use the map directly."
if size := len(urlValues["sa"]); size != 2 {
t.Fatalf("Expected length %v, got %v", 2, size)
}
if urlValues["sa"][0] != "s1" {
t.Errorf("Expected string %v, got %v", "s1", urlValues["sa"][0])
}
if urlValues["sa"][1] != "s2" {
t.Errorf("Expected string %v, got %v", "s2", urlValues["sa"][1])
}
if size := len(urlValues["ia"]); size != 2 {
t.Fatalf("Expected length %v, got %v", 2, size)
}
if urlValues["ia"][0] != "47" {
t.Errorf("Expected string %v, got %v", "47", urlValues["ia"][0])
}
if urlValues["ia"][1] != "73" {
t.Errorf("Expected string %v, got %v", "73", urlValues["ia"][1])
}
if size := len(urlValues["ba"]); size != 2 {
t.Fatalf("Expected length %v, got %v", 2, size)
}
if urlValues["ba"][0] != "true" {
t.Errorf("Expected string %v, got %v", "true", urlValues["ba"][0])
}
if urlValues["ba"][1] != "false" {
t.Errorf("Expected string %v, got %v", "false", urlValues["ba"][1])
}
if size := len(urlValues["fa"]); size != 2 {
t.Fatalf("Expected length %v, got %v", 2, size)
}
if urlValues["fa"][0] != "1.23" {
t.Errorf("Expected string %v, got %v", "true", urlValues["fa"][0])
}
if urlValues["fa"][1] != "4.56" {
t.Errorf("Expected string %v, got %v", "false", urlValues["fa"][1])
}
}
// Test for Make request
func TestMakeRequest(t *testing.T) {
var err error
var cases = []struct {
m string
s *SuperAgent
}{
{POST, New().Post("/")},
{GET, New().Get("/")},
{HEAD, New().Head("/")},
{PUT, New().Put("/")},
{PATCH, New().Patch("/")},
{DELETE, New().Delete("/")},
{OPTIONS, New().Options("/")},
{"TRACE", New().CustomMethod("TRACE", "/")}, // valid HTTP 1.1 method, see W3C RFC 2616
}
for _, c := range cases {
_, err = c.s.MakeRequest()
if err != nil {
t.Errorf("Expected nil error for method %q; got %q", c.m, err.Error())
}
}
// empty method should fail
_, err = New().CustomMethod("", "/").MakeRequest()
if err == nil {
t.Errorf("Expected non-nil error for empty method; got %q", err.Error())
}
}
// testing for Get method
func TestGet(t *testing.T) {
const case1_empty = "/"
const case2_set_header = "/set_header"
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// check method is GET before going to check other features
if r.Method != GET {
t.Errorf("Expected method %q; got %q", GET, r.Method)
}
if r.Header == nil {
t.Error("Expected non-nil request Header")
}
switch r.URL.Path {
default:
t.Errorf("No testing for this case yet : %q", r.URL.Path)
case case1_empty:
t.Logf("case %v ", case1_empty)
case case2_set_header:
t.Logf("case %v ", case2_set_header)
if r.Header.Get("API-Key") != "fookey" {
t.Errorf("Expected 'API-Key' == %q; got %q", "fookey", r.Header.Get("API-Key"))
}
}
}))
defer ts.Close()
New().Get(ts.URL + case1_empty).
End()
New().Get(ts.URL+case2_set_header).
Set("API-Key", "fookey").
End()
}
// testing for Get method.. but clone our base.
func TestGetWithClone(t *testing.T) {
const case1_empty = "/"
const case2_set_header = "/set_header"
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// check method is GET before going to check other features
if r.Method != GET {
t.Errorf("Expected method %q; got %q", GET, r.Method)
}
if r.Header == nil {
t.Error("Expected non-nil request Header")
}
switch r.URL.Path {
default:
t.Errorf("No testing for this case yet : %q", r.URL.Path)
case case1_empty:
t.Logf("case %v ", case1_empty)
case case2_set_header:
t.Logf("case %v ", case2_set_header)
if r.Header.Get("API-Key") != "fookey" {
t.Errorf("Expected 'API-Key' == %q; got %q", "fookey", r.Header.Get("API-Key"))
}
}
}))
defer ts.Close()
reqBase := New()
reqBase.Clone().Get(ts.URL + case1_empty).
End()
reqBase.Clone().Get(ts.URL+case2_set_header).
Set("API-Key", "fookey").
End()
}
// testing for Get method.. but clone our base.
func TestGetWithCloneRequestAfterMake(t *testing.T) {
const case1_empty = "/"
const case2_set_header = "/set_header"
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// check method is GET before going to check other features
if r.Method != GET {
t.Errorf("Expected method %q; got %q", GET, r.Method)
}
if r.Header == nil {
t.Error("Expected non-nil request Header")
}
switch r.URL.Path {
default:
t.Errorf("No testing for this case yet : %q", r.URL.Path)
case case1_empty:
t.Logf("case %v ", case1_empty)
case case2_set_header:
t.Logf("case %v ", case2_set_header)
if r.Header.Get("API-Key") != "fookey" {
t.Errorf("Expected 'API-Key' == %q; got %q", "fookey", r.Header.Get("API-Key"))
}
}
}))
defer ts.Close()
reqBase := New()
// define the two request
req1 := reqBase.Clone().Get(ts.URL + case1_empty)
req2 := reqBase.Clone().Get(ts.URL+case2_set_header).
Set("API-Key", "fookey")
// now they have different bases, so make the requests
req1.End()
req2.End()
}
// testing for Get method.. but clone our base.
func TestGetWithCloneWithHeadersAndQuery(t *testing.T) {
const case1_empty = "/"
const case2_set_header = "/set_header"
const case3_set_query = "/set_query"
const case4_set_both = "/set_both"
const case5_empty = "/empty"
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// check method is GET before going to check other features
if r.Method != GET {
t.Errorf("Expected method %q; got %q", GET, r.Method)
}
if r.Header == nil {
t.Error("Expected non-nil request Header")
}
t.Logf("header %v", r.Header)
if r.Header.Get("base") != "header" {
t.Errorf("Expected base header: %s", r.Header.Get("base"))
}
if r.URL.Query().Get("queryBase") != "yep" {
t.Errorf("Expected queryBase queryParam: %s", r.URL.Query().Get("queryBase"))
}
switch r.URL.Path {
default:
t.Errorf("No testing for this case yet : %q", r.URL.Path)
case case1_empty, case5_empty:
t.Logf("case %v ", case1_empty)
if r.Header.Get("API-Key") != "base" {
t.Errorf("Expected 'API-Key' == %q; got %q", "base", r.Header.Get("API-Key"))
}
if r.URL.Query().Get("newQuery") != "" {
t.Errorf("Expected 'newQuery' == %q; got %q", "", r.URL.Query().Get("newQuery"))
}
if r.Header.Get("FOURTH") != "" {
t.Errorf("Expected 'FOURTH' == %q; got %q", "", r.Header.Get("FOURTH"))
}
case case2_set_header:
t.Logf("case %v ", case2_set_header)
if r.Header.Get("API-Key") != "fookey" {
t.Errorf("Expected 'API-Key' == %q; got %q", "fookey", r.Header.Get("API-Key"))
}
case case3_set_query:
t.Logf("case %v ", case3_set_query)
if r.URL.Query().Get("newQuery") != "newVal" {
t.Errorf("Expected 'newQuery' == %q; got %q", "newVal", r.URL.Query().Get("newQuery"))
}
case case4_set_both:
t.Logf("case %v ", case3_set_query)
if r.URL.Query().Get("fourth") != "4val" {
t.Errorf("Expected 'fourth' == %q; got %q", "4val", r.URL.Query().Get("fourth"))
}
if r.Header.Get("FOURTH") != "fourkey" {
t.Errorf("Expected 'FOURTH' == %q; got %q", "fourkey", r.Header.Get("FOURTH"))
}
}
}))
defer ts.Close()
reqBase := New().
Set("base", "header").
Set("API-KEY", "base").
Param("queryBase", "yep")
// define the two request
req1 := reqBase.Clone().Get(ts.URL + case1_empty)
req2 := reqBase.Clone().Get(ts.URL+case2_set_header).
Set("API-Key", "fookey")
req3 := reqBase.Clone().Get(ts.URL+case3_set_query).
Param("newQuery", "newVal")
req4 := reqBase.Clone().Get(ts.URL+case4_set_both).
Param("fourth", "4val").
Set("FOURTH", "fourkey")
req5 := reqBase.Clone().Get(ts.URL + case5_empty)
// now they have different bases, so make the requests
req1.End()
req2.End()
req3.End()
req4.End()
req5.End()
}
// testing for Get method.. but clone our base.
func TestConcurrently(t *testing.T) {
const case1_empty = "/"
const case2_set_header = "/set_header"
const case3_set_query = "/set_query"
const case4_set_both = "/set_both"
const case5_post = "/post"
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// check method is GET before going to check other features
if r.Method != GET && r.URL.Path != case5_post {
t.Errorf("Expected method %q; got %q", GET, r.Method)
} else if r.Method != POST && r.URL.Path == case5_post {
t.Errorf("Expected method %q; got %q", POST, r.Method)
}
if r.Header == nil {
t.Error("Expected non-nil request Header")
}
t.Logf("header %v", r.Header)
if r.Header.Get("base") != "header" {
t.Errorf("Expected base header: %s", r.Header.Get("base"))
}
if r.URL.Query().Get("queryBase") != "yep" {
t.Errorf("Expected queryBase queryParam: %s", r.URL.Query().Get("queryBase"))
}
switch r.URL.Path {
default:
t.Errorf("No testing for this case yet : %q", r.URL.Path)
case case1_empty:
t.Logf("case %v ", case1_empty)
if r.Header.Get("API-Key") != "base" {
t.Errorf("Expected 'API-Key' == %q; got %q", "base", r.Header.Get("API-Key"))
}
if r.URL.Query().Get("newQuery") != "" {
t.Errorf("Expected 'newQuery' == %q; got %q", "", r.URL.Query().Get("newQuery"))
}
if r.Header.Get("FOURTH") != "" {
t.Errorf("Expected 'FOURTH' == %q; got %q", "", r.Header.Get("FOURTH"))
}
case case2_set_header:
t.Logf("case %v ", case2_set_header)
if r.Header.Get("API-Key") != "fookey" {
t.Errorf("Expected 'API-Key' == %q; got %q", "fookey", r.Header.Get("API-Key"))
}
case case3_set_query:
t.Logf("case %v ", case3_set_query)
if r.URL.Query().Get("newQuery") != "newVal" {
t.Errorf("Expected 'newQuery' == %q; got %q", "newVal", r.URL.Query().Get("newQuery"))
}
case case4_set_both:
t.Logf("case %v ", case3_set_query)
if r.URL.Query().Get("fourth") != "4val" {
t.Errorf("Expected 'fourth' == %q; got %q", "4val", r.URL.Query().Get("fourth"))
}
if r.Header.Get("FOURTH") != "fourkey" {
t.Errorf("Expected 'FOURTH' == %q; got %q", "fourkey", r.Header.Get("FOURTH"))
}
case case5_post:
t.Logf("case %v ", case5_post)
if r.URL.Query().Get("iteration") == "" {
t.Errorf("Expected 'fourth' != %q; got %q", "", r.URL.Query().Get("iteration"))
}
r.ParseForm()
if r.Form.Get("form_iteration") == "" {
t.Errorf("Expected 'form_iteration' != %q; got %q", "", r.Form.Get("form_iteration"))
}
if r.Form.Get("form_iteration") != r.URL.Query().Get("iteration") {
t.Errorf("Expected 'form_iteration' == %q; got %q", r.URL.Query().Get("iteration"), r.Form.Get("form_iteration"))
}
}
}))
defer ts.Close()
reqBase := New().
Set("base", "header").
Set("API-KEY", "base").
Param("queryBase", "yep")
var waitForCompletion sync.WaitGroup
// define the two request
for i := 0; i < 1000; i++ {
waitForCompletion.Add(5)
go func() {
reqBase.Clone().Get(ts.URL + case1_empty).End()
waitForCompletion.Done()
}()
go func() {
reqBase.Clone().Get(ts.URL+case2_set_header).
Set("API-Key", "fookey").
End()
waitForCompletion.Done()
}()
go func() {
reqBase.Clone().Get(ts.URL+case3_set_query).
Param("newQuery", "newVal").
End()
waitForCompletion.Done()
}()
go func() {
reqBase.Clone().Get(ts.URL+case4_set_both).
Param("fourth", "4val").
Set("FOURTH", "fourkey").
End()
waitForCompletion.Done()
}()
go func(iter int) {
iterStr := fmt.Sprintf("%d", iter)
reqBase.Clone().Post(ts.URL+case5_post).
Param("iteration", iterStr).
Type("form").
Send(fmt.Sprintf(`{"form_iteration": "%s"}`, iterStr)).
End()
waitForCompletion.Done()
}(i)
}
waitForCompletion.Wait()
}
// testing for Get method with retry option
func TestRetryGet(t *testing.T) {
const (
case1_empty = "/"
case24_after_3_attempt_return_valid = "/retry_3_attempt_then_valid"
retry_count_expected = "3"
)
var attempt int
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// check method is GET before going to check other features
if r.Method != GET {
t.Errorf("Expected method %q; got %q", GET, r.Method)
}
//set return status
if r.Header == nil {
t.Error("Expected non-nil request Header")
}
switch r.URL.Path {
default:
t.Errorf("No testing for this case yet : %q", r.URL.Path)
case case1_empty:
w.WriteHeader(400)
t.Logf("case %v ", case1_empty)
case case24_after_3_attempt_return_valid:
if attempt == 3 {
w.WriteHeader(200)
} else {
w.WriteHeader(400)
t.Logf("case %v ", case24_after_3_attempt_return_valid)
}
attempt++
}
}))
defer ts.Close()
resp, _, errs := New().Get(ts.URL+case1_empty).
Retry(3, 1*time.Nanosecond, http.StatusBadRequest).
End()
if errs != nil {
t.Errorf("No testing for this case yet : %q", errs)
}
retryCountReturn := resp.Header.Get("Retry-Count")
if retryCountReturn != retry_count_expected {
t.Errorf("Expected [%s] retry but was [%s]", retry_count_expected, retryCountReturn)
}
resp, _, errs = New().Get(ts.URL+case24_after_3_attempt_return_valid).
Retry(4, 1*time.Nanosecond, http.StatusBadRequest).
End()
if errs != nil {
t.Errorf("No testing for this case yet : %q", errs)
}
retryCountReturn = resp.Header.Get("Retry-Count")
if retryCountReturn != retry_count_expected {
t.Errorf("Expected [%s] retry but was [%s]", retry_count_expected, retryCountReturn)
}
}
// testing for Options method
func TestOptions(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// check method is OPTIONS before going to check other features
if r.Method != OPTIONS {
t.Errorf("Expected method %q; got %q", OPTIONS, r.Method)
}
t.Log("test Options")
w.Header().Set("Allow", "HEAD, GET")
w.WriteHeader(204)
}))
defer ts.Close()
New().Options(ts.URL).
End()
}
// testing that resp.Body is reusable
func TestResetBody(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Just some text"))
}))
defer ts.Close()
resp, _, _ := New().Get(ts.URL).End()
bodyBytes, _ := ioutil.ReadAll(resp.Body)
if string(bodyBytes) != "Just some text" {
t.Error("Expected to be able to reuse the response body")
}
}
// testing for Param method
func TestParam(t *testing.T) {
paramCode := "123456"
paramFields := "f1;f2;f3"
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Form.Get("code") != paramCode {
t.Errorf("Expected 'code' == %s; got %v", paramCode, r.Form.Get("code"))
}
if r.Form.Get("fields") != paramFields {
t.Errorf("Expected 'fields' == %s; got %v", paramFields, r.Form.Get("fields"))
}
}))
defer ts.Close()
New().Get(ts.URL).
Param("code", paramCode).
Param("fields", paramFields)
}
const (
test_post_case1_empty = "/"
test_post_case2_set_header = "/set_header"
test_post_case3_send_json = "/send_json"
test_post_case4_send_string = "/send_string"
test_post_case5_integration_send_json_string = "/integration_send_json_string"
test_post_case6_set_query = "/set_query"
test_post_case7_integration_send_json_struct = "/integration_send_json_struct"
// Check that the number conversion should be converted as string not float64
test_post_case8_send_json_with_long_id_number = "/send_json_with_long_id_number"
test_post_case9_send_json_string_with_long_id_number_as_form_result = "/send_json_string_with_long_id_number_as_form_result"
test_post_case10_send_struct_pointer = "/send_struct_pointer"
test_post_case11_send_string_pointer = "/send_string_pointer"
test_post_case12_send_slice_string = "/send_slice_string"
test_post_case13_send_slice_string_pointer = "/send_slice_string_pointer"
test_post_case14_send_int_pointer = "/send_int_pointer"
test_post_case15_send_float_pointer = "/send_float_pointer"
test_post_case16_send_bool_pointer = "/send_bool_pointer"
test_post_case17_send_string_array = "/send_string_array"
test_post_case18_send_string_array_pointer = "/send_string_array_pointer"
test_post_case19_send_struct = "/send_struct"
test_post_case20_send_byte_char = "/send_byte_char"
test_post_case21_send_byte_char_pointer = "/send_byte_char_pointer"
test_post_case22_send_byte_int = "/send_byte_int"
test_post_case22_send_byte_int_pointer = "/send_byte_int_pointer"
test_post_case23_send_duplicate_query_params = "/send_duplicate_query_params"
test_post_case24_send_query_and_request_body = "/send_query_and_request_body"
)
// testing for POST method
func testPostServer(t *testing.T) *httptest.Server {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// check method is POST before going to check other features
if r.Method != POST {
t.Errorf("Expected method %q; got %q", POST, r.Method)
}
if r.Header == nil {
t.Error("Expected non-nil request Header")
}
switch r.URL.Path {
default:
t.Errorf("No testing for this case yet : %q", r.URL.Path)
case test_post_case1_empty:
t.Logf("case %v ", test_post_case1_empty)
case test_post_case2_set_header:
t.Logf("case %v ", test_post_case2_set_header)
if r.Header.Get("API-Key") != "fookey" {
t.Errorf("Expected 'API-Key' == %q; got %q", "fookey", r.Header.Get("API-Key"))
}
case test_post_case3_send_json:
t.Logf("case %v ", test_post_case3_send_json)
defer r.Body.Close()
body, _ := ioutil.ReadAll(r.Body)
if string(body) != `{"query1":"test","query2":"test"}` {
t.Error(`Expected Body with {"query1":"test","query2":"test"}`, "| but got", string(body))
}
case test_post_case4_send_string, test_post_case11_send_string_pointer:
t.Logf("case %v ", r.URL.Path)
if r.Header.Get("Content-Type") != "application/x-www-form-urlencoded" {
t.Error("Expected Header Content-Type -> application/x-www-form-urlencoded", "| but got", r.Header.Get("Content-Type"))
}
defer r.Body.Close()
body, _ := ioutil.ReadAll(r.Body)
if string(body) != "query1=test&query2=test" {
t.Error("Expected Body with \"query1=test&query2=test\"", "| but got", string(body))
}
case test_post_case5_integration_send_json_string:
t.Logf("case %v ", test_post_case5_integration_send_json_string)
defer r.Body.Close()
body, _ := ioutil.ReadAll(r.Body)
if string(body) != "query1=test&query2=test" {
t.Error("Expected Body with \"query1=test&query2=test\"", "| but got", string(body))
}
case test_post_case6_set_query:
t.Logf("case %v ", test_post_case6_set_query)
v := r.URL.Query()
if v["query1"][0] != "test" {
t.Error("Expected query1:test", "| but got", v["query1"][0])
}
if v["query2"][0] != "test" {
t.Error("Expected query2:test", "| but got", v["query2"][0])
}
case test_post_case7_integration_send_json_struct:
t.Logf("case %v ", test_post_case7_integration_send_json_struct)
defer r.Body.Close()
body, _ := ioutil.ReadAll(r.Body)
comparedBody := []byte(`{"Lower":{"Color":"green","Size":1.7},"Upper":{"Color":"red","Size":0},"a":"a","name":"Cindy"}`)
if !bytes.Equal(body, comparedBody) {
t.Errorf(`Expected correct json but got ` + string(body))
}
case test_post_case8_send_json_with_long_id_number:
t.Logf("case %v ", test_post_case8_send_json_with_long_id_number)
defer r.Body.Close()
body, _ := ioutil.ReadAll(r.Body)
if string(body) != `{"id":123456789,"name":"nemo"}` {
t.Error(`Expected Body with {"id":123456789,"name":"nemo"}`, "| but got", string(body))
}
case test_post_case9_send_json_string_with_long_id_number_as_form_result:
t.Logf("case %v ", test_post_case9_send_json_string_with_long_id_number_as_form_result)
defer r.Body.Close()
body, _ := ioutil.ReadAll(r.Body)
if string(body) != `id=123456789&name=nemo` {
t.Error(`Expected Body with "id=123456789&name=nemo"`, `| but got`, string(body))
}
case test_post_case19_send_struct, test_post_case10_send_struct_pointer:
t.Logf("case %v ", r.URL.Path)
defer r.Body.Close()
body, _ := ioutil.ReadAll(r.Body)
comparedBody := []byte(`{"Bfalse":false,"BoolArray":[true,false],"Btrue":true,"Float":12.345,"FloatArray":[1.23,4.56,7.89],"Int":42,"IntArray":[1,2],"String":"a string","StringArray":["string1","string2"]}`)
if !bytes.Equal(body, comparedBody) {
t.Errorf(`Expected correct json but got ` + string(body))
}
case test_post_case12_send_slice_string, test_post_case13_send_slice_string_pointer, test_post_case17_send_string_array, test_post_case18_send_string_array_pointer:
t.Logf("case %v ", r.URL.Path)
defer r.Body.Close()
body, _ := ioutil.ReadAll(r.Body)
comparedBody := []byte(`["string1","string2"]`)
if !bytes.Equal(body, comparedBody) {
t.Errorf(`Expected correct json but got ` + string(body))
}
case test_post_case14_send_int_pointer:
t.Logf("case %v ", test_post_case14_send_int_pointer)
defer r.Body.Close()
body, _ := ioutil.ReadAll(r.Body)
if string(body) != "42" {
t.Error("Expected Body with \"42\"", "| but got", string(body))
}
case test_post_case15_send_float_pointer:
t.Logf("case %v ", test_post_case15_send_float_pointer)
defer r.Body.Close()
body, _ := ioutil.ReadAll(r.Body)
if string(body) != "12.345" {
t.Error("Expected Body with \"12.345\"", "| but got", string(body))
}
case test_post_case16_send_bool_pointer:
t.Logf("case %v ", test_post_case16_send_bool_pointer)
defer r.Body.Close()
body, _ := ioutil.ReadAll(r.Body)
if string(body) != "true" {
t.Error("Expected Body with \"true\"", "| but got", string(body))
}
case test_post_case20_send_byte_char, test_post_case21_send_byte_char_pointer, test_post_case22_send_byte_int, test_post_case22_send_byte_int_pointer:
t.Logf("case %v ", r.URL.Path)
defer r.Body.Close()
body, _ := ioutil.ReadAll(r.Body)
if string(body) != "71" {
t.Error("Expected Body with \"71\"", "| but got", string(body))
}
case test_post_case23_send_duplicate_query_params:
t.Logf("case %v ", test_post_case23_send_duplicate_query_params)
defer r.Body.Close()
body, _ := ioutil.ReadAll(r.Body)
sbody := string(body)
if sbody != "param=4¶m=3¶m=2¶m=1" {
t.Error("Expected Body \"param=4¶m=3¶m=2¶m=1\"", "| but got", sbody)
}
values, _ := url.ParseQuery(sbody)
if len(values["param"]) != 4 {
t.Error("Expected Body with 4 params", "| but got", sbody)
}
if values["param"][0] != "4" || values["param"][1] != "3" || values["param"][2] != "2" || values["param"][3] != "1" {
t.Error("Expected Body with 4 params and values", "| but got", sbody)
}
case test_post_case24_send_query_and_request_body:
t.Logf("case %v ", test_post_case24_send_query_and_request_body)
defer r.Body.Close()
body, _ := ioutil.ReadAll(r.Body)
sbody := string(body)
if sbody != `{"name":"jkbbwr"}` {
t.Error(`Expected Body "{"name":"jkbbwr"}"`, "| but got", sbody)
}
v := r.URL.Query()
if v["test"][0] != "true" {
t.Error("Expected test:true", "| but got", v["test"][0])
}
}
}))
return ts
}
func TestPost(t *testing.T) {
ts := testPostServer(t)
defer ts.Close()
New().Post(ts.URL + test_post_case1_empty).
End()
New().Post(ts.URL+test_post_case2_set_header).
Set("API-Key", "fookey").
End()
New().Post(ts.URL + test_post_case3_send_json).
Send(`{"query1":"test"}`).
Send(`{"query2":"test"}`).
End()
New().Post(ts.URL + test_post_case4_send_string).
Send("query1=test").
Send("query2=test").
End()
New().Post(ts.URL + test_post_case5_integration_send_json_string).
Send("query1=test").
Send(`{"query2":"test"}`).
End()
/* TODO: More testing post for application/x-www-form-urlencoded
post.query(json), post.query(string), post.send(json), post.send(string), post.query(both).send(both)
*/
New().Post(ts.URL + test_post_case6_set_query).
Query("query1=test").
Query("query2=test").
End()
// TODO:
// 1. test 2nd layer nested struct
// 2. test lowercase won't be export to json
// 3. test field tag change to json field name
type Upper struct {
Color string
Size int
note string
}
type Lower struct {
Color string
Size float64
note string
}
type Style struct {
Upper Upper
Lower Lower
Name string `json:"name"`
}
myStyle := Style{Upper: Upper{Color: "red"}, Name: "Cindy", Lower: Lower{Color: "green", Size: 1.7}}
New().Post(ts.URL + test_post_case7_integration_send_json_struct).
Send(`{"a":"a"}`).
Send(myStyle).
End()
New().Post(ts.URL + test_post_case8_send_json_with_long_id_number).
Send(`{"id":123456789, "name":"nemo"}`).
End()
New().Post(ts.URL + test_post_case9_send_json_string_with_long_id_number_as_form_result).
Type("form").
Send(`{"id":123456789, "name":"nemo"}`).
End()
payload := testStruct{
String: "a string",
Int: 42,
Btrue: true,
Bfalse: false,
Float: 12.345,
StringArray: []string{"string1", "string2"},
IntArray: []int{1, 2},
BoolArray: []bool{true, false},
FloatArray: []float64{1.23, 4.56, 7.89},
}
New().Post(ts.URL + test_post_case10_send_struct_pointer).
Send(&payload).
End()
New().Post(ts.URL + test_post_case19_send_struct).
Send(payload).
End()
s1 := "query1=test"
s2 := "query2=test"
New().Post(ts.URL + test_post_case11_send_string_pointer).
Send(&s1).
Send(&s2).
End()
New().Post(ts.URL + test_post_case12_send_slice_string).
Send([]string{"string1", "string2"}).
End()
New().Post(ts.URL + test_post_case13_send_slice_string_pointer).
Send(&[]string{"string1", "string2"}).
End()
i := 42
New().Post(ts.URL + test_post_case14_send_int_pointer).
Send(&i).
End()
f := 12.345
New().Post(ts.URL + test_post_case15_send_float_pointer).
Send(&f).
End()
b := true
New().Post(ts.URL + test_post_case16_send_bool_pointer).
Send(&b).
End()
var a [2]string
a[0] = "string1"
a[1] = "string2"
New().Post(ts.URL + test_post_case17_send_string_array).
Send(a).
End()
New().Post(ts.URL + test_post_case18_send_string_array_pointer).
Send(&a).
End()
aByte := byte('G') // = 71 dec
New().Post(ts.URL + test_post_case20_send_byte_char).
Send(aByte).
End()
New().Post(ts.URL + test_post_case21_send_byte_char_pointer).
Send(&aByte).
End()
iByte := byte(71) // = 'G'
New().Post(ts.URL + test_post_case22_send_byte_int).
Send(iByte).
End()
New().Post(ts.URL + test_post_case22_send_byte_int_pointer).
Send(&iByte).
End()
New().Post(ts.URL + test_post_case23_send_duplicate_query_params).
Send("param=1").
Send("param=2").
Send("param=3¶m=4").
End()
data24 := struct {