-
-
Notifications
You must be signed in to change notification settings - Fork 120
/
sling_test.go
1012 lines (925 loc) · 34 KB
/
sling_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 sling
import (
"bytes"
"context"
"encoding/xml"
"errors"
"fmt"
"io"
"math"
"net"
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"strings"
"sync/atomic"
"testing"
)
type FakeParams struct {
KindName string `url:"kind_name"`
Count int `url:"count"`
}
// Url-tagged query struct
var paramsA = struct {
Limit int `url:"limit"`
}{
30,
}
var paramsB = FakeParams{KindName: "recent", Count: 25}
// Json/XML-tagged model struct
type FakeModel struct {
Text string `json:"text,omitempty" xml:"text"`
FavoriteCount int64 `json:"favorite_count,omitempty" xml:"favorite_count"`
Temperature float64 `json:"temperature,omitempty" xml:"temperature"`
}
var modelA = FakeModel{Text: "note", FavoriteCount: 12}
// Non-Json response decoder
type xmlResponseDecoder struct{}
func (d xmlResponseDecoder) Decode(resp *http.Response, v interface{}) error {
return xml.NewDecoder(resp.Body).Decode(v)
}
func TestNew(t *testing.T) {
sling := New()
if sling.httpClient != http.DefaultClient {
t.Errorf("expected %v, got %v", http.DefaultClient, sling.httpClient)
}
if sling.header == nil {
t.Errorf("Header map not initialized with make")
}
if sling.queryStructs == nil {
t.Errorf("queryStructs not initialized with make")
}
}
func TestSlingNew(t *testing.T) {
fakeBodyProvider := jsonBodyProvider{FakeModel{}}
cases := []*Sling{
&Sling{httpClient: &http.Client{}, method: "GET", rawURL: "http://example.com"},
&Sling{httpClient: nil, method: "", rawURL: "http://example.com"},
&Sling{queryStructs: make([]interface{}, 0)},
&Sling{queryStructs: []interface{}{paramsA}},
&Sling{queryStructs: []interface{}{paramsA, paramsB}},
&Sling{bodyProvider: fakeBodyProvider},
&Sling{bodyProvider: fakeBodyProvider},
&Sling{bodyProvider: nil},
New().Add("Content-Type", "application/json"),
New().Add("A", "B").Add("a", "c").New(),
New().Add("A", "B").New().Add("a", "c"),
New().BodyForm(paramsB),
New().BodyForm(paramsB).New(),
}
for _, sling := range cases {
child := sling.New()
if child.httpClient != sling.httpClient {
t.Errorf("expected %v, got %v", sling.httpClient, child.httpClient)
}
if child.method != sling.method {
t.Errorf("expected %s, got %s", sling.method, child.method)
}
if child.rawURL != sling.rawURL {
t.Errorf("expected %s, got %s", sling.rawURL, child.rawURL)
}
// Header should be a copy of parent Sling header. For example, calling
// baseSling.Add("k","v") should not mutate previously created child Slings
if sling.header != nil {
// struct literal cases don't init Header in usual way, skip header check
if !reflect.DeepEqual(sling.header, child.header) {
t.Errorf("not DeepEqual: expected %v, got %v", sling.header, child.header)
}
sling.header.Add("K", "V")
if child.header.Get("K") != "" {
t.Errorf("child.header was a reference to original map, should be copy")
}
}
// queryStruct slice should be a new slice with a copy of the contents
if len(sling.queryStructs) > 0 {
// mutating one slice should not mutate the other
child.queryStructs[0] = nil
if sling.queryStructs[0] == nil {
t.Errorf("child.queryStructs was a re-slice, expected slice with copied contents")
}
}
// body should be copied
if child.bodyProvider != sling.bodyProvider {
t.Errorf("expected %v, got %v", sling.bodyProvider, child.bodyProvider)
}
}
}
func TestClientSetter(t *testing.T) {
developerClient := &http.Client{}
cases := []struct {
input *http.Client
expected *http.Client
}{
{nil, http.DefaultClient},
{developerClient, developerClient},
}
for _, c := range cases {
sling := New()
sling.Client(c.input)
if sling.httpClient != c.expected {
t.Errorf("input %v, expected %v, got %v", c.input, c.expected, sling.httpClient)
}
}
}
func TestDoerSetter(t *testing.T) {
developerClient := &http.Client{}
cases := []struct {
input Doer
expected Doer
}{
{nil, http.DefaultClient},
{developerClient, developerClient},
}
for _, c := range cases {
sling := New()
sling.Doer(c.input)
if sling.httpClient != c.expected {
t.Errorf("input %v, expected %v, got %v", c.input, c.expected, sling.httpClient)
}
}
}
func TestBaseSetter(t *testing.T) {
cases := []string{"http://a.io/", "http://b.io", "/path", "path", ""}
for _, base := range cases {
sling := New().Base(base)
if sling.rawURL != base {
t.Errorf("expected %s, got %s", base, sling.rawURL)
}
}
}
func TestPathSetter(t *testing.T) {
cases := []struct {
rawURL string
path string
expectedRawURL string
}{
{"http://a.io/", "foo", "http://a.io/foo"},
{"http://a.io/", "/foo", "http://a.io/foo"},
{"http://a.io", "foo", "http://a.io/foo"},
{"http://a.io", "/foo", "http://a.io/foo"},
{"http://a.io/foo/", "bar", "http://a.io/foo/bar"},
// rawURL should end in trailing slash if it is to be Path extended
{"http://a.io/foo", "bar", "http://a.io/bar"},
{"http://a.io/foo", "/bar", "http://a.io/bar"},
// path extension is absolute
{"http://a.io", "http://b.io/", "http://b.io/"},
{"http://a.io/", "http://b.io/", "http://b.io/"},
{"http://a.io", "http://b.io", "http://b.io"},
{"http://a.io/", "http://b.io", "http://b.io"},
// empty base, empty path
{"", "http://b.io", "http://b.io"},
{"http://a.io", "", "http://a.io"},
{"", "", ""},
}
for _, c := range cases {
sling := New().Base(c.rawURL).Path(c.path)
if sling.rawURL != c.expectedRawURL {
t.Errorf("expected %s, got %s", c.expectedRawURL, sling.rawURL)
}
}
}
func TestMethodSetters(t *testing.T) {
cases := []struct {
sling *Sling
expectedMethod string
}{
{New().Path("http://a.io"), "GET"},
{New().Head("http://a.io"), "HEAD"},
{New().Get("http://a.io"), "GET"},
{New().Post("http://a.io"), "POST"},
{New().Put("http://a.io"), "PUT"},
{New().Patch("http://a.io"), "PATCH"},
{New().Delete("http://a.io"), "DELETE"},
{New().Options("http://a.io"), "OPTIONS"},
{New().Trace("http://a.io"), "TRACE"},
{New().Connect("http://a.io"), "CONNECT"},
}
for _, c := range cases {
if c.sling.method != c.expectedMethod {
t.Errorf("expected method %s, got %s", c.expectedMethod, c.sling.method)
}
}
}
func TestAddHeader(t *testing.T) {
cases := []struct {
sling *Sling
expectedHeader map[string][]string
}{
{New().Add("authorization", "OAuth key=\"value\""), map[string][]string{"Authorization": []string{"OAuth key=\"value\""}}},
// header keys should be canonicalized
{New().Add("content-tYPE", "application/json").Add("User-AGENT", "sling"), map[string][]string{"Content-Type": []string{"application/json"}, "User-Agent": []string{"sling"}}},
// values for existing keys should be appended
{New().Add("A", "B").Add("a", "c"), map[string][]string{"A": []string{"B", "c"}}},
// Add should add to values for keys added by parent Slings
{New().Add("A", "B").Add("a", "c").New(), map[string][]string{"A": []string{"B", "c"}}},
{New().Add("A", "B").New().Add("a", "c"), map[string][]string{"A": []string{"B", "c"}}},
}
for _, c := range cases {
// type conversion from header to alias'd map for deep equality comparison
headerMap := map[string][]string(c.sling.header)
if !reflect.DeepEqual(c.expectedHeader, headerMap) {
t.Errorf("not DeepEqual: expected %v, got %v", c.expectedHeader, headerMap)
}
}
}
func TestSetHeader(t *testing.T) {
cases := []struct {
sling *Sling
expectedHeader map[string][]string
}{
// should replace existing values associated with key
{New().Add("A", "B").Set("a", "c"), map[string][]string{"A": []string{"c"}}},
{New().Set("content-type", "A").Set("Content-Type", "B"), map[string][]string{"Content-Type": []string{"B"}}},
// Set should replace values received by copying parent Slings
{New().Set("A", "B").Add("a", "c").New(), map[string][]string{"A": []string{"B", "c"}}},
{New().Add("A", "B").New().Set("a", "c"), map[string][]string{"A": []string{"c"}}},
}
for _, c := range cases {
// type conversion from Header to alias'd map for deep equality comparison
headerMap := map[string][]string(c.sling.header)
if !reflect.DeepEqual(c.expectedHeader, headerMap) {
t.Errorf("not DeepEqual: expected %v, got %v", c.expectedHeader, headerMap)
}
}
}
func TestBasicAuth(t *testing.T) {
cases := []struct {
sling *Sling
expectedAuth []string
}{
// basic auth: username & password
{New().SetBasicAuth("Aladdin", "open sesame"), []string{"Aladdin", "open sesame"}},
// empty username
{New().SetBasicAuth("", "secret"), []string{"", "secret"}},
// empty password
{New().SetBasicAuth("admin", ""), []string{"admin", ""}},
}
for _, c := range cases {
req, err := c.sling.Request()
if err != nil {
t.Errorf("unexpected error when building Request with .SetBasicAuth()")
}
username, password, ok := req.BasicAuth()
if !ok {
t.Errorf("basic auth missing when expected")
}
auth := []string{username, password}
if !reflect.DeepEqual(c.expectedAuth, auth) {
t.Errorf("not DeepEqual: expected %v, got %v", c.expectedAuth, auth)
}
}
}
func TestQueryStructSetter(t *testing.T) {
cases := []struct {
sling *Sling
expectedStructs []interface{}
}{
{New(), []interface{}{}},
{New().QueryStruct(nil), []interface{}{}},
{New().QueryStruct(paramsA), []interface{}{paramsA}},
{New().QueryStruct(paramsA).QueryStruct(paramsA), []interface{}{paramsA, paramsA}},
{New().QueryStruct(paramsA).QueryStruct(paramsB), []interface{}{paramsA, paramsB}},
{New().QueryStruct(paramsA).New(), []interface{}{paramsA}},
{New().QueryStruct(paramsA).New().QueryStruct(paramsB), []interface{}{paramsA, paramsB}},
}
for _, c := range cases {
if count := len(c.sling.queryStructs); count != len(c.expectedStructs) {
t.Errorf("expected length %d, got %d", len(c.expectedStructs), count)
}
check:
for _, expected := range c.expectedStructs {
for _, param := range c.sling.queryStructs {
if param == expected {
continue check
}
}
t.Errorf("expected to find %v in %v", expected, c.sling.queryStructs)
}
}
}
func TestBodyJSONSetter(t *testing.T) {
fakeModel := &FakeModel{}
fakeBodyProvider := jsonBodyProvider{payload: fakeModel}
cases := []struct {
initial BodyProvider
input interface{}
expected BodyProvider
}{
// json tagged struct is set as bodyJSON
{nil, fakeModel, fakeBodyProvider},
// nil argument to bodyJSON does not replace existing bodyJSON
{fakeBodyProvider, nil, fakeBodyProvider},
// nil bodyJSON remains nil
{nil, nil, nil},
}
for _, c := range cases {
sling := New()
sling.bodyProvider = c.initial
sling.BodyJSON(c.input)
if sling.bodyProvider != c.expected {
t.Errorf("expected %v, got %v", c.expected, sling.bodyProvider)
}
// Header Content-Type should be application/json if bodyJSON arg was non-nil
if c.input != nil && sling.header.Get(contentType) != jsonContentType {
t.Errorf("Incorrect or missing header, expected %s, got %s", jsonContentType, sling.header.Get(contentType))
} else if c.input == nil && sling.header.Get(contentType) != "" {
t.Errorf("did not expect a Content-Type header, got %s", sling.header.Get(contentType))
}
}
}
func TestBodyFormSetter(t *testing.T) {
fakeParams := FakeParams{KindName: "recent", Count: 25}
fakeBodyProvider := formBodyProvider{payload: fakeParams}
cases := []struct {
initial BodyProvider
input interface{}
expected BodyProvider
}{
// url tagged struct is set as bodyStruct
{nil, paramsB, fakeBodyProvider},
// nil argument to bodyStruct does not replace existing bodyStruct
{fakeBodyProvider, nil, fakeBodyProvider},
// nil bodyStruct remains nil
{nil, nil, nil},
}
for _, c := range cases {
sling := New()
sling.bodyProvider = c.initial
sling.BodyForm(c.input)
if sling.bodyProvider != c.expected {
t.Errorf("expected %v, got %v", c.expected, sling.bodyProvider)
}
// Content-Type should be application/x-www-form-urlencoded if bodyStruct was non-nil
if c.input != nil && sling.header.Get(contentType) != formContentType {
t.Errorf("Incorrect or missing header, expected %s, got %s", formContentType, sling.header.Get(contentType))
} else if c.input == nil && sling.header.Get(contentType) != "" {
t.Errorf("did not expect a Content-Type header, got %s", sling.header.Get(contentType))
}
}
}
func TestBodySetter(t *testing.T) {
fakeInput := io.NopCloser(strings.NewReader("test"))
fakeBodyProvider := bodyProvider{body: fakeInput}
cases := []struct {
initial BodyProvider
input io.Reader
expected BodyProvider
}{
// nil body is overriden by a set body
{nil, fakeInput, fakeBodyProvider},
// initial body is not overriden by nil body
{fakeBodyProvider, nil, fakeBodyProvider},
// nil body is returned unaltered
{nil, nil, nil},
}
for _, c := range cases {
sling := New()
sling.bodyProvider = c.initial
sling.Body(c.input)
if sling.bodyProvider != c.expected {
t.Errorf("expected %v, got %v", c.expected, sling.bodyProvider)
}
}
}
func TestRequest_urlAndMethod(t *testing.T) {
cases := []struct {
sling *Sling
expectedMethod string
expectedURL string
expectedErr error
}{
{New().Base("http://a.io"), "GET", "http://a.io", nil},
{New().Path("http://a.io"), "GET", "http://a.io", nil},
{New().Get("http://a.io"), "GET", "http://a.io", nil},
{New().Put("http://a.io"), "PUT", "http://a.io", nil},
{New().Base("http://a.io/").Path("foo"), "GET", "http://a.io/foo", nil},
{New().Base("http://a.io/").Post("foo"), "POST", "http://a.io/foo", nil},
// if relative path is an absolute url, base is ignored
{New().Base("http://a.io").Path("http://b.io"), "GET", "http://b.io", nil},
{New().Path("http://a.io").Path("http://b.io"), "GET", "http://b.io", nil},
// last method setter takes priority
{New().Get("http://b.io").Post("http://a.io"), "POST", "http://a.io", nil},
{New().Post("http://a.io/").Put("foo/").Delete("bar"), "DELETE", "http://a.io/foo/bar", nil},
// last Base setter takes priority
{New().Base("http://a.io").Base("http://b.io"), "GET", "http://b.io", nil},
// Path setters are additive
{New().Base("http://a.io/").Path("foo/").Path("bar"), "GET", "http://a.io/foo/bar", nil},
{New().Path("http://a.io/").Path("foo/").Path("bar"), "GET", "http://a.io/foo/bar", nil},
// removes extra '/' between base and ref url
{New().Base("http://a.io/").Get("/foo"), "GET", "http://a.io/foo", nil},
}
for _, c := range cases {
req, err := c.sling.Request()
if err != c.expectedErr {
t.Errorf("expected error %v, got %v for %+v", c.expectedErr, err, c.sling)
}
if req.URL.String() != c.expectedURL {
t.Errorf("expected url %s, got %s for %+v", c.expectedURL, req.URL.String(), c.sling)
}
if req.Method != c.expectedMethod {
t.Errorf("expected method %s, got %s for %+v", c.expectedMethod, req.Method, c.sling)
}
}
}
func TestRequest_queryStructs(t *testing.T) {
cases := []struct {
sling *Sling
expectedURL string
}{
{New().Base("http://a.io").QueryStruct(paramsA), "http://a.io?limit=30"},
{New().Base("http://a.io").QueryStruct(paramsA).QueryStruct(paramsB), "http://a.io?count=25&kind_name=recent&limit=30"},
{New().Base("http://a.io/").Path("foo?path=yes").QueryStruct(paramsA), "http://a.io/foo?limit=30&path=yes"},
{New().Base("http://a.io").QueryStruct(paramsA).New(), "http://a.io?limit=30"},
{New().Base("http://a.io").QueryStruct(paramsA).New().QueryStruct(paramsB), "http://a.io?count=25&kind_name=recent&limit=30"},
}
for _, c := range cases {
req, _ := c.sling.Request()
if req.URL.String() != c.expectedURL {
t.Errorf("expected url %s, got %s for %+v", c.expectedURL, req.URL.String(), c.sling)
}
}
}
func TestRequest_body(t *testing.T) {
cases := []struct {
sling *Sling
expectedBody string // expected Body io.Reader as a string
expectedContentType string
}{
// BodyJSON
{New().BodyJSON(modelA), "{\"text\":\"note\",\"favorite_count\":12}\n", jsonContentType},
{New().BodyJSON(&modelA), "{\"text\":\"note\",\"favorite_count\":12}\n", jsonContentType},
{New().BodyJSON(&FakeModel{}), "{}\n", jsonContentType},
{New().BodyJSON(FakeModel{}), "{}\n", jsonContentType},
// BodyJSON overrides existing values
{New().BodyJSON(&FakeModel{}).BodyJSON(&FakeModel{Text: "msg"}), "{\"text\":\"msg\"}\n", jsonContentType},
// BodyForm
{New().BodyForm(paramsA), "limit=30", formContentType},
{New().BodyForm(paramsB), "count=25&kind_name=recent", formContentType},
{New().BodyForm(¶msB), "count=25&kind_name=recent", formContentType},
// BodyForm overrides existing values
{New().BodyForm(paramsA).New().BodyForm(paramsB), "count=25&kind_name=recent", formContentType},
// Mixture of BodyJSON and BodyForm prefers body setter called last with a non-nil argument
{New().BodyForm(paramsB).New().BodyJSON(modelA), "{\"text\":\"note\",\"favorite_count\":12}\n", jsonContentType},
{New().BodyJSON(modelA).New().BodyForm(paramsB), "count=25&kind_name=recent", formContentType},
{New().BodyForm(paramsB).New().BodyJSON(nil), "count=25&kind_name=recent", formContentType},
{New().BodyJSON(modelA).New().BodyForm(nil), "{\"text\":\"note\",\"favorite_count\":12}\n", jsonContentType},
// Body
{New().Body(strings.NewReader("this-is-a-test")), "this-is-a-test", ""},
{New().Body(strings.NewReader("a")).Body(strings.NewReader("b")), "b", ""},
}
for _, c := range cases {
req, _ := c.sling.Request()
buf := new(bytes.Buffer)
buf.ReadFrom(req.Body)
// req.Body should have contained the expectedBody string
if value := buf.String(); value != c.expectedBody {
t.Errorf("expected Request.Body %s, got %s", c.expectedBody, value)
}
// Header Content-Type should be expectedContentType ("" means no contentType expected)
if actualHeader := req.Header.Get(contentType); actualHeader != c.expectedContentType && c.expectedContentType != "" {
t.Errorf("Incorrect or missing header, expected %s, got %s", c.expectedContentType, actualHeader)
}
}
}
func TestRequest_bodyNoData(t *testing.T) {
// test that Body is left nil when no bodyJSON or bodyStruct set
slings := []*Sling{
New(),
New().BodyJSON(nil),
New().BodyForm(nil),
}
for _, sling := range slings {
req, _ := sling.Request()
if req.Body != nil {
t.Errorf("expected nil Request.Body, got %v", req.Body)
}
// Header Content-Type should not be set when bodyJSON argument was nil or never called
if actualHeader := req.Header.Get(contentType); actualHeader != "" {
t.Errorf("did not expect a Content-Type header, got %s", actualHeader)
}
}
}
func TestRequest_bodyEncodeErrors(t *testing.T) {
cases := []struct {
sling *Sling
expectedErr error
}{
// check that Encode errors are propagated, illegal JSON field
{New().BodyJSON(FakeModel{Temperature: math.Inf(1)}), errors.New("json: unsupported value: +Inf")},
}
for _, c := range cases {
req, err := c.sling.Request()
if err == nil || err.Error() != c.expectedErr.Error() {
t.Errorf("expected error %v, got %v", c.expectedErr, err)
}
if req != nil {
t.Errorf("expected nil Request, got %+v", req)
}
}
}
func TestRequest_headers(t *testing.T) {
cases := []struct {
sling *Sling
expectedHeader map[string][]string
}{
{New().Add("authorization", "OAuth key=\"value\""), map[string][]string{"Authorization": []string{"OAuth key=\"value\""}}},
// header keys should be canonicalized
{New().Add("content-tYPE", "application/json").Add("User-AGENT", "sling"), map[string][]string{"Content-Type": []string{"application/json"}, "User-Agent": []string{"sling"}}},
// values for existing keys should be appended
{New().Add("A", "B").Add("a", "c"), map[string][]string{"A": []string{"B", "c"}}},
// Add should add to values for keys added by parent Slings
{New().Add("A", "B").Add("a", "c").New(), map[string][]string{"A": []string{"B", "c"}}},
{New().Add("A", "B").New().Add("a", "c"), map[string][]string{"A": []string{"B", "c"}}},
// Add and Set
{New().Add("A", "B").Set("a", "c"), map[string][]string{"A": []string{"c"}}},
{New().Set("content-type", "A").Set("Content-Type", "B"), map[string][]string{"Content-Type": []string{"B"}}},
// Set should replace values received by copying parent Slings
{New().Set("A", "B").Add("a", "c").New(), map[string][]string{"A": []string{"B", "c"}}},
{New().Add("A", "B").New().Set("a", "c"), map[string][]string{"A": []string{"c"}}},
}
for _, c := range cases {
req, _ := c.sling.Request()
// type conversion from Header to alias'd map for deep equality comparison
headerMap := map[string][]string(req.Header)
if !reflect.DeepEqual(c.expectedHeader, headerMap) {
t.Errorf("not DeepEqual: expected %v, got %v", c.expectedHeader, headerMap)
}
}
}
func TestAddQueryStructs(t *testing.T) {
cases := []struct {
rawurl string
queryStructs []interface{}
expected string
}{
{"http://a.io", []interface{}{}, "http://a.io"},
{"http://a.io", []interface{}{paramsA}, "http://a.io?limit=30"},
{"http://a.io", []interface{}{paramsA, paramsA}, "http://a.io?limit=30&limit=30"},
{"http://a.io", []interface{}{paramsA, paramsB}, "http://a.io?count=25&kind_name=recent&limit=30"},
// don't blow away query values on the rawURL (parsed into RawQuery)
{"http://a.io?initial=7", []interface{}{paramsA}, "http://a.io?initial=7&limit=30"},
}
for _, c := range cases {
reqURL, _ := url.Parse(c.rawurl)
addQueryStructs(reqURL, c.queryStructs)
if reqURL.String() != c.expected {
t.Errorf("expected %s, got %s", c.expected, reqURL.String())
}
}
}
// Sending
type APIError struct {
Message string `json:"message"`
Code int `json:"code"`
}
func TestDo_onSuccess(t *testing.T) {
const expectedText = "Some text"
const expectedFavoriteCount int64 = 24
client, mux, server := testServer()
defer server.Close()
mux.HandleFunc("/success", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, `{"text": "Some text", "favorite_count": 24}`)
})
sling := New().Client(client)
req, _ := http.NewRequest("GET", "http://example.com/success", nil)
model := new(FakeModel)
apiError := new(APIError)
resp, err := sling.Do(req, model, apiError)
if err != nil {
t.Errorf("expected nil, got %v", err)
}
if resp.StatusCode != 200 {
t.Errorf("expected %d, got %d", 200, resp.StatusCode)
}
if model.Text != expectedText {
t.Errorf("expected %s, got %s", expectedText, model.Text)
}
if model.FavoriteCount != expectedFavoriteCount {
t.Errorf("expected %d, got %d", expectedFavoriteCount, model.FavoriteCount)
}
}
func TestDo_onSuccessWithNilValue(t *testing.T) {
client, mux, server := testServer()
defer server.Close()
mux.HandleFunc("/success", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, `{"text": "Some text", "favorite_count": 24}`)
})
sling := New().Client(client)
req, _ := http.NewRequest("GET", "http://example.com/success", nil)
apiError := new(APIError)
resp, err := sling.Do(req, nil, apiError)
if err != nil {
t.Errorf("expected nil, got %v", err)
}
if resp.StatusCode != 200 {
t.Errorf("expected %d, got %d", 200, resp.StatusCode)
}
expected := &APIError{}
if !reflect.DeepEqual(expected, apiError) {
t.Errorf("failureV should not be populated, exepcted %v, got %v", expected, apiError)
}
}
func TestDo_noContent(t *testing.T) {
client, mux, server := testServer()
defer server.Close()
mux.HandleFunc("/nocontent", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(204)
})
sling := New().Client(client)
req, _ := http.NewRequest("DELETE", "http://example.com/nocontent", nil)
model := new(FakeModel)
apiError := new(APIError)
resp, err := sling.Do(req, model, apiError)
if err != nil {
t.Errorf("expected nil, got %v", err)
}
if resp.StatusCode != 204 {
t.Errorf("expected %d, got %d", 204, resp.StatusCode)
}
expectedModel := &FakeModel{}
if !reflect.DeepEqual(expectedModel, model) {
t.Errorf("successV should not be populated, exepcted %v, got %v", expectedModel, model)
}
expectedAPIError := &APIError{}
if !reflect.DeepEqual(expectedAPIError, apiError) {
t.Errorf("failureV should not be populated, exepcted %v, got %v", expectedAPIError, apiError)
}
}
func TestDo_onFailure(t *testing.T) {
const expectedMessage = "Invalid argument"
const expectedCode int = 215
client, mux, server := testServer()
defer server.Close()
mux.HandleFunc("/failure", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(400)
fmt.Fprintf(w, `{"message": "Invalid argument", "code": 215}`)
})
sling := New().Client(client)
req, _ := http.NewRequest("GET", "http://example.com/failure", nil)
model := new(FakeModel)
apiError := new(APIError)
resp, err := sling.Do(req, model, apiError)
if err != nil {
t.Errorf("expected nil, got %v", err)
}
if resp.StatusCode != 400 {
t.Errorf("expected %d, got %d", 400, resp.StatusCode)
}
if apiError.Message != expectedMessage {
t.Errorf("expected %s, got %s", expectedMessage, apiError.Message)
}
if apiError.Code != expectedCode {
t.Errorf("expected %d, got %d", expectedCode, apiError.Code)
}
}
func TestDo_onFailureWithNilValue(t *testing.T) {
client, mux, server := testServer()
defer server.Close()
mux.HandleFunc("/failure", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(420)
fmt.Fprintf(w, `{"message": "Enhance your calm", "code": 88}`)
})
sling := New().Client(client)
req, _ := http.NewRequest("GET", "http://example.com/failure", nil)
model := new(FakeModel)
resp, err := sling.Do(req, model, nil)
if err != nil {
t.Errorf("expected nil, got %v", err)
}
if resp.StatusCode != 420 {
t.Errorf("expected %d, got %d", 420, resp.StatusCode)
}
expected := &FakeModel{}
if !reflect.DeepEqual(expected, model) {
t.Errorf("successV should not be populated, exepcted %v, got %v", expected, model)
}
}
func TestReceive_success_nonDefaultDecoder(t *testing.T) {
client, mux, server := testServer()
defer server.Close()
mux.HandleFunc("/foo/submit", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/xml")
data := ` <response>
<text>Some text</text>
<favorite_count>24</favorite_count>
<temperature>10.5</temperature>
</response>`
fmt.Fprintf(w, xml.Header)
fmt.Fprint(w, data)
})
endpoint := New().Client(client).Base("http://example.com/").Path("foo/").Post("submit")
model := new(FakeModel)
apiError := new(APIError)
resp, err := endpoint.New().ResponseDecoder(xmlResponseDecoder{}).Receive(model, apiError)
if err != nil {
t.Errorf("expected nil, got %v", err)
}
if resp.StatusCode != 200 {
t.Errorf("expected %d, got %d", 200, resp.StatusCode)
}
expectedModel := &FakeModel{Text: "Some text", FavoriteCount: 24, Temperature: 10.5}
if !reflect.DeepEqual(expectedModel, model) {
t.Errorf("expected %v, got %v", expectedModel, model)
}
expectedAPIError := &APIError{}
if !reflect.DeepEqual(expectedAPIError, apiError) {
t.Errorf("failureV should be zero valued, exepcted %v, got %v", expectedAPIError, apiError)
}
}
func TestReceive_success(t *testing.T) {
client, mux, server := testServer()
defer server.Close()
mux.HandleFunc("/foo/submit", func(w http.ResponseWriter, r *http.Request) {
assertMethod(t, "POST", r)
assertQuery(t, map[string]string{"kind_name": "vanilla", "count": "11"}, r)
assertPostForm(t, map[string]string{"kind_name": "vanilla", "count": "11"}, r)
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, `{"text": "Some text", "favorite_count": 24}`)
})
endpoint := New().Client(client).Base("http://example.com/").Path("foo/").Post("submit")
// encode url-tagged struct in query params and as post body for testing purposes
params := FakeParams{KindName: "vanilla", Count: 11}
model := new(FakeModel)
apiError := new(APIError)
resp, err := endpoint.New().QueryStruct(params).BodyForm(params).Receive(model, apiError)
if err != nil {
t.Errorf("expected nil, got %v", err)
}
if resp.StatusCode != 200 {
t.Errorf("expected %d, got %d", 200, resp.StatusCode)
}
expectedModel := &FakeModel{Text: "Some text", FavoriteCount: 24}
if !reflect.DeepEqual(expectedModel, model) {
t.Errorf("expected %v, got %v", expectedModel, model)
}
expectedAPIError := &APIError{}
if !reflect.DeepEqual(expectedAPIError, apiError) {
t.Errorf("failureV should be zero valued, exepcted %v, got %v", expectedAPIError, apiError)
}
}
func TestReceive_StatusOKNoContent(t *testing.T) {
client, mux, server := testServer()
defer server.Close()
mux.HandleFunc("/foo/submit", func(w http.ResponseWriter, r *http.Request) {
assertMethod(t, "POST", r)
w.WriteHeader(201)
w.Header().Set("Location", "/foo/latest")
})
endpoint := New().Client(client).Base("http://example.com/").Path("foo/").Post("submit")
// fake a post response for testing purposes, checking that it's valid happens in other tests
params := FakeParams{}
model := new(FakeModel)
apiError := new(APIError)
resp, err := endpoint.New().BodyForm(params).Receive(model, apiError)
if err != nil {
t.Errorf("expected nil, got %v", err)
}
if resp.StatusCode != 201 {
t.Errorf("expected %d, got %d", 201, resp.StatusCode)
}
expectedModel := &FakeModel{}
if !reflect.DeepEqual(expectedModel, model) {
t.Errorf("expected %v, got %v", expectedModel, model)
}
expectedAPIError := &APIError{}
if !reflect.DeepEqual(expectedAPIError, apiError) {
t.Errorf("failureV should be zero valued, exepcted %v, got %v", expectedAPIError, apiError)
}
}
func TestReceive_failure(t *testing.T) {
client, mux, server := testServer()
defer server.Close()
mux.HandleFunc("/foo/submit", func(w http.ResponseWriter, r *http.Request) {
assertMethod(t, "POST", r)
assertQuery(t, map[string]string{"kind_name": "vanilla", "count": "11"}, r)
assertPostForm(t, map[string]string{"kind_name": "vanilla", "count": "11"}, r)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(429)
fmt.Fprintf(w, `{"message": "Rate limit exceeded", "code": 88}`)
})
endpoint := New().Client(client).Base("http://example.com/").Path("foo/").Post("submit")
// encode url-tagged struct in query params and as post body for testing purposes
params := FakeParams{KindName: "vanilla", Count: 11}
model := new(FakeModel)
apiError := new(APIError)
resp, err := endpoint.New().QueryStruct(params).BodyForm(params).Receive(model, apiError)
if err != nil {
t.Errorf("expected nil, got %v", err)
}
if resp.StatusCode != 429 {
t.Errorf("expected %d, got %d", 429, resp.StatusCode)
}
expectedAPIError := &APIError{Message: "Rate limit exceeded", Code: 88}
if !reflect.DeepEqual(expectedAPIError, apiError) {
t.Errorf("expected %v, got %v", expectedAPIError, apiError)
}
expectedModel := &FakeModel{}
if !reflect.DeepEqual(expectedModel, model) {
t.Errorf("successV should not be zero valued, expected %v, got %v", expectedModel, model)
}
}
func TestReceive_noContent(t *testing.T) {
client, mux, server := testServer()
defer server.Close()
mux.HandleFunc("/foo/submit", func(w http.ResponseWriter, r *http.Request) {
assertMethod(t, "HEAD", r)
w.WriteHeader(204)
})
endpoint := New().Client(client).Base("http://example.com/").Path("foo/").Head("submit")
resp, err := endpoint.New().Receive(nil, nil)
if err != nil {
t.Errorf("expected nil, got %v", err)
}
if resp.StatusCode != 204 {
t.Errorf("expected %d, got %d", 204, resp.StatusCode)
}
}
func TestReceive_errorCreatingRequest(t *testing.T) {
expectedErr := errors.New("json: unsupported value: +Inf")
resp, err := New().BodyJSON(FakeModel{Temperature: math.Inf(1)}).Receive(nil, nil)
if err == nil || err.Error() != expectedErr.Error() {
t.Errorf("expected %v, got %v", expectedErr, err)
}
if resp != nil {
t.Errorf("expected nil resp, got %v", resp)
}
}
func TestReuseTcpConnections(t *testing.T) {
var connCount int32
ln, _ := net.Listen("tcp", ":0")
rawURL := fmt.Sprintf("http://%s/", ln.Addr())
server := http.Server{
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assertMethod(t, "GET", r)
fmt.Fprintf(w, `{"text": "Some text"}`)
}),
ConnState: func(conn net.Conn, state http.ConnState) {
if state == http.StateNew {
atomic.AddInt32(&connCount, 1)
}
},
}
go server.Serve(ln)
endpoint := New().Client(http.DefaultClient).Base(rawURL).Path("foo/").Get("get")
for i := 0; i < 10; i++ {
resp, err := endpoint.New().Receive(nil, nil)
if err != nil {
t.Errorf("expected nil, got %v", err)
}
if resp.StatusCode != 200 {
t.Errorf("expected %d, got %d", 200, resp.StatusCode)
}
}
server.Shutdown(context.Background())
if count := atomic.LoadInt32(&connCount); count != 1 {
t.Errorf("expected 1, got %v", count)
}
}
// Testing Utils
// testServer returns an http Client, ServeMux, and Server. The client proxies
// requests to the server and handlers can be registered on the mux to handle
// requests. The caller must close the test server.
func testServer() (*http.Client, *http.ServeMux, *httptest.Server) {
mux := http.NewServeMux()
server := httptest.NewServer(mux)
transport := &http.Transport{
Proxy: func(req *http.Request) (*url.URL, error) {
return url.Parse(server.URL)
},
}
client := &http.Client{Transport: transport}
return client, mux, server
}
func assertMethod(t *testing.T, expectedMethod string, req *http.Request) {
if actualMethod := req.Method; actualMethod != expectedMethod {
t.Errorf("expected method %s, got %s", expectedMethod, actualMethod)
}
}
// assertQuery tests that the Request has the expected url query key/val pairs
func assertQuery(t *testing.T, expected map[string]string, req *http.Request) {
queryValues := req.URL.Query() // net/url Values is a map[string][]string
expectedValues := url.Values{}
for key, value := range expected {
expectedValues.Add(key, value)
}
if !reflect.DeepEqual(expectedValues, queryValues) {
t.Errorf("expected parameters %v, got %v", expected, req.URL.RawQuery)
}
}