-
-
Notifications
You must be signed in to change notification settings - Fork 104
/
Copy pathtransport_test.go
1175 lines (1003 loc) · 29.1 KB
/
transport_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 httpmock_test
import (
"bytes"
"context"
"encoding/json"
"errors"
"net"
"net/http"
"net/url"
"reflect"
"regexp"
"strings"
"testing"
"time"
. "github.com/jarcoal/httpmock"
"github.com/jarcoal/httpmock/internal"
)
const testURL = "http://www.example.com/"
func TestMockTransport(t *testing.T) {
Activate()
defer Deactivate()
url := "https://github.com/"
body := `["hello world"]` + "\n"
RegisterResponder("GET", url, NewStringResponder(200, body))
RegisterResponder("GET", `=~/xxx\z`, NewStringResponder(200, body))
// Read it as a simple string (ioutil.ReadAll of assertBody will
// trigger io.EOF)
func() {
resp, err := http.Get(url)
if err != nil {
t.Fatal(err)
}
if !assertBody(t, resp, body) {
t.FailNow()
}
// the http client wraps our NoResponderFound error, so we just try and match on text
_, err = http.Get(testURL)
if err == nil {
t.Fatal("An error should occur")
}
if !strings.HasSuffix(err.Error(), NoResponderFound.Error()) {
t.Fatal(err)
}
// Use wrongly cased method, the error should warn us
req, err := http.NewRequest("Get", url, nil)
if err != nil {
t.Fatal(err)
}
c := http.Client{}
_, err = c.Do(req)
if err == nil {
t.Fatal("An error should occur")
}
if !strings.HasSuffix(err.Error(),
NoResponderFound.Error()+" for method Get, but one matches method GET") {
t.Fatal(err)
}
// Use POST instead of GET, the error should warn us
req, err = http.NewRequest("POST", url, nil)
if err != nil {
t.Fatal(err)
}
_, err = c.Do(req)
if err == nil {
t.Fatal("An error should occur")
}
if !strings.HasSuffix(err.Error(),
NoResponderFound.Error()+" for method POST, but one matches method GET") {
t.Fatal(err)
}
// Same using a regexp responder
req, err = http.NewRequest("POST", "http://pipo.com/xxx", nil)
if err != nil {
t.Fatal(err)
}
_, err = c.Do(req)
if err == nil {
t.Fatal("An error should occur")
}
if !strings.HasSuffix(err.Error(),
NoResponderFound.Error()+" for method POST, but one matches method GET") {
t.Fatal(err)
}
}()
// Do it again, but twice with json decoder (json Decode will not
// reach EOF, but Close is called as the JSON response is complete)
for i := 0; i < 2; i++ {
func() {
resp, err := http.Get(url)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
var res []string
err = json.NewDecoder(resp.Body).Decode(&res)
if err != nil {
t.Fatal(err)
}
if len(res) != 1 || res[0] != "hello world" {
t.Fatalf(`%v read instead of ["hello world"]`, res)
}
}()
}
}
// We should be able to find GET handlers when using an http.Request with a
// default (zero-value) .Method.
func TestMockTransportDefaultMethod(t *testing.T) {
Activate()
defer Deactivate()
const urlString = "https://github.com/"
url, err := url.Parse(urlString)
if err != nil {
t.Fatal(err)
}
body := "hello world"
RegisterResponder("GET", urlString, NewStringResponder(200, body))
req := &http.Request{
URL: url,
// Note: Method unspecified (zero-value)
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
t.Fatal(err)
}
assertBody(t, resp, body)
}
func TestMockTransportReset(t *testing.T) {
DeactivateAndReset()
if DefaultTransport.NumResponders() > 0 {
t.Fatal("expected no responders at this point")
}
RegisterResponder("GET", testURL, NewStringResponder(200, "hey"))
if DefaultTransport.NumResponders() != 1 {
t.Fatal("expected one responder")
}
Reset()
if DefaultTransport.NumResponders() > 0 {
t.Fatal("expected no responders as they were just reset")
}
}
func TestMockTransportNoResponder(t *testing.T) {
Activate()
defer DeactivateAndReset()
Reset()
if _, err := http.Get(testURL); err == nil {
t.Fatal("expected to receive a connection error due to lack of responders")
}
RegisterNoResponder(NewStringResponder(200, "hello world"))
resp, err := http.Get(testURL)
if err != nil {
t.Fatal("expected request to succeed")
}
assertBody(t, resp, "hello world")
// Using NewNotFoundResponder()
RegisterNoResponder(NewNotFoundResponder(nil))
_, err = http.Get(testURL)
if err == nil {
t.Fatal("an error should occur")
}
if !strings.HasSuffix(err.Error(), "Responder not found for GET http://www.example.com/") {
t.Fatalf("Unexpected error content: %s", err)
}
// Help the user in case a Responder exists for another method
RegisterResponder("POST", testURL, NewStringResponder(200, "hello world"))
_, err = http.Get(testURL)
if err == nil {
t.Fatal("an error should occur")
}
if !strings.HasSuffix(err.Error(), "Responder not found for GET http://www.example.com/, but one matches method POST") {
t.Fatalf("Unexpected error content: %s", err)
}
}
func TestMockTransportQuerystringFallback(t *testing.T) {
Activate()
defer DeactivateAndReset()
// register the testURL responder
RegisterResponder("GET", testURL, NewStringResponder(200, "hello world"))
for _, suffix := range []string{"?", "?hello=world", "?hello=world#foo", "?hello=world&hello=all", "#foo"} {
reqURL := testURL + suffix
t.Log(reqURL)
// make a request for the testURL with a querystring
resp, err := http.Get(reqURL)
if err != nil {
t.Fatalf("expected request %s to succeed", reqURL)
}
assertBody(t, resp, "hello world")
}
}
func TestMockTransportPathOnlyFallback(t *testing.T) {
// Just in case a panic occurs
defer DeactivateAndReset()
for _, test := range []struct {
Responder string
Paths []string
}{
{
// unsorted query string matches exactly
Responder: "/hello/world?query=string&abc=zz#fragment",
Paths: []string{
testURL + "hello/world?query=string&abc=zz#fragment",
},
},
{
// sorted query string matches all cases
Responder: "/hello/world?abc=zz&query=string#fragment",
Paths: []string{
testURL + "hello/world?query=string&abc=zz#fragment",
testURL + "hello/world?abc=zz&query=string#fragment",
},
},
{
// unsorted query string matches exactly
Responder: "/hello/world?query=string&abc=zz",
Paths: []string{
testURL + "hello/world?query=string&abc=zz",
},
},
{
// sorted query string matches all cases
Responder: "/hello/world?abc=zz&query=string",
Paths: []string{
testURL + "hello/world?query=string&abc=zz",
testURL + "hello/world?abc=zz&query=string",
},
},
{
// unsorted query string matches exactly
Responder: "/hello/world?query=string&query=string2&abc=zz",
Paths: []string{
testURL + "hello/world?query=string&query=string2&abc=zz",
},
},
// sorted query string matches all cases
{
Responder: "/hello/world?abc=zz&query=string&query=string2",
Paths: []string{
testURL + "hello/world?query=string&query=string2&abc=zz",
testURL + "hello/world?query=string2&query=string&abc=zz",
testURL + "hello/world?abc=zz&query=string2&query=string",
},
},
{
Responder: "/hello/world?query",
Paths: []string{
testURL + "hello/world?query",
},
},
{
Responder: "/hello/world?query&abc",
Paths: []string{
testURL + "hello/world?query&abc",
// testURL + "hello/world?abc&query" won' work as "=" is needed, see below
},
},
{
// In case the sorting does not matter for received params without
// values, we must register params with "="
Responder: "/hello/world?abc=&query=",
Paths: []string{
testURL + "hello/world?query&abc",
testURL + "hello/world?abc&query",
},
},
{
Responder: "/hello/world#fragment",
Paths: []string{
testURL + "hello/world#fragment",
},
},
{
Responder: "/hello/world",
Paths: []string{
testURL + "hello/world?query=string&abc=zz#fragment",
testURL + "hello/world?query=string&abc=zz",
testURL + "hello/world#fragment",
testURL + "hello/world",
},
},
// Regexp cases
{
Responder: `=~^http://.*/hello/.*ld\z`,
Paths: []string{
testURL + "hello/world?query=string&abc=zz#fragment",
testURL + "hello/world?query=string&abc=zz",
testURL + "hello/world#fragment",
testURL + "hello/world",
},
},
{
Responder: `=~^http://.*/hello/.*ld(\z|[?#])`,
Paths: []string{
testURL + "hello/world?query=string&abc=zz#fragment",
testURL + "hello/world?query=string&abc=zz",
testURL + "hello/world#fragment",
testURL + "hello/world",
},
},
{
Responder: `=~^/hello/.*ld\z`,
Paths: []string{
testURL + "hello/world?query=string&abc=zz#fragment",
testURL + "hello/world?query=string&abc=zz",
testURL + "hello/world#fragment",
testURL + "hello/world",
},
},
{
Responder: `=~^/hello/.*ld(\z|[?#])`,
Paths: []string{
testURL + "hello/world?query=string&abc=zz#fragment",
testURL + "hello/world?query=string&abc=zz",
testURL + "hello/world#fragment",
testURL + "hello/world",
},
},
{
Responder: `=~abc=zz`,
Paths: []string{
testURL + "hello/world?query=string&abc=zz#fragment",
testURL + "hello/world?query=string&abc=zz",
},
},
} {
Activate()
// register the responder
RegisterResponder("GET", test.Responder, NewStringResponder(200, "hello world"))
for _, reqURL := range test.Paths {
t.Logf("%s: %s", test.Responder, reqURL)
// make a request for the testURL with a querystring
resp, err := http.Get(reqURL)
if err != nil {
t.Errorf("%s: expected request %s to succeed", test.Responder, reqURL)
continue
}
assertBody(t, resp, "hello world")
}
DeactivateAndReset()
}
}
type dummyTripper struct{}
func (d *dummyTripper) RoundTrip(*http.Request) (*http.Response, error) {
return nil, nil
}
func TestMockTransportInitialTransport(t *testing.T) {
DeactivateAndReset()
tripper := &dummyTripper{}
http.DefaultTransport = tripper
Activate()
if http.DefaultTransport == tripper {
t.Fatal("expected http.DefaultTransport to be a mock transport")
}
Deactivate()
if http.DefaultTransport != tripper {
t.Fatal("expected http.DefaultTransport to be dummy")
}
}
func TestMockTransportNonDefault(t *testing.T) {
// create a custom http client w/ custom Roundtripper
client := &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: (&net.Dialer{
Timeout: 60 * time.Second,
KeepAlive: 30 * time.Second,
}).Dial,
TLSHandshakeTimeout: 60 * time.Second,
},
}
// activate mocks for the client
ActivateNonDefault(client)
defer DeactivateAndReset()
body := "hello world!"
RegisterResponder("GET", testURL, NewStringResponder(200, body))
req, err := http.NewRequest("GET", testURL, nil)
if err != nil {
t.Fatal(err)
}
resp, err := client.Do(req)
if err != nil {
t.Fatal(err)
}
assertBody(t, resp, body)
}
func TestMockTransportRespectsCancel(t *testing.T) {
Activate()
defer DeactivateAndReset()
const (
cancelNone = iota
cancelReq
cancelCtx
)
cases := []struct {
withCancel int
cancelNow bool
withPanic bool
expectedBody string
expectedErr error
}{
// No cancel specified at all. Falls back to normal behavior
{cancelNone, false, false, "hello world", nil},
// Cancel returns error
{cancelReq, true, false, "", errors.New("request canceled")},
// Cancel via context returns error
{cancelCtx, true, false, "", errors.New("context canceled")},
// Request can be cancelled but it is not cancelled.
{cancelReq, false, false, "hello world", nil},
// Request can be cancelled but it is not cancelled.
{cancelCtx, false, false, "hello world", nil},
// Panic in cancelled request is handled
{cancelReq, false, true, "", errors.New(`panic in responder: got "oh no"`)},
// Panic in cancelled request is handled
{cancelCtx, false, true, "", errors.New(`panic in responder: got "oh no"`)},
}
for _, c := range cases {
Reset()
if c.withPanic {
RegisterResponder("GET", testURL, func(r *http.Request) (*http.Response, error) {
time.Sleep(10 * time.Millisecond)
panic("oh no")
})
} else {
RegisterResponder("GET", testURL, func(r *http.Request) (*http.Response, error) {
time.Sleep(10 * time.Millisecond)
return NewStringResponse(http.StatusOK, "hello world"), nil
})
}
req, err := http.NewRequest("GET", testURL, nil)
if err != nil {
t.Fatal(err)
}
switch c.withCancel {
case cancelReq:
cancel := make(chan struct{}, 1)
req.Cancel = cancel // nolint: staticcheck
if c.cancelNow {
cancel <- struct{}{}
}
case cancelCtx:
ctx, cancel := context.WithCancel(req.Context())
req = req.WithContext(ctx)
if c.cancelNow {
cancel()
} else {
defer cancel() // avoid ctx leak
}
}
resp, err := http.DefaultClient.Do(req)
// If we expect an error but none was returned, it's fatal for this test...
if err == nil && c.expectedErr != nil {
t.Fatal("Error should not be nil")
}
if err != nil {
got := err.(*url.Error)
// Do not use reflect.DeepEqual as go 1.13 includes stack frames
// into errors issued by errors.New()
if c.expectedErr == nil || got.Err.Error() != c.expectedErr.Error() {
t.Errorf("Expected error: %v, got: %v", c.expectedErr, got.Err)
}
}
if c.expectedBody != "" {
assertBody(t, resp, c.expectedBody)
}
}
}
func TestMockTransportRespectsTimeout(t *testing.T) {
timeout := time.Millisecond
client := &http.Client{
Timeout: timeout,
}
ActivateNonDefault(client)
defer DeactivateAndReset()
RegisterResponder(
"GET", testURL,
func(r *http.Request) (*http.Response, error) {
time.Sleep(100 * timeout)
return NewStringResponse(http.StatusOK, ""), nil
},
)
_, err := client.Get(testURL)
if err == nil {
t.Fail()
}
}
func TestMockTransportCallCountReset(t *testing.T) {
Reset()
Activate()
defer Deactivate()
const (
url = "https://github.com/path?b=1&a=2"
url2 = "https://gitlab.com/"
)
RegisterResponder("GET", url, NewStringResponder(200, "body"))
RegisterResponder("POST", "=~gitlab", NewStringResponder(200, "body"))
_, err := http.Get(url)
if err != nil {
t.Fatal(err)
}
buff := new(bytes.Buffer)
json.NewEncoder(buff).Encode("{}") // nolint: errcheck
_, err = http.Post(url2, "application/json", buff)
if err != nil {
t.Fatal(err)
}
_, err = http.Get(url)
if err != nil {
t.Fatal(err)
}
totalCallCount := GetTotalCallCount()
if totalCallCount != 3 {
t.Fatalf("did not track the total count of calls correctly. expected it to be 3, but it was %v", totalCallCount)
}
info := GetCallCountInfo()
expectedInfo := map[string]int{
"GET " + url: 2,
// Regexp match generates 2 entries:
"POST " + url2: 1, // the matched call
"POST =~gitlab": 1, // the regexp responder
}
if !reflect.DeepEqual(info, expectedInfo) {
t.Fatalf("did not correctly track the call count info. expected it to be \n %+v\n but it was \n %+v", expectedInfo, info)
}
Reset()
afterResetTotalCallCount := GetTotalCallCount()
if afterResetTotalCallCount != 0 {
t.Fatalf("did not reset the total count of calls correctly. expected it to be 0 after reset, but it was %v", afterResetTotalCallCount)
}
info = GetCallCountInfo()
if !reflect.DeepEqual(info, map[string]int{}) {
t.Fatalf("did not correctly reset the call count info. expected it to be \n {}\n but it was \n %+v", info)
}
}
func TestMockTransportCallCountZero(t *testing.T) {
Reset()
Activate()
defer Deactivate()
const (
url = "https://github.com/path?b=1&a=2"
url2 = "https://gitlab.com/"
)
RegisterResponder("GET", url, NewStringResponder(200, "body"))
RegisterResponder("POST", "=~gitlab", NewStringResponder(200, "body"))
_, err := http.Get(url)
if err != nil {
t.Fatal(err)
}
buff := new(bytes.Buffer)
json.NewEncoder(buff).Encode("{}") // nolint: errcheck
_, err = http.Post(url2, "application/json", buff)
if err != nil {
t.Fatal(err)
}
_, err = http.Get(url)
if err != nil {
t.Fatal(err)
}
totalCallCount := GetTotalCallCount()
if totalCallCount != 3 {
t.Fatalf("did not track the total count of calls correctly. expected it to be 3, but it was %v", totalCallCount)
}
info := GetCallCountInfo()
expectedInfo := map[string]int{
"GET " + url: 2,
// Regexp match generates 2 entries:
"POST " + url2: 1, // the matched call
"POST =~gitlab": 1, // the regexp responder
}
if !reflect.DeepEqual(info, expectedInfo) {
t.Fatalf("did not correctly track the call count info. expected it to be \n %+v\n but it was \n %+v", expectedInfo, info)
}
ZeroCallCounters()
afterResetTotalCallCount := GetTotalCallCount()
if afterResetTotalCallCount != 0 {
t.Fatalf("did not reset the total count of calls correctly. expected it to be 0 after reset, but it was %v", afterResetTotalCallCount)
}
info = GetCallCountInfo()
expectedInfo = map[string]int{
"GET " + url: 0,
// Regexp match generates 2 entries:
"POST " + url2: 0, // the matched call
"POST =~gitlab": 0, // the regexp responder
}
if !reflect.DeepEqual(info, expectedInfo) {
t.Fatalf("did not correctly reset the call count info. expected it to be \n %+v\n but it was \n %+v", expectedInfo, info)
}
// Unregister each responder
RegisterResponder("GET", url, nil)
RegisterResponder("POST", "=~gitlab", nil)
info = GetCallCountInfo()
expectedInfo = map[string]int{
// this one remains as it is not directly related to a registered
// responder but a consequence of a regexp match
"POST " + url2: 0,
}
if !reflect.DeepEqual(info, expectedInfo) {
t.Fatalf("did not correctly reset the call count info. expected it to be \n %+v\n but it was \n %+v", expectedInfo, info)
}
}
func TestRegisterResponderWithQuery(t *testing.T) {
Reset()
// Just in case a panic occurs
defer DeactivateAndReset()
// create a custom http client w/ custom Roundtripper
client := &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: (&net.Dialer{
Timeout: 60 * time.Second,
KeepAlive: 30 * time.Second,
}).Dial,
TLSHandshakeTimeout: 60 * time.Second,
},
}
body := "hello world!"
testURLPath := "http://acme.test/api"
for _, test := range []struct {
URL string
Queries []interface{}
URLs []string
}{
{
Queries: []interface{}{
map[string]string{"a": "1", "b": "2"},
"a=1&b=2",
"b=2&a=1",
url.Values{"a": []string{"1"}, "b": []string{"2"}},
},
URLs: []string{
"http://acme.test/api?a=1&b=2",
"http://acme.test/api?b=2&a=1",
},
},
{
Queries: []interface{}{
url.Values{
"a": []string{"3", "2", "1"},
"b": []string{"4", "2"},
"c": []string{""}, // is the net/url way to record params without values
// Test:
// u, _ := url.Parse("/hello/world?query")
// fmt.Printf("%d<%s>\n", len(u.Query()["query"]), u.Query()["query"][0])
// // prints "1<>"
},
"a=1&b=2&a=3&c&b=4&a=2",
"b=2&a=1&c=&b=4&a=2&a=3",
nil,
},
URLs: []string{
testURLPath + "?a=1&b=2&a=3&c&b=4&a=2",
testURLPath + "?a=1&b=2&a=3&c=&b=4&a=2",
testURLPath + "?b=2&a=1&c=&b=4&a=2&a=3",
testURLPath + "?b=2&a=1&c&b=4&a=2&a=3",
},
},
} {
for _, query := range test.Queries {
ActivateNonDefault(client)
RegisterResponderWithQuery("GET", testURLPath, query, NewStringResponder(200, body))
for _, url := range test.URLs {
t.Logf("query=%v URL=%s", query, url)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
t.Fatal(err)
}
resp, err := client.Do(req)
if err != nil {
t.Fatal(err)
}
assertBody(t, resp, body)
}
if info := GetCallCountInfo(); len(info) != 1 {
t.Fatalf("%s: len(GetCallCountInfo()) should be 1 but contains %+v", testURLPath, info)
}
// Remove...
RegisterResponderWithQuery("GET", testURLPath, query, nil)
if info := GetCallCountInfo(); len(info) != 0 {
t.Fatalf("did not correctly reset the call count info, it still contains %+v", info)
}
for _, url := range test.URLs {
t.Logf("query=%v URL=%s", query, url)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
t.Fatal(err)
}
_, err = client.Do(req)
if err == nil {
t.Fatalf("No error occurred for %s", url)
}
if !strings.HasSuffix(err.Error(), "no responder found") {
t.Errorf("Not expected error suffix: %s", err)
}
}
DeactivateAndReset()
}
}
}
func TestRegisterResponderWithQueryPanic(t *testing.T) {
resp := NewStringResponder(200, "hello world!")
for _, test := range []struct {
Path string
Query interface{}
PanicPrefix string
}{
{
Path: "foobar",
Query: "%",
PanicPrefix: "RegisterResponderWithQuery bad query string: ",
},
{
Path: "foobar",
Query: 1234,
PanicPrefix: "RegisterResponderWithQuery bad query type int. Only url.Values, map[string]string and string are allowed",
},
{
Path: `=~regexp.*\z`,
Query: "",
PanicPrefix: `path begins with "=~", RegisterResponder should be used instead of RegisterResponderWithQuery`,
},
} {
panicked, panicStr := catchPanic(func() {
RegisterResponderWithQuery("GET", test.Path, test.Query, resp)
})
if !panicked {
t.Errorf("RegisterResponderWithQuery + query=%v did not panic", test.Query)
continue
}
if !strings.HasPrefix(panicStr, test.PanicPrefix) {
t.Fatalf(`RegisterResponderWithQuery + query=%v panic="%v" expected prefix="%v"`,
test.Query, panicStr, test.PanicPrefix)
}
}
}
func TestRegisterRegexpResponder(t *testing.T) {
Activate()
defer DeactivateAndReset()
rx := regexp.MustCompile("ex.mple")
RegisterRegexpResponder("GET", rx, NewStringResponder(200, "first"))
// Overwrite responder
RegisterRegexpResponder("GET", rx, NewStringResponder(200, "second"))
resp, err := http.Get(testURL)
if err != nil {
t.Fatalf("expected request %s to succeed", testURL)
}
assertBody(t, resp, "second")
}
func TestSubmatches(t *testing.T) {
req, err := http.NewRequest("GET", "/foo/bar", nil)
if err != nil {
t.Fatal(err)
}
req2 := internal.SetSubmatches(req, []string{"foo", "123", "-123", "12.3"})
t.Run("GetSubmatch", func(t *testing.T) {
_, err := GetSubmatch(req, 1)
if err != ErrSubmatchNotFound {
t.Errorf("Submatch should not be found in req: %v", err)
}
_, err = GetSubmatch(req2, 5)
if err != ErrSubmatchNotFound {
t.Errorf("Submatch #5 should not be found in req2: %v", err)
}
s, err := GetSubmatch(req2, 1)
if err != nil {
t.Errorf("GetSubmatch(req2, 1) failed: %v", err)
}
if s != "foo" {
t.Errorf("GetSubmatch(req2, 1) failed, got: %v, expected: foo", s)
}
s, err = GetSubmatch(req2, 4)
if err != nil {
t.Errorf("GetSubmatch(req2, 4) failed: %v", err)
}
if s != "12.3" {
t.Errorf("GetSubmatch(req2, 4) failed, got: %v, expected: 12.3", s)
}
s = MustGetSubmatch(req2, 4)
if s != "12.3" {
t.Errorf("GetSubmatch(req2, 4) failed, got: %v, expected: 12.3", s)
}
})
t.Run("GetSubmatchAsInt", func(t *testing.T) {
_, err := GetSubmatchAsInt(req, 1)
if err != ErrSubmatchNotFound {
t.Errorf("Submatch should not be found in req: %v", err)
}
_, err = GetSubmatchAsInt(req2, 4) // not an int
if err == nil || err == ErrSubmatchNotFound {
t.Errorf("Submatch should not be an int64: %v", err)
}
i, err := GetSubmatchAsInt(req2, 3)
if err != nil {
t.Errorf("GetSubmatchAsInt(req2, 3) failed: %v", err)
}
if i != -123 {
t.Errorf("GetSubmatchAsInt(req2, 3) failed, got: %d, expected: -123", i)
}
i = MustGetSubmatchAsInt(req2, 3)
if i != -123 {
t.Errorf("MustGetSubmatchAsInt(req2, 3) failed, got: %d, expected: -123", i)
}
})
t.Run("GetSubmatchAsUint", func(t *testing.T) {
_, err := GetSubmatchAsUint(req, 1)
if err != ErrSubmatchNotFound {
t.Errorf("Submatch should not be found in req: %v", err)
}
_, err = GetSubmatchAsUint(req2, 3) // not a uint
if err == nil || err == ErrSubmatchNotFound {
t.Errorf("Submatch should not be an uint64: %v", err)
}
u, err := GetSubmatchAsUint(req2, 2)
if err != nil {
t.Errorf("GetSubmatchAsUint(req2, 2) failed: %v", err)
}
if u != 123 {
t.Errorf("GetSubmatchAsUint(req2, 2) failed, got: %d, expected: 123", u)
}
u = MustGetSubmatchAsUint(req2, 2)
if u != 123 {
t.Errorf("MustGetSubmatchAsUint(req2, 2) failed, got: %d, expected: 123", u)
}
})
t.Run("GetSubmatchAsFloat", func(t *testing.T) {
_, err := GetSubmatchAsFloat(req, 1)
if err != ErrSubmatchNotFound {
t.Errorf("Submatch should not be found in req: %v", err)
}
_, err = GetSubmatchAsFloat(req2, 1) // not a float
if err == nil || err == ErrSubmatchNotFound {
t.Errorf("Submatch should not be an float64: %v", err)
}
f, err := GetSubmatchAsFloat(req2, 4)
if err != nil {
t.Errorf("GetSubmatchAsFloat(req2, 4) failed: %v", err)
}
if f != 12.3 {
t.Errorf("GetSubmatchAsFloat(req2, 4) failed, got: %f, expected: 12.3", f)
}
f = MustGetSubmatchAsFloat(req2, 4)
if f != 12.3 {
t.Errorf("MustGetSubmatchAsFloat(req2, 4) failed, got: %f, expected: 12.3", f)
}
})
t.Run("GetSubmatch* panics", func(t *testing.T) {
for _, test := range []struct {
Name string
Fn func()
PanicPrefix string
}{
{