-
Notifications
You must be signed in to change notification settings - Fork 5
/
client_test.go
646 lines (578 loc) · 16.4 KB
/
client_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
package clink_test
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/davesavic/clink"
)
func TestNewClient(t *testing.T) {
testCases := []struct {
name string
opts []clink.Option
result func(*clink.Client) bool
}{
{
name: "default client with no options",
opts: []clink.Option{},
result: func(client *clink.Client) bool {
return client.HttpClient != nil && client.Headers != nil && len(client.Headers) == 0
},
},
{
name: "client with custom http client",
opts: []clink.Option{
clink.WithClient(nil),
},
result: func(client *clink.Client) bool {
return client.HttpClient == nil
},
},
{
name: "client with custom headers",
opts: []clink.Option{
clink.WithHeaders(map[string]string{"key": "value"}),
},
result: func(client *clink.Client) bool {
return client.Headers != nil && len(client.Headers) == 1
},
},
{
name: "client with custom header",
opts: []clink.Option{
clink.WithHeader("key", "value"),
},
result: func(client *clink.Client) bool {
return client.Headers != nil && len(client.Headers) == 1
},
},
{
name: "client with custom rate limit",
opts: []clink.Option{
clink.WithRateLimit(60),
},
result: func(client *clink.Client) bool {
return client.RateLimiter != nil && client.RateLimiter.Limit() == 1
},
},
{
name: "client with basic auth",
opts: []clink.Option{
clink.WithBasicAuth("username", "password"),
},
result: func(client *clink.Client) bool {
b64, err := base64.StdEncoding.DecodeString(
strings.Replace(client.Headers["Authorization"], "Basic ", "", 1),
)
if err != nil {
return false
}
return string(b64) == "username:password"
},
},
{
name: "client with bearer token",
opts: []clink.Option{
clink.WithBearerAuth("token"),
},
result: func(client *clink.Client) bool {
return client.Headers["Authorization"] == "Bearer token"
},
},
{
name: "client with user agent",
opts: []clink.Option{
clink.WithUserAgent("user-agent"),
},
result: func(client *clink.Client) bool {
return client.Headers["User-Agent"] == "user-agent"
},
},
{
name: "client with retries",
opts: []clink.Option{
clink.WithRetries(3, func(request *http.Request, response *http.Response, err error) bool {
return true
}),
},
result: func(client *clink.Client) bool {
return client.MaxRetries == 3 && client.ShouldRetryFunc != nil
},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
c := clink.NewClient(tc.opts...)
if c == nil {
t.Error("expected client to be created")
}
if !tc.result(c) {
t.Errorf("expected client to be created with options: %+v", tc.opts)
}
})
}
}
func TestClient_Do(t *testing.T) {
testCases := []struct {
name string
opts []clink.Option
setupServer func() *httptest.Server
resultFunc func(*http.Response, error) bool
}{
{
name: "successful response no body",
opts: []clink.Option{},
setupServer: func() *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))
},
resultFunc: func(response *http.Response, err error) bool {
return response != nil && err == nil && response.StatusCode == http.StatusOK
},
},
{
name: "successful response with text body",
opts: []clink.Option{},
setupServer: func() *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("response"))
}))
},
resultFunc: func(response *http.Response, err error) bool {
bodyContents, err := io.ReadAll(response.Body)
if err != nil {
return false
}
return string(bodyContents) == "response"
},
},
{
name: "successful response with json body",
opts: []clink.Option{},
setupServer: func() *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = json.NewEncoder(w).Encode(map[string]string{"key": "value"})
}))
},
resultFunc: func(response *http.Response, err error) bool {
var target map[string]string
er := clink.ResponseToJson(response, &target)
if er != nil {
return false
}
return target["key"] == "value"
},
},
{
name: "successful response with json body and custom headers",
opts: []clink.Option{
clink.WithHeaders(map[string]string{"key": "value"}),
},
setupServer: func() *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("key") != "value" {
w.WriteHeader(http.StatusBadRequest)
}
_ = json.NewEncoder(w).Encode(map[string]string{"key": "value"})
}))
},
resultFunc: func(response *http.Response, err error) bool {
var target map[string]string
er := clink.ResponseToJson(response, &target)
if er != nil {
return false
}
return target["key"] == "value"
},
},
{
name: "successful response with json body and custom header",
opts: []clink.Option{
clink.WithHeader("key", "value"),
},
setupServer: func() *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("key") != "value" {
w.WriteHeader(http.StatusBadRequest)
}
_ = json.NewEncoder(w).Encode(map[string]string{"key": "value"})
}))
},
resultFunc: func(response *http.Response, err error) bool {
var target map[string]string
er := clink.ResponseToJson(response, &target)
if er != nil {
return false
}
return target["key"] == "value"
},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
server := tc.setupServer()
defer server.Close()
opts := append(tc.opts, clink.WithClient(server.Client()))
c := clink.NewClient(opts...)
if c == nil {
t.Error("expected client to be created")
}
req, err := http.NewRequest(http.MethodGet, server.URL, nil)
if err != nil {
t.Errorf("failed to create request: %v", err)
}
resp, err := c.Do(req)
if !tc.resultFunc(resp, err) {
t.Errorf("expected result to be successful")
}
})
}
}
func TestClient_Methods(t *testing.T) {
serverFunc := func() *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("X-Method", r.Method)
}))
}
resultFunc := func(r *http.Response, m string) bool {
return r.Header.Get("X-Method") == m
}
testCases := []struct {
name string
method string
body io.Reader
setupServer func() *httptest.Server
resultFunc func(*http.Response, string) bool
}{
{
name: "successful head response",
method: http.MethodHead,
setupServer: serverFunc,
resultFunc: resultFunc,
},
{
name: "successful options response",
method: http.MethodOptions,
setupServer: serverFunc,
resultFunc: resultFunc,
},
{
name: "successful get response",
method: http.MethodGet,
setupServer: serverFunc,
resultFunc: resultFunc,
},
{
name: "successful post response",
method: http.MethodPost,
setupServer: serverFunc,
resultFunc: resultFunc,
},
{
name: "successful put response",
method: http.MethodPut,
setupServer: serverFunc,
resultFunc: resultFunc,
},
{
name: "successful patch response",
method: http.MethodPatch,
setupServer: serverFunc,
resultFunc: resultFunc,
},
{
name: "successful delete response",
method: http.MethodDelete,
setupServer: serverFunc,
resultFunc: resultFunc,
},
}
call := func(c *clink.Client, method, url string, body io.Reader) (*http.Response, error) {
switch method {
case http.MethodHead:
return c.Head(url)
case http.MethodOptions:
return c.Options(url)
case http.MethodGet:
return c.Get(url)
case http.MethodPost:
return c.Post(url, body)
case http.MethodPut:
return c.Put(url, body)
case http.MethodPatch:
return c.Patch(url, body)
case http.MethodDelete:
return c.Delete(url)
}
return nil, nil
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
server := tc.setupServer()
defer server.Close()
c := clink.NewClient(clink.WithClient(server.Client()))
if c == nil {
t.Error("expected client to be created")
}
resp, _ := call(c, tc.method, server.URL, tc.body)
if !tc.resultFunc(resp, tc.method) {
t.Errorf("expected result to be successful")
}
})
}
}
func TestClient_ResponseToJson(t *testing.T) {
testCases := []struct {
name string
response *http.Response
target any
resultFunc func(*http.Response, any) bool
}{
{
name: "successful response with json body",
response: &http.Response{
Body: io.NopCloser(strings.NewReader(`{"key": "value"}`)),
},
resultFunc: func(response *http.Response, target any) bool {
var t map[string]string
er := clink.ResponseToJson(response, &t)
if er != nil {
return false
}
return t["key"] == "value"
},
},
{
name: "response is nil",
response: nil,
resultFunc: func(response *http.Response, target any) bool {
var t map[string]string
er := clink.ResponseToJson(response, &t)
if er == nil {
return false
}
return er.Error() == "response is nil"
},
},
{
name: "response body is nil",
response: &http.Response{
Body: nil,
},
resultFunc: func(response *http.Response, target any) bool {
var t map[string]string
er := clink.ResponseToJson(response, &t)
if er == nil {
return false
}
return er.Error() == "response body is nil"
},
},
{
name: "json decode error",
response: &http.Response{
Body: io.NopCloser(strings.NewReader(`{"key": "value`)),
},
target: nil,
resultFunc: func(response *http.Response, target any) bool {
var t map[string]string
er := clink.ResponseToJson(response, &t)
if er == nil {
return false
}
return strings.Contains(er.Error(), "failed to decode response")
},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
if !tc.resultFunc(tc.response, tc.target) {
t.Errorf("expected result to be successful")
}
})
}
}
func TestRateLimiter(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
client := clink.NewClient(
clink.WithRateLimit(60),
clink.WithClient(server.Client()),
)
startTime := time.Now()
for i := 0; i < 2; i++ {
req, err := http.NewRequest(http.MethodGet, server.URL, nil)
if err != nil {
t.Errorf("failed to create request: %v", err)
}
resp, err := client.Do(req)
if err != nil {
t.Errorf("failed to make request: %v", err)
}
if resp.StatusCode != http.StatusOK {
t.Errorf("expected status code to be 200")
}
}
elapsedTime := time.Since(startTime)
if elapsedTime.Seconds() < 0.5 || elapsedTime.Seconds() > 1.5 {
t.Errorf("expected elapsed time to be between 0.5 and 1.5 seconds, got: %f", elapsedTime.Seconds())
}
}
func TestSuccessfulRetries(t *testing.T) {
var requestCount int
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestCount++ // Increment the request count
w.WriteHeader(http.StatusInternalServerError)
}))
defer server.Close()
retryCount := 3
client := clink.NewClient(
clink.WithRetries(retryCount, func(request *http.Request, response *http.Response, err error) bool {
// Check if the response is a 500 Internal Server Error
return response != nil && response.StatusCode == http.StatusInternalServerError
}),
clink.WithClient(server.Client()),
)
req, err := http.NewRequest(http.MethodGet, server.URL, nil)
if err != nil {
t.Fatalf("failed to create request: %v", err)
}
_, err = client.Do(req)
if err != nil {
t.Fatalf("failed to make request: %v", err)
}
if requestCount != retryCount+1 { // +1 for the initial request
t.Errorf("expected %d retries (total requests: %d), but got %d", retryCount, retryCount+1, requestCount)
}
}
func TestUnsuccessfulRetries(t *testing.T) {
var requestCount int
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestCount++ // Increment the request count
w.WriteHeader(http.StatusInternalServerError)
}))
defer server.Close()
retryCount := 3
client := clink.NewClient(
clink.WithRetries(retryCount, func(request *http.Request, response *http.Response, err error) bool {
return false
}),
clink.WithClient(server.Client()),
)
req, err := http.NewRequest(http.MethodGet, server.URL, nil)
if err != nil {
t.Fatalf("failed to create request: %v", err)
}
_, err = client.Do(req)
if requestCount != 1 { // +1 for the initial request
t.Errorf("expected %d retries (total requests: %d), but got %d", retryCount, retryCount+1, requestCount)
}
}
// TestRequestBodyEmptyOnRetries tests that the request body on a custom io.Reader wrapper is NOT empty on retries.
type oneTimeReaderWrapper struct {
data []byte
consumed bool
}
func (r *oneTimeReaderWrapper) Read(p []byte) (n int, err error) {
if r.consumed {
return 0, fmt.Errorf("body already read")
}
n = copy(p, r.data)
r.consumed = true
return n, io.EOF
}
func TestRequestBodyNotEmptyOnRetries(t *testing.T) {
var requestCount int
var lastRequestBody string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestCount++
bodyBytes, err := io.ReadAll(r.Body)
if err != nil {
t.Fatalf("failed to read request body: %v", err)
}
lastRequestBody = string(bodyBytes)
w.WriteHeader(http.StatusInternalServerError)
}))
defer server.Close()
client := clink.NewClient(
clink.WithRetries(1, func(request *http.Request, response *http.Response, err error) bool {
return true
}),
clink.WithClient(server.Client()),
)
requestBody := []byte("test body")
req, err := http.NewRequest(http.MethodPost, server.URL, &oneTimeReaderWrapper{data: requestBody})
if err != nil {
t.Fatalf("failed to create request: %v", err)
}
_, err = client.Do(req)
if err != nil {
t.Fatalf("failed to make request: %v", err)
}
if requestCount != 2 {
t.Fatalf("expected 2 requests due to retry, but got %d", requestCount)
}
expectedBody := string(requestBody)
if lastRequestBody != expectedBody {
t.Errorf("expected request body to be '%s' on retry, got '%s'", expectedBody, lastRequestBody)
}
}
func TestContextCancellationDuringRetries(t *testing.T) {
var requestCount int
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestCount++
w.WriteHeader(http.StatusInternalServerError) // Always return an error to trigger retries
}))
defer server.Close()
client := clink.NewClient(
clink.WithRetries(3, func(request *http.Request, response *http.Response, err error) bool {
// Always return true to retry
return true
}),
clink.WithClient(server.Client()),
)
ctx, cancel := context.WithCancel(context.Background())
req, err := http.NewRequestWithContext(ctx, http.MethodGet, server.URL, nil)
if err != nil {
t.Fatalf("failed to create request: %v", err)
}
go func() {
time.Sleep(100 * time.Millisecond)
cancel()
}()
_, err = client.Do(req)
if requestCount > 2 {
t.Errorf("expected at most 2 requests due to context cancellation, but got %d", requestCount)
}
if err == nil || !errors.Is(err, context.Canceled) {
t.Errorf("expected context cancellation error, but got: %v", err)
}
}
func TestRequestWithCanceledContext(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(2 * time.Second) // Simulate a delay in the response
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
client := clink.NewClient(clink.WithClient(server.Client()))
ctx, cancel := context.WithCancel(context.Background())
req, err := http.NewRequestWithContext(ctx, http.MethodGet, server.URL, nil)
if err != nil {
t.Fatalf("failed to create request: %v", err)
}
cancel() // Cancel the context immediately
_, err = client.Do(req)
if err == nil || !errors.Is(err, context.Canceled) {
t.Errorf("expected context cancellation error, but got: %v", err)
}
}