forked from levigross/grequests
-
Notifications
You must be signed in to change notification settings - Fork 0
/
base_get_test.go
1300 lines (1031 loc) · 32.7 KB
/
base_get_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 grequests
import (
"bytes"
"context"
"encoding/json"
"encoding/xml"
"errors"
"io"
"net/http"
"net/http/cookiejar"
"net/http/httptest"
"net/url"
"os"
"testing"
"time"
)
type BasicGetResponse struct {
Args struct{} `json:"args"`
Headers struct {
Accept string `json:"Accept"`
AcceptEncoding string `json:"Accept-Encoding"`
AcceptLanguage string `json:"Accept-Language"`
Dnt string `json:"Dst"`
Host string `json:"Host"`
UserAgent string `json:"User-Agent"`
Hello string `json:"Hello"`
} `json:"headers"`
Origin string `json:"origin"`
URL string `json:"url"`
}
type BasicGetResponseNewHeader struct {
Args struct{} `json:"args"`
Headers struct {
Accept string `json:"Accept"`
AcceptEncoding string `json:"Accept-Encoding"`
AcceptLanguage string `json:"Accept-Language"`
Dnt string `json:"Dst"`
Host string `json:"Host"`
UserAgent string `json:"User-Agent"`
XWonderfulHeader string `json:"X-Wonderful-Header"`
} `json:"headers"`
Origin string `json:"origin"`
URL string `json:"url"`
}
type BasicGetResponseBasicAuth struct {
Args struct{} `json:"args"`
Headers struct {
Accept string `json:"Accept"`
AcceptEncoding string `json:"Accept-Encoding"`
AcceptLanguage string `json:"Accept-Language"`
Dnt string `json:"Dst"`
Host string `json:"Host"`
UserAgent string `json:"User-Agent"`
Authorization string `json:"Authorization"`
} `json:"headers"`
Origin string `json:"origin"`
URL string `json:"url"`
}
type BasicGetResponseArgs struct {
Args struct {
Goodbye string `json:"Goodbye"`
Hello string `json:"Hello"`
} `json:"args"`
Headers struct {
Accept string `json:"Accept"`
AcceptEncoding string `json:"Accept-Encoding"`
AcceptLanguage string `json:"Accept-Language"`
Dnt string `json:"Dst"`
Host string `json:"Host"`
UserAgent string `json:"User-Agent"`
Authorization string `json:"Authorization"`
} `json:"headers"`
Origin string `json:"origin"`
URL string `json:"url"`
}
type GetXMLSample struct {
XMLName xml.Name `xml:"slideshow"`
Title string `xml:"title,attr"`
Date string `xml:"date,attr"`
Author string `xml:"author,attr"`
Slide []struct {
Type string `xml:"type,attr"`
Title string `xml:"title"`
} `xml:"slide"`
}
type TestJSONCookies struct {
Cookies struct {
AnotherCookie string `json:"AnotherCookie"`
TestCookie string `json:"TestCookie"`
} `json:"cookies"`
}
type MassiveJSONBlob struct {
Type string `json:"type"`
Features []struct {
Type string `json:"type"`
Properties struct {
MAPBLKLOT string `json:"MAPBLKLOT"`
BLKLOT string `json:"BLKLOT"`
BLOCKNUM string `json:"BLOCK_NUM"`
LOTNUM string `json:"LOT_NUM"`
FROMST string `json:"FROM_ST"`
TOST string `json:"TO_ST"`
STREET string `json:"STREET"`
STTYPE interface{} `json:"ST_TYPE"`
ODDEVEN string `json:"ODD_EVEN"`
} `json:"properties"`
Geometry struct {
Type string `json:"type"`
Coordinates []struct {
Num0 []float64 `json:"0,omitempty"`
Num1 []float64 `json:"1,omitempty"`
Num2 []float64 `json:"2,omitempty"`
Num3 []float64 `json:"3,omitempty"`
Num4 []float64 `json:"4,omitempty"`
Num5 []float64 `json:"5,omitempty"`
Num6 []float64 `json:"6,omitempty"`
Num7 []float64 `json:"7,omitempty"`
Num8 []float64 `json:"8,omitempty"`
Num9 []float64 `json:"9,omitempty"`
Num10 []float64 `json:"10,omitempty"`
} `json:"-"`
} `json:"geometry"`
} `json:"features"`
}
type GithubSelfJSON struct {
ID int `json:"id"`
Name string `json:"name"`
FullName string `json:"full_name"`
Owner struct {
Login string `json:"login"`
ID int `json:"id"`
AvatarURL string `json:"avatar_url"`
GravatarID string `json:"gravatar_id"`
URL string `json:"url"`
HTMLURL string `json:"html_url"`
FollowersURL string `json:"followers_url"`
FollowingURL string `json:"following_url"`
GistsURL string `json:"gists_url"`
StarredURL string `json:"starred_url"`
SubscriptionsURL string `json:"subscriptions_url"`
OrganizationsURL string `json:"organizations_url"`
ReposURL string `json:"repos_url"`
EventsURL string `json:"events_url"`
ReceivedEventsURL string `json:"received_events_url"`
Type string `json:"type"`
SiteAdmin bool `json:"site_admin"`
} `json:"owner"`
Private bool `json:"private"`
HTMLURL string `json:"html_url"`
Description string `json:"description"`
Fork bool `json:"fork"`
URL string `json:"url"`
ForksURL string `json:"forks_url"`
KeysURL string `json:"keys_url"`
CollaboratorsURL string `json:"collaborators_url"`
TeamsURL string `json:"teams_url"`
HooksURL string `json:"hooks_url"`
IssueEventsURL string `json:"issue_events_url"`
EventsURL string `json:"events_url"`
AssigneesURL string `json:"assignees_url"`
BranchesURL string `json:"branches_url"`
TagsURL string `json:"tags_url"`
BlobsURL string `json:"blobs_url"`
GitTagsURL string `json:"git_tags_url"`
GitRefsURL string `json:"git_refs_url"`
TreesURL string `json:"trees_url"`
StatusesURL string `json:"statuses_url"`
LanguagesURL string `json:"languages_url"`
StargazersURL string `json:"stargazers_url"`
ContributorsURL string `json:"contributors_url"`
SubscribersURL string `json:"subscribers_url"`
SubscriptionURL string `json:"subscription_url"`
CommitsURL string `json:"commits_url"`
GitCommitsURL string `json:"git_commits_url"`
CommentsURL string `json:"comments_url"`
IssueCommentURL string `json:"issue_comment_url"`
ContentsURL string `json:"contents_url"`
CompareURL string `json:"compare_url"`
MergesURL string `json:"merges_url"`
ArchiveURL string `json:"archive_url"`
DownloadsURL string `json:"downloads_url"`
IssuesURL string `json:"issues_url"`
PullsURL string `json:"pulls_url"`
MilestonesURL string `json:"milestones_url"`
NotificationsURL string `json:"notifications_url"`
LabelsURL string `json:"labels_url"`
ReleasesURL string `json:"releases_url"`
DeploymentsURL string `json:"deployments_url"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
PushedAt time.Time `json:"pushed_at"`
GitURL string `json:"git_url"`
SSHURL string `json:"ssh_url"`
CloneURL string `json:"clone_url"`
SvnURL string `json:"svn_url"`
Homepage string `json:"homepage"`
Size int `json:"size"`
StargazersCount int `json:"stargazers_count"`
WatchersCount int `json:"watchers_count"`
Language string `json:"language"`
HasIssues bool `json:"has_issues"`
HasDownloads bool `json:"has_downloads"`
HasWiki bool `json:"has_wiki"`
HasPages bool `json:"has_pages"`
ForksCount int `json:"forks_count"`
MirrorURL interface{} `json:"mirror_url"`
OpenIssuesCount int `json:"open_issues_count"`
Forks int `json:"forks"`
OpenIssues int `json:"open_issues"`
Watchers int `json:"watchers"`
DefaultBranch string `json:"default_branch"`
NetworkCount int `json:"network_count"`
SubscribersCount int `json:"subscribers_count"`
}
func TestGetNoOptions(t *testing.T) {
resp, _ := Get("http://httpbin.org/get", nil)
verifyOkResponse(resp, t)
}
func TestGetRequestHook(t *testing.T) {
addHelloWorld := func(req *http.Request) error {
req.Header.Add("Hello", "World")
return nil
}
resp, _ := Get("http://httpbin.org/get",
&RequestOptions{BeforeRequest: addHelloWorld})
j := verifyOkResponse(resp, t)
if j.Headers.Hello != "World" {
t.Error("Hook Function failed")
}
}
func TestGetNoOptionsCustomClient(t *testing.T) {
resp, _ := Get("http://httpbin.org/get",
&RequestOptions{HTTPClient: http.DefaultClient})
verifyOkResponse(resp, t)
}
func TestGetCustomTLSHandshakeTimeout(t *testing.T) {
ro := &RequestOptions{TLSHandshakeTimeout: 10 * time.Millisecond}
if _, err := Get("https://httpbin.org", ro); err == nil {
t.Error("unexpected: successful TLS Handshake")
}
}
func TestGetCustomDialTimeout(t *testing.T) {
ro := &RequestOptions{DialTimeout: time.Nanosecond}
if _, err := Get("http://httpbin.org", ro); err == nil {
t.Error("unexpected: successful connection")
}
}
func TestGetProxy(t *testing.T) {
ch := make(chan string, 1)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ch <- "real server"
}))
defer ts.Close()
proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ch <- "proxy for " + r.URL.String()
}))
defer proxy.Close()
pu, err := url.Parse(proxy.URL)
if err != nil {
t.Fatal(err)
}
resp, err := Head(ts.URL, &RequestOptions{Proxies: map[string]*url.URL{pu.Scheme: pu}})
defer http.DefaultTransport.(*http.Transport).CloseIdleConnections()
if err != nil {
t.Error("Unable to make request: ", err)
}
if resp.Ok != true {
t.Error("Response is not OK for some reason: ", resp.StatusCode)
}
got := <-ch
want := "proxy for " + ts.URL + "/"
if got != want {
t.Errorf("want %q, got %q", want, got)
}
}
func TestGetSyncInvalidProxyScheme(t *testing.T) {
resp, err := Get("http://httpbin.org/get", &RequestOptions{Proxies: map[string]*url.URL{"gopher": nil}})
if err != nil {
t.Error("Request failed: ", err)
}
verifyOkResponse(resp, t)
}
func TestGetSyncNoOptions(t *testing.T) {
resp, err := Get("http://httpbin.org/get", nil)
if err != nil {
t.Error("Request failed: ", err)
}
verifyOkResponse(resp, t)
}
func TestGetNoOptionsGzip(t *testing.T) {
resp, _ := Get("https://httpbin.org/gzip", nil)
verifyOkResponse(resp, t)
}
func TestGetWithCookies(t *testing.T) {
resp, err := Get("http://httpbin.org/cookies",
&RequestOptions{
Cookies: []*http.Cookie{
{
Name: "TestCookie",
Value: "Random Value",
HttpOnly: true,
Secure: false,
}, {
Name: "AnotherCookie",
Value: "Some Value",
HttpOnly: true,
Secure: false,
},
},
})
if err != nil {
t.Error("Unable to make request", err)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
myJSONStruct := &TestJSONCookies{}
if err := resp.JSON(myJSONStruct); err != nil {
t.Error("Cannot serialize cookie JSON: ", err)
}
if myJSONStruct.Cookies.TestCookie != "Random Value" {
t.Errorf("Cookie value not set properly: %#v", myJSONStruct)
}
if myJSONStruct.Cookies.AnotherCookie != "Some Value" {
t.Errorf("Cookie value not set properly: %#v", myJSONStruct)
}
}
func TestGetWithCookiesCustomCookieJar(t *testing.T) {
cookieJar, _ := cookiejar.New(nil)
resp, err := Get("http://httpbin.org/cookies",
&RequestOptions{
CookieJar: cookieJar,
Cookies: []*http.Cookie{
{
Name: "TestCookie",
Value: "Random Value",
HttpOnly: true,
Secure: false,
}, {
Name: "AnotherCookie",
Value: "Some Value",
HttpOnly: true,
Secure: false,
},
},
})
if err != nil {
t.Error("Unable to make request", err)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
myJSONStruct := &TestJSONCookies{}
if err := resp.JSON(myJSONStruct); err != nil {
t.Error("Cannot serialize cookie JSON: ", err)
}
if myJSONStruct.Cookies.TestCookie != "Random Value" {
t.Errorf("Cookie value not set properly: %#v", myJSONStruct)
}
if myJSONStruct.Cookies.AnotherCookie != "Some Value" {
t.Errorf("Cookie value not set properly: %#v", myJSONStruct)
}
}
func TestGetSession(t *testing.T) {
session := NewSession(nil)
resp, err := session.Get("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"one": "two"}})
if err != nil {
t.Fatal("Cannot set cookie: ", err)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
resp, err = session.Get("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"two": "three"}})
if err != nil {
t.Fatal("Cannot set cookie: ", err)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
resp, err = session.Get("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"three": "four"}})
if err != nil {
t.Fatal("Cannot set cookie: ", err)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
cookieURL, err := url.Parse("http://httpbin.org")
if err != nil {
t.Error("We (for some reason) cannot parse the cookie URL")
}
if len(session.HTTPClient.Jar.Cookies(cookieURL)) != 3 {
t.Error("Invalid number of cookies provided: ", session.HTTPClient.Jar.Cookies(cookieURL))
}
for _, cookie := range session.HTTPClient.Jar.Cookies(cookieURL) {
switch cookie.Name {
case "one":
if cookie.Value != "two" {
t.Error("Cookie value is not valid", cookie)
}
case "two":
if cookie.Value != "three" {
t.Error("Cookie value is not valid", cookie)
}
case "three":
if cookie.Value != "four" {
t.Error("Cookie value is not valid", cookie)
}
default:
t.Error("We should not have any other cookies: ", cookie)
}
}
session.CloseIdleConnections()
}
//func TestGetNoOptionsDeflate(t *testing.T) {
// verifyOkResponse(<-GetAsync("http://httpbin.org/deflate", nil), t)
//}
func xmlASCIIDecoder(charset string, input io.Reader) (io.Reader, error) {
return input, nil
}
func TestGetInvalidURL(t *testing.T) {
resp, err := Get("%../dir/", &RequestOptions{Params: map[string]string{"1": "2"}})
if err == nil {
t.Error("Some how the request was valid to make request", err)
}
resp.ClearInternalBuffer() // This will panic without our nil checks
}
func TestGetInvalidURLNoParams(t *testing.T) {
_, err := Get("%../dir/", nil)
if err == nil {
t.Error("Some how the request was valid to make request", err)
}
}
func TestGetInvalidURLSession(t *testing.T) {
session := NewSession(nil)
if _, err := session.Get("%../dir/", nil); err == nil {
t.Error("Some how the request was valid to make request ", err)
}
}
func TestGetXMLSerialize(t *testing.T) {
resp, err := Get("http://httpbin.org/xml", nil)
if err != nil {
t.Error("Unable to make request", err)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
userXML := &GetXMLSample{}
if err := resp.XML(userXML, xmlASCIIDecoder); err != nil {
t.Error("Unable to consume the response as XML: ", err)
}
if userXML.Title != "Sample Slide Show" {
t.Errorf("Invalid XML serialization %#v", userXML)
}
if err := resp.XML(int(123), nil); err == nil {
t.Error("Still able to consume XML from used response")
}
}
func TestGetCustomUserAgent(t *testing.T) {
ro := &RequestOptions{UserAgent: "LeviBot 0.1"}
resp, _ := Get("http://httpbin.org/get", ro)
jsonResp := verifyOkResponse(resp, t)
if jsonResp.Headers.UserAgent != "LeviBot 0.1" {
t.Error("User agent header not properly set")
}
}
func TestGetBasicAuth(t *testing.T) {
ro := &RequestOptions{Auth: []string{"Levi", "Bot"}}
resp, err := Get("http://httpbin.org/get", ro)
// Not the usual JSON so copy and paste from below
if err != nil {
t.Error("Unable to make request", err)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
myJSONStruct := &BasicGetResponseBasicAuth{}
err = resp.JSON(myJSONStruct)
if err != nil {
t.Error("Unable to coerce to JSON", err)
}
if myJSONStruct.Headers.Authorization != "Basic TGV2aTpCb3Q=" {
t.Error("Unable to set HTTP basic auth", myJSONStruct.Headers)
}
}
func TestGetCustomHeader(t *testing.T) {
ro := &RequestOptions{UserAgent: "LeviBot 0.1",
Headers: map[string]string{"X-Wonderful-Header": "1"}}
resp, err := Get("http://httpbin.org/get", ro)
// Not the usual JSON so copy and paste from below
if err != nil {
t.Error("Unable to make request", err)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
myJSONStruct := &BasicGetResponseNewHeader{}
err = resp.JSON(myJSONStruct)
if err != nil {
t.Error("Unable to coerce to JSON", err)
}
if myJSONStruct.Headers.XWonderfulHeader != "1" {
t.Error("Unable to set custom HTTP header", myJSONStruct.Headers)
}
}
func TestGetInvalidSSLCertNoVerify(t *testing.T) {
ro := &RequestOptions{InsecureSkipVerify: true}
for _, badSSL := range []string{
"https://self-signed.badssl.com/",
"https://expired.badssl.com/",
"https://wrong.host.badssl.com/",
} {
resp, err := Get(badSSL, ro)
if err != nil {
t.Error("Unable to make request", err)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
}
}
func TestGetInvalidSSLCertNoVerifyNoOptions(t *testing.T) {
for _, badSSL := range []string{
"https://self-signed.badssl.com/",
"https://expired.badssl.com/",
"https://wrong.host.badssl.com/",
} {
resp, err := Get(badSSL, nil)
if err == nil {
t.Error("Unable to make request", err)
}
if resp.Ok == true {
t.Error("Request did not return OK")
}
}
}
func TestGetInvalidSSLCertNoCompression(t *testing.T) {
ro := &RequestOptions{UserAgent: "LeviBot 0.1", DisableCompression: true}
resp, err := Get("https://self-signed.badssl.com/", ro)
if err == nil {
t.Error("SSL verification worked when it shouldn't of", err)
}
if resp.Ok == true {
t.Error("Request did return OK")
}
}
func TestGetInvalidSSLCertWithCompression(t *testing.T) {
ro := &RequestOptions{UserAgent: "LeviBot 0.1", DisableCompression: false}
resp, err := Get("https://self-signed.badssl.com/", ro)
if err == nil {
t.Error("SSL verification worked when it shouldn't of", err)
}
if resp.Ok == true {
t.Error("Request did return OK")
}
}
func TestErrorResponseNOOP(t *testing.T) {
ro := &RequestOptions{UserAgent: "LeviBot 0.1", DisableCompression: false}
resp, err := Get("https://self-signed.badssl.com/", ro)
if err == nil {
t.Error("SSL verification worked when it shouldn't of", err)
}
if resp.Ok == true {
t.Error("Request did return OK")
}
myJSONStruct := &BasicGetResponseArgs{}
if err := resp.JSON(myJSONStruct); err == nil {
t.Error("Somehow Able to convert to JSON", err)
}
if resp.Bytes() != nil {
t.Error("Somehow byte buffer is working now (bytes)", resp.Bytes())
}
if resp.String() != "" {
t.Error("Somehow byte buffer is working now (bytes)", resp.String())
}
resp.ClearInternalBuffer()
if resp.Bytes() != nil {
t.Error("Somehow byte buffer is working now (bytes)", resp.Bytes())
}
if resp.String() != "" {
t.Error("Somehow byte buffer is working now (bytes)", resp.String())
}
userXML := &GetXMLSample{}
if err := resp.XML(userXML, xmlASCIIDecoder); err == nil {
t.Errorf("Somehow to consume the response as XML: %#v", userXML)
}
fileName := "randomFile"
if err := resp.DownloadToFile(fileName); err == nil {
t.Error("Somehow able to download to file: ", err)
}
var buf [1]byte
if written, err := resp.Read(buf[:]); written != -1 && err == nil {
t.Error("Somehow we were able to read from our error response")
}
}
func TestGetInvalidSSLCertNoCompressionNoVerify(t *testing.T) {
ro := &RequestOptions{UserAgent: "LeviBot 0.1", InsecureSkipVerify: true, DisableCompression: true}
resp, err := Get("https://self-signed.badssl.com/", ro)
if err != nil {
t.Error("SSL verification worked when it shouldn't of", err)
}
if resp.Ok != true {
t.Error("Request did return OK")
}
}
func TestGetInvalidSSLCertWithCompressionNoVerify(t *testing.T) {
ro := &RequestOptions{UserAgent: "LeviBot 0.1", InsecureSkipVerify: true, DisableCompression: false}
resp, err := Get("https://self-signed.badssl.com/", ro)
if err != nil {
t.Error("SSL verification worked when it shouldn't of", err)
}
if resp.Ok != true {
t.Error("Request did return OK")
}
}
func TestGetInvalidSSLCert(t *testing.T) {
ro := &RequestOptions{UserAgent: "LeviBot 0.1"}
resp, err := Get("https://self-signed.badssl.com/", ro)
if err == nil {
t.Error("SSL verification worked when it shouldn't of", err)
}
if resp.Ok == true {
t.Error("Request did return OK")
}
}
func TestGetBasicArgs(t *testing.T) {
ro := &RequestOptions{
Params: map[string]string{"Hello": "World"},
}
resp, _ := Get("http://httpbin.org/get?Goodbye=World", ro)
verifyOkArgsResponse(resp, t)
}
func TestGetBasicArgsQueryStruct(t *testing.T) {
ro := &RequestOptions{
QueryStruct: struct {
Hello string `url:"Hello"`
}{
"World",
},
}
resp, _ := Get("http://httpbin.org/get?Goodbye=World", ro)
verifyOkArgsResponse(resp, t)
}
func TestGetBasicArgsQueryStructErr(t *testing.T) {
ro := &RequestOptions{
QueryStruct: 5,
}
resp, err := Get("http://httpbin.org/get?Goodbye=World", ro)
if err == nil {
t.Error("URL Parsing should have failed")
}
if resp.Ok == true {
t.Error("Request did return OK")
}
}
func TestGetBasicArgsQueryStructUrlQueryErr(t *testing.T) {
ro := &RequestOptions{
QueryStruct: 5,
}
resp, err := Get("http://httpbin.org/get?Goodbye=World%zz", ro)
if err == nil {
t.Error("URL Parsing should have failed")
}
if resp.Ok == true {
t.Error("Request did return OK")
}
}
func TestGetBasicArgsQueryStructUrlErr(t *testing.T) {
ro := &RequestOptions{
QueryStruct: 5,
}
resp, err := Get("%", ro)
if err == nil {
t.Error("URL Parsing should have failed")
}
if resp.Ok == true {
t.Error("Request did return OK")
}
}
func TestGetBasicArgsErr(t *testing.T) {
ro := &RequestOptions{
Params: map[string]string{"Hello": "World"},
}
resp, err := Get("http://httpbin.org/get?Goodbye=%zzz", ro)
if err == nil {
t.Error("URL Parsing should have failed")
}
if resp.Ok == true {
t.Error("Request did return OK")
}
}
func TestGetBasicArgsParams(t *testing.T) {
ro := &RequestOptions{
Params: map[string]string{"Hello": "World", "Goodbye": "World"},
}
resp, _ := Get("http://httpbin.org/get", ro)
verifyOkArgsResponse(resp, t)
}
func TestGetBasicArgsParamsOverwrite(t *testing.T) {
ro := &RequestOptions{
Params: map[string]string{"Hello": "World", "Goodbye": "World"},
}
resp, _ := Get("http://httpbin.org/get?Hello=Nothing", ro)
verifyOkArgsResponse(resp, t)
}
func TestGetFileDownload(t *testing.T) {
resp, err := Get("http://httpbin.org/get", nil)
fileName := "randomFile"
if err := resp.DownloadToFile(fileName); err != nil {
t.Error("Unable to download to file: ", err)
}
if err := resp.DownloadToFile("."); err == nil {
t.Error("Able to create file '.'")
}
fd, err := os.Open(fileName)
defer fd.Close()
defer os.Remove(fileName)
if err != nil {
t.Error("Unable to open file to verify content ", err)
}
jsonDecoder := json.NewDecoder(fd)
myJSONStruct := &BasicGetResponse{}
if err := jsonDecoder.Decode(myJSONStruct); err != nil {
t.Error("Unable to cocerce file to JSON ", err)
}
if myJSONStruct.URL != "http://httpbin.org/get" {
t.Error("For some reason the URL isn't the same", myJSONStruct.URL)
}
if myJSONStruct.Headers.Host != "httpbin.org" {
t.Error("The host header is invalid")
}
if resp.Bytes() != nil {
t.Error("JSON decoding did not fully consume the response stream (Bytes)", resp.Bytes())
}
if resp.String() != "" {
t.Error("JSON decoding did not fully consume the response stream (String)", resp.String())
}
if resp.StatusCode != 200 {
t.Error("Response returned a non-200 code")
}
}
func TestJsonConsumedResponse(t *testing.T) {
resp, err := Get("http://httpbin.org/get", nil)
if err != nil {
t.Error("Unable to make request", err)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
if resp.Bytes() == nil {
t.Error("Unable to coerce value to bytes", resp.Bytes())
}
resp.ClearInternalBuffer()
if err := resp.JSON(struct{}{}); err == nil {
t.Error("Struct should not be able to hold JSON: ")
}
}
func TestDownloadConsumedResponse(t *testing.T) {
resp, err := Get("http://httpbin.org/get", nil)
if err != nil {
t.Error("Unable to make request", err)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
if resp.Bytes() == nil {
t.Error("Unable to coerce value to bytes")
}
resp.ClearInternalBuffer()
if err := resp.DownloadToFile("randomFile"); err == nil {
t.Error("Still able to download file: ", err)
}
defer os.Remove("randomFile")
}
func TestGetBytes(t *testing.T) {
resp, err := Get("http://httpbin.org/get", nil)
if err != nil {
t.Error("Unable to make request", err)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
if resp.Bytes() == nil {
t.Error("JSON decoding did not fully consume the response stream")
}
if bytes.Compare(resp.Bytes(), resp.Bytes()) != 0 {
t.Error("Body bytes have not been cached", resp.Bytes())
}
}
func TestGetBytesNoBuffer(t *testing.T) {
resp, err := Get("http://httpbin.org/get", nil)
if err != nil {
t.Error("Unable to make request", err)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
if resp.Bytes() == nil {
t.Error("Cannot coerce HTTP response to bytes")
}
if bytes.Compare(resp.Bytes(), resp.Bytes()) != 0 {
t.Error("Body bytes have not been cached", resp.Bytes())
}