-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathclient_test.go
More file actions
868 lines (822 loc) · 21.7 KB
/
Copy pathclient_test.go
File metadata and controls
868 lines (822 loc) · 21.7 KB
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
package client
import (
"bytes"
"context"
"crypto/tls"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"strconv"
"strings"
"testing"
"time"
"unsafe"
"git.sr.ht/~mariusor/cache"
"git.sr.ht/~mariusor/lw"
"github.com/carlmjohnson/requests"
vocab "github.com/go-ap/activitypub"
"github.com/go-ap/client/c2s"
"github.com/go-ap/client/debug"
"github.com/go-ap/client/s2s"
"github.com/go-ap/errors"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"golang.org/x/oauth2"
)
func TestClient_LoadIRI1(t *testing.T) {
empty := vocab.IRI("")
c := New()
var err error
_, err = c.LoadIRI(empty)
if err == nil {
t.Errorf("LoadIRI should have failed when using empty IRI value")
}
inv := vocab.IRI("example.com")
_, err = c.LoadIRI(inv)
if err == nil {
t.Errorf("LoadIRI should have failed when using invalid http url")
} else {
t.Logf("Valid error received: %s", err)
}
}
func Test_getTransportWithTLSValidation(t *testing.T) {
type args struct {
rt http.RoundTripper
skip bool
}
tests := []struct {
name string
args args
want http.RoundTripper
}{
{
name: "empty",
args: args{},
want: defaultTransport,
},
{
name: "cache, skip false",
args: args{rt: &cache.Transport{Base: defaultTransport}, skip: false},
want: &cache.Transport{Base: defaultTransport},
},
{
name: "cache, skip true",
args: args{rt: &cache.Transport{Base: defaultTransport}, skip: true},
// NOTE(marius): this is defaultTransport with InsecureSkipVerify set to true
want: &cache.Transport{Base: &http.Transport{
Proxy: http.ProxyFromEnvironment,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
MaxIdleConnsPerHost: 20,
DialContext: (&net.Dialer{Timeout: longTimeout}).DialContext,
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
TLSHandshakeTimeout: longTimeout,
},
},
},
{
name: "empty oauth2, skip false",
args: args{rt: &oauth2.Transport{}, skip: false},
want: &oauth2.Transport{Base: defaultTransport},
},
{
name: "empty oauth2, skip true",
args: args{rt: &oauth2.Transport{}, skip: true},
// NOTE(marius): this is defaultTransport with InsecureSkipVerify set to true
want: &oauth2.Transport{
Base: &http.Transport{
Proxy: http.ProxyFromEnvironment,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
MaxIdleConnsPerHost: 20,
DialContext: (&net.Dialer{Timeout: longTimeout}).DialContext,
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
TLSHandshakeTimeout: longTimeout,
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := getTransportWithTLSValidation(tt.args.rt, tt.args.skip)
if !cmp.Equal(got, tt.want, ignoredTransports, equateFuncs) {
t.Errorf("getTransportWithTLSValidation() = %s", cmp.Diff(tt.want, got, ignoredTransports, equateFuncs))
}
})
}
}
var ignoredTransports = cmpopts.IgnoreUnexported(http.Transport{}, tls.Config{}, cache.Transport{}, s2s.Signer{})
func TestSkipTLSValidation(t *testing.T) {
tests := []struct {
name string
skip bool
tr http.RoundTripper
wantErr error
}{
{
name: "false empty transport",
skip: false,
},
{
name: "true empty transport",
skip: true,
},
{
name: "false http.Transport",
tr: &http.Transport{},
skip: false,
},
{
name: "true http.Transport",
tr: &http.Transport{},
skip: true,
},
{
name: "false debug.Transport",
tr: &debug.Transport{},
skip: false,
},
{
name: "true debug.Transport",
tr: &debug.Transport{},
skip: true,
},
{
name: "false cache.Transport",
tr: &cache.Transport{},
skip: false,
},
{
name: "true cache.Transport",
tr: &cache.Transport{},
skip: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cl := new(C)
cl.c = &http.Client{Transport: tt.tr}
SkipTLSValidation(tt.skip)(cl)
switch tr := cl.c.(*http.Client).Transport.(type) {
case *http.Transport:
if tr.TLSClientConfig.InsecureSkipVerify != tt.skip {
t.Errorf("SkipTLSValidation() got skip validation %t, wanted %t", tt.skip, tr.TLSClientConfig.InsecureSkipVerify)
}
}
})
}
}
func areErrors(a, b any) bool {
_, ok1 := a.(error)
_, ok2 := b.(error)
return ok1 && ok2
}
func compareErrorsWithUrl(url string) func(x, y any) bool {
return func(x, y any) bool {
xe := x.(error)
ye := y.(error)
if errors.Is(xe, ye) || errors.Is(ye, xe) {
return true
}
xs := strings.ReplaceAll(xe.Error(), "http://example.com", url)
ys := strings.ReplaceAll(ye.Error(), "http://example.com", url)
return xs == ys
}
}
var EquateWeakErrors = func(url string) cmp.Option {
return cmp.FilterValues(areErrors, cmp.Comparer(compareErrorsWithUrl(url)))
}
func areFuncs(a, b any) bool {
ta := reflect.TypeOf(a)
tb := reflect.TypeOf(b)
return ta != nil && ta.Kind() == reflect.Func && tb != nil && tb.Kind() == reflect.Func
}
func compareFuncs(x, y any) bool {
px := *(*unsafe.Pointer)(unsafe.Pointer(&x))
py := *(*unsafe.Pointer)(unsafe.Pointer(&y))
return px == py
}
var equateFuncs = cmp.FilterValues(areFuncs, cmp.Comparer(compareFuncs))
func TestWithLogger(t *testing.T) {
tests := []struct {
name string
l lw.Logger
wantErr error
}{
{
name: "empty",
l: nil,
wantErr: nil,
},
{
name: "nil logger",
l: lw.Nil(),
wantErr: nil,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cl := new(C)
WithLogger(tt.l)(cl)
if !cmp.Equal(cl.l, tt.l) {
t.Errorf("WithLogger() = %s", cmp.Diff(tt.l, cl.l))
}
})
}
}
func TestWithHTTPClient(t *testing.T) {
tests := []struct {
name string
h *http.Client
wantErr error
}{
{
name: "empty",
h: nil,
wantErr: nil,
},
{
name: "default client",
h: defaultClient,
wantErr: nil,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cl := new(C)
WithHTTPClient(tt.h)(cl)
if !cmp.Equal(cl.c, tt.h, ignoredTransports, equateFuncs) {
t.Errorf("WithHTTPClient() = %s", cmp.Diff(tt.h, cl.c, ignoredTransports, equateFuncs))
}
})
}
}
var emptyAuthFn = func(r *http.Request) error {
return nil
}
func TestWithAuthorizationFn(t *testing.T) {
tests := []struct {
name string
args []func(*http.Request) error
want []func(*http.Request) error
wantErr error
}{
{
name: "empty",
wantErr: fmt.Errorf("nil sign function"),
},
{
name: "empty fn",
args: []func(*http.Request) error{emptyAuthFn},
want: []func(*http.Request) error{emptyAuthFn},
},
{
name: "RFC9421 Sign Fn",
args: []func(*http.Request) error{new(s2s.Signer).SignRFC9421},
want: []func(*http.Request) error{new(s2s.Signer).SignRFC9421},
},
{
name: "Draft Sign Fn",
args: []func(*http.Request) error{new(s2s.Signer).SignDraft},
want: []func(*http.Request) error{new(s2s.Signer).SignDraft},
},
{
name: "RFC9421+Draft Sign Fns",
args: []func(*http.Request) error{new(s2s.Signer).SignRFC9421, new(s2s.Signer).SignDraft},
want: []func(*http.Request) error{new(s2s.Signer).SignRFC9421, new(s2s.Signer).SignDraft},
},
{
name: "C2S Sign Fn",
args: []func(*http.Request) error{(*c2s.BearerSigner)(&oauth2.Token{AccessToken: "t", TokenType: "B"}).Sign},
want: []func(*http.Request) error{(*c2s.BearerSigner)(&oauth2.Token{AccessToken: "t", TokenType: "B"}).Sign},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cl := new(C)
WithAuthorizationFn(tt.args...)(cl)
if !cmp.Equal(cl.authFns, tt.want, equateFuncs) {
t.Errorf("WithAuthorizationFn() = %s", cmp.Diff(tt.want, cl.authFns, equateFuncs))
}
})
}
}
func TestWithUserAgent(t *testing.T) {
tests := []struct {
name string
ua string
want string
wantErr error
}{
{
name: "empty",
ua: "",
want: UserAgent,
},
{
name: "random UA",
ua: "//RANDOM UA//",
want: "//RANDOM UA//",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cl := new(C)
WithUserAgent(tt.ua)(cl)
if !cmp.Equal(cl.ua, tt.ua) {
t.Errorf("WithUserAgent() = %s", cmp.Diff(tt.ua, cl.ua))
}
})
}
}
func TestHTTPClient(t *testing.T) {
tests := []struct {
name string
client *C
want *http.Client
}{
{
name: "empty",
want: nil,
},
{
name: "with http.Client",
client: &C{c: &http.Client{Timeout: 666 * time.Second}},
want: &http.Client{Timeout: 666 * time.Second},
},
{
name: "with C client",
client: &C{c: &C{c: &http.Client{Timeout: 66 * time.Second}}},
want: &http.Client{Timeout: 66 * time.Second},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := HTTPClient(tt.client); !cmp.Equal(got, tt.want, ignoredTransports, equateFuncs) {
t.Errorf("HTTPClient() = %s", cmp.Diff(tt.want, got, ignoredTransports, equateFuncs))
}
})
}
}
func TestC_ToCollection(t *testing.T) {
type args struct {
toSend vocab.Item
colPaths vocab.CollectionPaths
}
tests := []struct {
name string
args args
wantIRI vocab.IRI
wantIt vocab.Item
wantErr error
}{
{
name: "empty",
args: args{},
wantIRI: "",
wantIt: nil,
},
{
name: "no collection IRIs",
args: args{toSend: &vocab.Actor{}},
},
{
name: "activity type",
args: args{toSend: &vocab.Activity{}, colPaths: vocab.CollectionPaths{vocab.Inbox}},
},
{
name: "activity type with multiple paths",
args: args{toSend: &vocab.Activity{}, colPaths: vocab.CollectionPaths{vocab.Inbox, vocab.Outbox}},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
raw, _ := vocab.MarshalJSON(tt.wantIt)
w.WriteHeader(http.StatusOK)
_, _ = w.Write(raw)
}))
defer srv.Close()
name := "jdoe"
toCollections := make(vocab.IRIs, 0, len(tt.args.colPaths))
actor := mockActor("http://example.com", name)
_ = vocab.OnIntransitiveActivity(tt.args.toSend, func(act *vocab.IntransitiveActivity) error {
act.Actor = actor
return nil
})
for _, col := range tt.args.colPaths {
toCollections = append(toCollections, col.IRI(actor))
}
c := C{
c: srv.Client(),
l: lw.Dev(lw.SetOutput(t.Output())),
}
gotIRI, gotIt, err := c.ToCollection(tt.args.toSend, toCollections...)
if !cmp.Equal(err, tt.wantErr, EquateWeakErrors("")) {
t.Errorf("ToCollection() error = %s", cmp.Diff(tt.wantErr, err, EquateWeakErrors("")))
return
}
if gotIRI != tt.wantIRI {
t.Errorf("ToCollection() got IRI = %v, want %v", gotIRI, tt.wantIRI)
}
if !cmp.Equal(gotIt, tt.wantIt, EquateItems) {
t.Errorf("ToCollection() got Item = %s", cmp.Diff(tt.wantIt, gotIt, EquateItems))
}
})
}
}
func TestC_toCollection(t *testing.T) {
type args struct {
ctx context.Context
act vocab.Item
colPath vocab.CollectionPath
}
tests := []struct {
name string
handlerFn http.HandlerFunc
args args
wantIRI vocab.IRI
wantIt vocab.Item
wantErr error
}{
{
name: "empty",
wantErr: errors.Newf("invalid IRI to POST to"),
},
{
name: "nil response",
args: args{
ctx: context.Background(),
act: mockActivity(),
colPath: vocab.Outbox,
},
handlerFn: func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
},
wantIRI: "",
wantIt: nil,
wantErr: nil,
},
{
name: "nil response with Location",
args: args{
ctx: context.Background(),
act: mockActivity(),
colPath: vocab.Outbox,
},
handlerFn: func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Location", "http://example.com/1")
w.WriteHeader(http.StatusOK)
},
wantIRI: "http://example.com/1",
wantIt: nil,
wantErr: nil,
},
{
name: "response with Location",
args: args{
ctx: context.Background(),
act: mockActivity(),
colPath: vocab.Outbox,
},
handlerFn: func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Location", "http://example.com/666")
w.WriteHeader(http.StatusOK)
raw, _ := vocab.MarshalJSON(vocab.Object{ID: "http://example.com/note-1", Type: vocab.NoteType})
_, _ = w.Write(raw)
},
wantIRI: "http://example.com/666",
wantIt: &vocab.Object{ID: "http://example.com/note-1", Type: vocab.NoteType},
wantErr: nil,
},
{
name: "404 response",
args: args{
ctx: context.Background(),
act: mockActivity(),
colPath: vocab.Outbox,
},
handlerFn: errors.HandleError(errors.NotFoundf("test")).ServeHTTP,
wantErr: errors.Annotatef(errors.NotFoundf("test"), "invalid status received: 404"),
},
{
name: "401 response",
args: args{
ctx: context.Background(),
act: mockActivity(),
colPath: vocab.Outbox,
},
handlerFn: errors.HandleError(errors.Unauthorizedf("STOP")).ServeHTTP,
wantErr: errors.Annotatef(errors.Unauthorizedf("STOP"), "invalid status received: 401"),
},
{
name: "500 response",
args: args{
ctx: context.Background(),
act: mockActivity(),
colPath: vocab.Outbox,
},
handlerFn: errors.HandleError(errors.Errorf("¡OOPS!")).ServeHTTP,
wantErr: errors.Errorf("invalid status received: 500: ¡OOPS!"),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := C{
l: lw.Dev(lw.SetOutput(t.Output())),
}
var colIRI vocab.IRI
if tt.args.colPath != "" {
srv := httptest.NewServer(tt.handlerFn)
defer srv.Close()
colIRI = tt.args.colPath.IRI(tt.args.act)
c.c = srv.Client()
}
gotIRI, gotIt, err := c.toCollection(tt.args.ctx, tt.args.act, colIRI)
if !cmp.Equal(err, tt.wantErr, EquateWeakErrors("")) {
t.Errorf("toCollection() error = %s", cmp.Diff(tt.wantErr, err, EquateWeakErrors("")))
return
}
if gotIRI != tt.wantIRI {
t.Errorf("toCollection() got IRI = %s, want %s", gotIRI, tt.wantIRI)
}
if !cmp.Equal(gotIt, tt.wantIt, EquateItems) {
t.Errorf("toCollection() got item = %s", cmp.Diff(tt.wantIt, gotIt, EquateItems))
}
})
}
}
func TestC_LoadIRI(t *testing.T) {
tests := []struct {
name string
handlerFn http.HandlerFunc
id vocab.IRI
want vocab.Item
wantErr cerr
}{
{
name: "empty",
wantErr: errf("invalid nil IRI"),
},
{
name: "invalid IRI",
id: ":",
wantErr: errf("trying to load an invalid IRI").iri(":").annotate(errors.Newf("parse \":\": missing protocol scheme")),
},
{
name: "no valid handler",
id: "http://example.com",
wantErr: errf("invalid status received").status(http.StatusGatewayTimeout),
},
{
name: "404 response",
handlerFn: func(w http.ResponseWriter, r *http.Request) {
errors.HandleError(errors.NotFoundf("NOT FOUND")).ServeHTTP(w, r)
},
id: "http://example.com",
wantErr: errf("invalid status received").status(http.StatusNotFound).annotate(errors.NotFoundf("NOT FOUND")),
},
{
name: "empty body",
handlerFn: func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
},
id: "http://example.com",
wantErr: errf("invalid response from ActivityPub server").annotate(errors.NotImplementedf("not a document and not an error")),
},
{
name: "invalid json body",
handlerFn: func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{`))
},
id: "http://example.com",
wantErr: errf("invalid ActivityPub object returned").iri("http://example.com").annotate(errors.Newf("cannot parse JSON: cannot parse object: missing '}'; unparsed tail: \"\"")),
},
{
name: "empty body but Gone",
handlerFn: func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusGone)
},
id: "http://example.com",
wantErr: errf("").annotate(errors.Gonef("gone")).iri("http://example.com"),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.handlerFn == nil {
tt.handlerFn = func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusGatewayTimeout)
}
}
srv := httptest.NewServer(tt.handlerFn)
defer srv.Close()
c := C{
c: srv.Client(),
l: lw.Dev(lw.SetOutput(t.Output())),
}
if tt.id != "" {
u, err := url.Parse(string(tt.id))
if err == nil {
su, _ := url.Parse(srv.URL)
u.Host = su.Host
if tt.wantErr.msg != "" || tt.wantErr.err != nil {
tt.wantErr.i = vocab.IRI(u.String())
}
}
}
got, err := c.LoadIRI(tt.id)
if !cmp.Equal(err, tt.wantErr, EquateWeakErrors(srv.URL)) {
t.Errorf("LoadIRI() error = %s", cmp.Diff(tt.wantErr, err, EquateWeakErrors(srv.URL)))
return
}
if !cmp.Equal(got, tt.want) {
t.Errorf("LoadIRI() got = %s", cmp.Diff(tt.want, got))
}
})
}
}
func mockPostReq(body []byte, hh ...url.Values) *http.Request {
r := httptest.NewRequest(http.MethodPost, "http://example.com", bytes.NewReader(body))
for _, h := range hh {
for k, v := range h {
r.Header[k] = v
}
}
r.Header.Add("Content-Length", strconv.Itoa(len(body)))
r.RequestURI = ""
return r
}
func mockGetReq(hh ...url.Values) *http.Request {
r := requests.URL("http://example.com")
r.Header("Date", TimeNow().Format(http.TimeFormat))
for _, h := range hh {
for k, v := range h {
r.Header(k, v...)
}
}
req, _ := r.Request(context.Background())
return req
}
func TestC_Do(t *testing.T) {
TimeNow = mockTimeFn
type fields struct {
ua string
authFns []func(*http.Request) error
}
tests := []struct {
name string
fields fields
req *http.Request
handler http.Handler
want *http.Response
wantErr error
}{
{
name: "empty",
fields: fields{},
req: mockGetReq(),
want: &http.Response{
Status: "404 Not Found",
StatusCode: http.StatusNotFound,
Header: http.Header{
"Content-Length": []string{"19"},
"Content-Type": []string{"text/plain; charset=utf-8"},
},
ContentLength: 19,
Body: io.NopCloser(bytes.NewBufferString("404 page not found\n")),
},
},
{
name: "with UA",
fields: fields{ua: "test-ua"},
req: mockGetReq(),
handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if ua := r.Header.Get("User-Agent"); ua != "test-ua" {
t.Errorf("Invalid user-agent %s, wanted %s", ua, "test-ua")
}
w.WriteHeader(http.StatusOK)
}),
want: &http.Response{
Status: "200 OK",
StatusCode: http.StatusOK,
Header: http.Header{"Content-Length": []string{"0"}},
},
},
{
name: "Post with UA",
fields: fields{ua: "test-ua"},
req: mockPostReq([]byte("{}")),
handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if ua := r.Header.Get("User-Agent"); ua != "test-ua" {
t.Errorf("Invalid user-agent %s, wanted %s", ua, "test-ua")
}
if r.Method != http.MethodPost {
t.Errorf("Invalid request method %s, wanted %s", r.Method, http.MethodPost)
}
w.WriteHeader(http.StatusOK)
}),
want: &http.Response{
Status: "200 OK",
StatusCode: http.StatusOK,
Header: http.Header{"Content-Length": []string{"0"}},
},
},
{
name: "with random authorization function",
fields: fields{authFns: []func(*http.Request) error{
func(r *http.Request) error {
r.Header.Add("Authorization", "test")
return nil
},
}},
req: mockGetReq(),
handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if auth := r.Header.Get("Authorization"); auth != "test" {
t.Errorf("Invalid Authorization header %s, wanted %s", auth, "test")
}
w.WriteHeader(http.StatusOK)
}),
want: &http.Response{
Status: "200 OK",
StatusCode: http.StatusOK,
Header: http.Header{"Content-Length": []string{"0"}},
},
},
{
name: "Post with random authorization function",
fields: fields{authFns: []func(*http.Request) error{
func(r *http.Request) error {
r.Header.Add("Authorization", "test")
return nil
},
}},
req: mockPostReq([]byte("{}")),
handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
t.Errorf("Invalid request method %s, wanted %s", r.Method, http.MethodPost)
}
w.WriteHeader(http.StatusOK)
}),
want: &http.Response{
Status: "200 OK",
StatusCode: http.StatusOK,
Header: http.Header{"Content-Length": []string{"0"}},
},
},
{
name: "Post receives 403/200",
fields: fields{authFns: []func(*http.Request) error{
func(r *http.Request) error {
r.Header.Add("Authorization", "test")
return nil
},
func(r *http.Request) error {
r.Header.Add("Authorization", "test1")
return nil
},
}},
req: mockPostReq([]byte("{}")),
handler: func() http.HandlerFunc {
cnt := 0
return func(w http.ResponseWriter, r *http.Request) {
status := http.StatusUnauthorized
if cnt > 0 {
status = http.StatusOK
}
w.WriteHeader(status)
}
}(),
want: &http.Response{
Status: "200 OK",
StatusCode: http.StatusOK,
Header: http.Header{"Content-Length": []string{"0"}},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
srv := httptest.NewServer(tt.handler)
cl := srv.Client()
c := C{
c: cl,
l: lw.Nil(),
ua: tt.fields.ua,
authFns: tt.fields.authFns,
}
got, err := c.Do(tt.req)
if !cmp.Equal(err, tt.wantErr, EquateWeakErrors(srv.URL)) {
t.Errorf("Do() error = %s", cmp.Diff(tt.wantErr, err, EquateWeakErrors(srv.URL)))
return
}
tt.want.Request = tt.req
if !cmp.Equal(got, tt.want, EquateResponses) {
t.Errorf("Do() got = %s", cmp.Diff(tt.want, got, EquateResponses))
}
})
}
}