-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient_test.go
879 lines (720 loc) · 26.7 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
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
package requests
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"net"
"net/http"
"net/http/cookiejar"
"net/http/httptest"
"os"
"testing"
"time"
"github.com/bytedance/sonic"
"github.com/goccy/go-yaml"
"github.com/stretchr/testify/assert"
"github.com/test-go/testify/require"
)
// startTestHTTPServer starts a test HTTP server that responds to various endpoints for testing purposes.
func startTestHTTPServer() *httptest.Server {
handler := http.NewServeMux()
handler.HandleFunc("/test-get", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "GET response")
})
handler.HandleFunc("/test-post", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "POST response")
})
handler.HandleFunc("/test-put", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "PUT response")
})
handler.HandleFunc("/test-delete", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "DELETE response")
})
handler.HandleFunc("/test-patch", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "PATCH response")
})
handler.HandleFunc("/test-status-code", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusCreated) // 201
fmt.Fprintln(w, `Created`)
})
handler.HandleFunc("/test-headers", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Custom-Header", "TestValue")
fmt.Fprintln(w, `Headers test`)
})
handler.HandleFunc("/test-cookies", func(w http.ResponseWriter, r *http.Request) {
http.SetCookie(w, &http.Cookie{Name: "test-cookie", Value: "cookie-value"})
fmt.Fprintln(w, `Cookies test`)
})
handler.HandleFunc("/test-body", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "This is the response body.")
})
handler.HandleFunc("/test-empty", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK) // Send a 200 OK status
// Don't write any body to ensure it's empty
})
handler.HandleFunc("/test-json", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
fmt.Fprintln(w, `{"message": "This is a JSON response", "status": true}`)
})
handler.HandleFunc("/test-xml", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/xml")
fmt.Fprintln(w, `<Response><Message>This is an XML response</Message><Status>true</Status></Response>`)
})
handler.HandleFunc("/test-text", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
fmt.Fprintln(w, `This is a text response`)
})
handler.HandleFunc("/test-pdf", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/pdf")
fmt.Fprintln(w, `This is a PDF response`)
})
handler.HandleFunc("/test-redirect", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/test-redirected", http.StatusFound)
})
handler.HandleFunc("/test-redirected", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Redirected")
})
handler.HandleFunc("/test-failure", func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
})
return httptest.NewServer(handler)
}
// testRoundTripperFunc type is an adapter to allow the use of ordinary functions as http.RoundTrippers.
type testRoundTripperFunc func(*http.Request) (*http.Response, error)
// RoundTrip executes a single HTTP transaction.
func (f testRoundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req)
}
// TestSetHTTPClient verifies that SetHTTPClient correctly sets a custom http.Client
// and uses it for subsequent requests, specifically checking for cookie modifications.
func TestSetHTTPClient(t *testing.T) {
// Create a mock server that inspects incoming requests for a specific cookie.
mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check for the presence of a specific cookie.
cookie, err := r.Cookie("X-Custom-Test-Cookie")
if err != nil || cookie.Value != "true" {
// If the cookie is missing or not as expected, respond with a 400 Bad Request.
w.WriteHeader(http.StatusBadRequest)
return
}
// If the cookie is present and correct, respond with a 200 OK.
w.WriteHeader(http.StatusOK)
}))
defer mockServer.Close()
// Create a new instance of your Client.
client := Create(&Config{
BaseURL: mockServer.URL, // Use the mock server URL in the client configuration.
})
// Define a custom transport that adds a custom cookie to all outgoing requests.
customTransport := testRoundTripperFunc(func(req *http.Request) (*http.Response, error) {
// Add the custom cookie to the request.
req.AddCookie(&http.Cookie{Name: "X-Custom-Test-Cookie", Value: "true"})
// Proceed with the default transport after adding the cookie.
return http.DefaultTransport.RoundTrip(req)
})
// Set the custom http.Client with the custom transport to your Client.
client.SetHTTPClient(&http.Client{
Transport: customTransport,
})
// Send a request using the custom http.Client.
resp, err := client.Get("/test").Send(context.Background())
if err != nil {
t.Fatalf("Failed to send request: %v", err)
}
defer resp.Close() //nolint: errcheck
// Verify that the server responded with a 200 OK, indicating the custom cookie was successfully added.
if resp.StatusCode() != http.StatusOK {
t.Errorf("Expected status code 200, got %d. Indicates custom cookie was not recognized by the server.", resp.StatusCode())
}
}
func TestClientURL(t *testing.T) {
client := URL("http://localhost:8080")
assert.NotNil(t, client)
assert.Equal(t, "http://localhost:8080", client.BaseURL)
}
func TestClientGetRequest(t *testing.T) {
server := startTestHTTPServer()
defer server.Close()
client := Create(&Config{BaseURL: server.URL})
resp, err := client.Get("/test-get").Send(context.Background())
assert.NoError(t, err)
assert.Equal(t, "GET response\n", resp.String())
}
func TestClientPostRequest(t *testing.T) {
server := startTestHTTPServer()
defer server.Close()
client := Create(&Config{BaseURL: server.URL})
resp, err := client.Post("/test-post").Body(map[string]interface{}{"key": "value"}).Send(context.Background())
assert.NoError(t, err)
assert.Equal(t, "POST response\n", resp.String())
}
func TestClientPutRequest(t *testing.T) {
server := startTestHTTPServer()
defer server.Close()
client := Create(&Config{BaseURL: server.URL})
resp, err := client.Put("/test-put").Body(map[string]interface{}{"key": "value"}).Send(context.Background())
assert.NoError(t, err)
assert.Equal(t, "PUT response\n", resp.String())
}
func TestClientDeleteRequest(t *testing.T) {
server := startTestHTTPServer()
defer server.Close()
client := Create(&Config{BaseURL: server.URL})
resp, err := client.Delete("/test-delete").Send(context.Background())
assert.NoError(t, err)
assert.Equal(t, "DELETE response\n", resp.String())
}
func TestClientPatchRequest(t *testing.T) {
server := startTestHTTPServer()
defer server.Close()
client := Create(&Config{BaseURL: server.URL})
resp, err := client.Patch("/test-patch").Body(map[string]interface{}{"key": "value"}).Send(context.Background())
assert.NoError(t, err)
assert.Equal(t, "PATCH response\n", resp.String())
}
func TestClientOptionsRequest(t *testing.T) {
server := startTestHTTPServer()
defer server.Close()
client := Create(&Config{BaseURL: server.URL})
resp, err := client.Options("/test-get").Send(context.Background())
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.RawResponse.StatusCode)
}
func TestClientHeadRequest(t *testing.T) {
server := startTestHTTPServer()
defer server.Close()
client := Create(&Config{BaseURL: server.URL})
resp, err := client.Head("/test-get").Send(context.Background())
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.RawResponse.StatusCode)
}
func TestClientTraceRequest(t *testing.T) {
server := startTestHTTPServer()
defer server.Close()
client := Create(&Config{BaseURL: server.URL})
resp, err := client.TRACE("/test-get").Send(context.Background())
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.RawResponse.StatusCode)
}
func TestClientCustomMethodRequest(t *testing.T) {
server := startTestHTTPServer()
defer server.Close()
client := Create(&Config{BaseURL: server.URL})
resp, err := client.Custom("/test-get", "OPTIONS").Send(context.Background())
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.RawResponse.StatusCode)
}
// testSchema represents the JSON structure for testing.
type testSchema struct {
Name string `json:"name"`
Age int `json:"age"`
}
// TestSetJSONMarshal tests custom JSON marshal functionality.
func TestSetJSONMarshal(t *testing.T) {
// Start a mock HTTP server.
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Read body from the request
var received testSchema
err := json.NewDecoder(r.Body).Decode(&received)
assert.NoError(t, err)
assert.Equal(t, "John Doe", received.Name)
assert.Equal(t, 30, received.Age)
}))
defer server.Close()
client := Create(&Config{BaseURL: server.URL})
// Set the custom JSON marshal function.
client.SetJSONMarshal(sonic.Marshal)
// Create a test data instance.
data := testSchema{
Name: "John Doe",
Age: 30,
}
// Send a request with the custom marshaled body.
resp, err := client.Post("/").JSONBody(&data).Send(context.Background())
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode())
}
// TestSetJSONUnmarshal tests custom JSON unmarshal functionality.
func TestSetJSONUnmarshal(t *testing.T) {
// Mock response data.
mockResponse := `{"name":"Jane Doe","age":25}`
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
fmt.Fprintln(w, mockResponse)
}))
defer server.Close()
client := Create(&Config{BaseURL: server.URL})
// Set the custom JSON unmarshal function.
client.SetJSONUnmarshal(sonic.Unmarshal)
// Fetch and unmarshal the response.
resp, err := client.Get("/").Send(context.Background())
assert.NoError(t, err)
var result testSchema
err = resp.Scan(&result)
assert.NoError(t, err)
assert.Equal(t, "Jane Doe", result.Name)
assert.Equal(t, 25, result.Age)
}
type xmlTestSchema struct {
XMLName xml.Name `xml:"Test"`
Message string `xml:"Message"`
Status bool `xml:"Status"`
}
func TestSetXMLMarshal(t *testing.T) {
// Mock server to check the received XML
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var received xmlTestSchema
err := xml.NewDecoder(r.Body).Decode(&received)
assert.NoError(t, err)
assert.Equal(t, "Test message", received.Message)
assert.True(t, received.Status)
}))
defer server.Close()
// Create your client and set the XML marshal function to use Go's default
client := Create(&Config{BaseURL: server.URL})
client.SetXMLMarshal(xml.Marshal)
// Data to marshal and send
data := xmlTestSchema{
Message: "Test message",
Status: true,
}
// Marshal and send the data
resp, err := client.Post("/").XMLBody(&data).Send(context.Background())
assert.NoError(t, err)
assert.NotNil(t, resp)
}
func TestSetXMLUnmarshal(t *testing.T) {
// Mock server to send XML data
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/xml")
fmt.Fprintln(w, `<Test><Message>Response message</Message><Status>true</Status></Test>`)
}))
defer server.Close()
// Create your client and set the XML unmarshal function to use Go's default
client := Create(&Config{BaseURL: server.URL})
client.SetXMLUnmarshal(xml.Unmarshal)
// Fetch and attempt to unmarshal the data
resp, err := client.Get("/").Send(context.Background())
assert.NoError(t, err)
var result xmlTestSchema
err = resp.Scan(&result)
assert.NoError(t, err)
assert.Equal(t, "Response message", result.Message)
assert.True(t, result.Status)
}
func TestSetYAMLMarshal(t *testing.T) {
// Define a test schema
type yamlTestSchema struct {
Message string `yaml:"message"`
Status bool `yaml:"status"`
}
// Mock server to check the received YAML
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var received yamlTestSchema
err := yaml.NewDecoder(r.Body).Decode(&received)
assert.NoError(t, err)
assert.Equal(t, "Test message", received.Message)
assert.True(t, received.Status)
}))
defer server.Close()
// Create your client and set the YAML marshal function to use goccy/go-yaml's Marshal
client := Create(&Config{BaseURL: server.URL})
client.SetYAMLMarshal(yaml.Marshal)
// Data to marshal and send
data := yamlTestSchema{
Message: "Test message",
Status: true,
}
// Marshal and send the data
resp, err := client.Post("/").YAMLBody(&data).Send(context.Background())
assert.NoError(t, err)
assert.NotNil(t, resp)
}
func TestSetYAMLUnmarshal(t *testing.T) {
// Define a test schema
type yamlTestSchema struct {
Message string `yaml:"message"`
Status bool `yaml:"status"`
}
// Mock server to send YAML data
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/yaml")
fmt.Fprintln(w, "message: Response message\nstatus: true")
}))
defer server.Close()
// Create your client and set the YAML unmarshal function to use goccy/go-yaml's Unmarshal
client := Create(&Config{BaseURL: server.URL})
client.SetYAMLUnmarshal(yaml.Unmarshal)
// Fetch and attempt to unmarshal the data
resp, err := client.Get("/").Send(context.Background())
assert.NoError(t, err)
var result yamlTestSchema
err = resp.Scan(&result)
assert.NoError(t, err)
assert.Equal(t, "Response message", result.Message)
assert.True(t, result.Status)
}
// TestSetAuth verifies that SetAuth correctly sets the Authorization header for basic authentication.
func TestSetAuth(t *testing.T) {
// Expected username and password.
expectedUsername := "testuser"
expectedPassword := "testpass"
// Expected Authorization header value.
expectedAuthValue := "Basic " + base64.StdEncoding.EncodeToString([]byte(expectedUsername+":"+expectedPassword))
// Create a mock server that checks the Authorization header.
mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Retrieve the Authorization header from the request.
authHeader := r.Header.Get("Authorization")
// Check if the Authorization header matches the expected value.
if authHeader != expectedAuthValue {
// If not, respond with 401 Unauthorized.
w.WriteHeader(http.StatusUnauthorized)
return
}
// If the header is correct, respond with 200 OK.
w.WriteHeader(http.StatusOK)
}))
defer mockServer.Close()
// Initialize your client.
client := Create(&Config{
BaseURL: mockServer.URL, // Use the mock server URL.
})
// Set basic authentication using the SetBasicAuth method.
client.SetAuth(BasicAuth{
Username: expectedUsername,
Password: expectedPassword,
})
// Send the request through the client.
resp, err := client.Get("/").Send(context.Background())
if err != nil {
t.Fatalf("Failed to send request: %v", err)
}
defer resp.Close() //nolint: errcheck
// Check the response status code.
if resp.StatusCode() != http.StatusOK {
t.Errorf("Expected status code 200, got %d. Indicates Authorization header was not set correctly.", resp.StatusCode())
}
}
func TestSetDefaultHeaders(t *testing.T) {
// Create a mock server to check headers
mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("X-Custom-Header") != "HeaderValue" {
t.Error("Default header 'X-Custom-Header' not found or value incorrect")
}
}))
defer mockServer.Close()
// Initialize the client and set a default header
client := Create(&Config{BaseURL: mockServer.URL})
client.SetDefaultHeader("X-Custom-Header", "HeaderValue")
// Make a request to trigger the header check
_, err := client.Get("/").Send(context.Background())
if err != nil {
t.Fatalf("Failed to send request: %v", err)
}
}
func TestDelDefaultHeader(t *testing.T) {
// Mock server to check for the absence of a specific header
mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("X-Deleted-Header") != "" {
t.Error("Deleted default header 'X-Deleted-Header' was found in the request")
}
}))
defer mockServer.Close()
// Initialize the client, set, and then delete a default header
client := Create(&Config{BaseURL: mockServer.URL})
client.SetDefaultHeader("X-Deleted-Header", "ShouldBeDeleted")
client.DelDefaultHeader("X-Deleted-Header")
// Make a request to check for the absence of the deleted header
_, err := client.Get("/").Send(context.Background())
if err != nil {
t.Fatalf("Failed to send request: %v", err)
}
}
func TestSetDefaultContentType(t *testing.T) {
mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check the Content-Type header
if r.Header.Get("Content-Type") != "application/json" {
t.Error("Default Content-Type header not set correctly")
}
}))
defer mockServer.Close()
client := Create(&Config{BaseURL: mockServer.URL})
client.SetDefaultContentType("application/json")
_, err := client.Get("/").Send(context.Background())
if err != nil {
t.Fatalf("Failed to send request: %v", err)
}
}
func TestSetDefaultAccept(t *testing.T) {
mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check the Accept header
if r.Header.Get("Accept") != "application/xml" {
t.Error("Default Accept header not set correctly")
}
}))
defer mockServer.Close()
client := Create(&Config{BaseURL: mockServer.URL})
client.SetDefaultAccept("application/xml")
_, err := client.Get("/").Send(context.Background())
if err != nil {
t.Fatalf("Failed to send request: %v", err)
}
}
func TestSetDefaultUserAgent(t *testing.T) {
mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check the User-Agent header
if r.Header.Get("User-Agent") != "MyCustomAgent/1.0" {
t.Error("Default User-Agent header not set correctly")
}
}))
defer mockServer.Close()
client := Create(&Config{BaseURL: mockServer.URL})
client.SetDefaultUserAgent("MyCustomAgent/1.0")
_, err := client.Get("/").Send(context.Background())
if err != nil {
t.Fatalf("Failed to send request: %v", err)
}
}
func TestSetDefaultTimeout(t *testing.T) {
// Create a server that delays its response
mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(2 * time.Second) // Delay longer than client's timeout
}))
defer mockServer.Close()
client := Create(&Config{BaseURL: mockServer.URL})
client.SetDefaultTimeout(1 * time.Second) // Set timeout to 1 second
_, err := client.Get("/").Send(context.Background())
if err == nil {
t.Fatal("Expected a timeout error, got nil")
}
// Check if the error is a timeout error.
// This method of checking for a timeout is more generic and should cover the observed error.
var netErr net.Error
if errors.As(err, &netErr) && netErr.Timeout() {
// If here, it's a timeout error
} else {
t.Fatalf("Expected a timeout error, got %v", err)
}
}
func TestSetDefaultCookieJar(t *testing.T) {
jar, _ := cookiejar.New(nil)
// Initialize the client and set the default cookie jar
client := Create(&Config{})
client.SetDefaultCookieJar(jar)
// Start a test HTTP server that sets a cookie
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/set-cookie" {
http.SetCookie(w, &http.Cookie{Name: "test", Value: "cookie"})
return
}
// Check for the cookie on a different endpoint
cookie, err := r.Cookie("test")
if err != nil {
t.Fatal("Cookie 'test' not found in request, cookie jar not working")
}
if cookie.Value != "cookie" {
t.Fatalf("Expected cookie 'test' to have value 'cookie', got '%s'", cookie.Value)
}
}))
defer server.Close()
// First request to set the cookie
_, err := client.Get(server.URL + "/set-cookie").Send(context.Background())
if err != nil {
t.Fatalf("Failed to send request: %v", err)
}
// Second request to check if the cookie is sent back
_, err = client.Get(server.URL + "/check-cookie").Send(context.Background())
if err != nil {
t.Fatalf("Failed to send second request: %v", err)
}
}
func TestSetDefaultCookies(t *testing.T) {
// Create a mock server to check cookies
mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check for the presence of specific cookies
sessionCookie, err := r.Cookie("session_id")
if err != nil || sessionCookie.Value != "abcd1234" {
t.Error("Default cookie 'session_id' not found or value incorrect")
}
authCookie, err := r.Cookie("auth_token")
if err != nil || authCookie.Value != "token1234" {
t.Error("Default cookie 'auth_token' not found or value incorrect")
}
}))
defer mockServer.Close()
// Initialize the client and set default cookies
client := Create(&Config{BaseURL: mockServer.URL})
client.SetDefaultCookies(map[string]string{
"session_id": "abcd1234",
"auth_token": "token1234",
})
// Make a request to trigger the cookie check
_, err := client.Get("/").Send(context.Background())
if err != nil {
t.Fatalf("Failed to send request: %v", err)
}
}
func TestDelDefaultCookie(t *testing.T) {
// Mock server to check for absence of a specific cookie
mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, err := r.Cookie("session_id")
if err == nil {
t.Error("Deleted default cookie 'session_id' was found in the request")
}
}))
defer mockServer.Close()
// Initialize the client, set, and then delete a default cookie
client := Create(&Config{BaseURL: mockServer.URL})
client.SetDefaultCookie("session_id", "abcd1234")
client.DelDefaultCookie("session_id")
// Make a request to check for the absence of the deleted cookie
_, err := client.Get("/").Send(context.Background())
if err != nil {
t.Fatalf("Failed to send request: %v", err)
}
}
// Helper function to create a test TLS server.
func createTestTLSServer() *httptest.Server {
server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))
// Load server certificate and key.
cert, err := tls.LoadX509KeyPair(".github/testdata/cert.pem", ".github/testdata/key.pem")
if err != nil {
panic("failed to load test certificate: " + err.Error())
}
server.TLS = &tls.Config{
Certificates: []tls.Certificate{cert},
}
server.StartTLS()
return server
}
func TestSetTLSConfig(t *testing.T) {
// Start a test TLS server.
server := createTestTLSServer()
defer server.Close()
// Initialize your client pointing to the test server.
client := URL(server.URL)
// Configure TLS to skip certificate verification.
// Note: This is for testing with self-signed certificates only.
tlsConfig := &tls.Config{
InsecureSkipVerify: true,
}
client.SetTLSConfig(tlsConfig)
// Make a request to the test server.
response, err := client.Get("/").Send(context.Background())
// Ensure no error occurred and the request was successful.
if err != nil {
t.Fatalf("Failed to send request with custom TLS config: %v", err)
}
if response == nil {
t.Fatal("Expected non-nil response")
}
}
func TestSetTLSConfigWithCert(t *testing.T) {
server := createTestTLSServer()
defer server.Close()
client := URL(server.URL)
cert, err := os.ReadFile(".github/testdata/cert.pem")
if err != nil {
t.Fatalf("Failed to load server certificate: %v", err)
}
certPool := x509.NewCertPool()
if !certPool.AppendCertsFromPEM(cert) {
t.Fatal("Failed to append server certificate to pool")
}
require.NoError(t, err, "Failed to load server certificate")
tlsConfig := &tls.Config{
RootCAs: certPool,
}
client.SetTLSConfig(tlsConfig)
// Make a request to the test server.
response, err := client.Get("/").Send(context.Background())
// Ensure no error occurred and the request was successful.
if err != nil {
t.Fatalf("Failed to send request with custom TLS config: %v", err)
}
if response == nil {
t.Fatal("Expected non-nil response")
}
}
func TestInsecureSkipVerify(t *testing.T) {
// Start a test TLS server.
server := createTestTLSServer()
defer server.Close()
// Initialize your client pointing to the test server.
client := URL(server.URL)
// Configure TLS to skip certificate verification.
client.InsecureSkipVerify()
// Make a request to the test server.
response, err := client.Get("/").Send(context.Background())
// Ensure no error occurred and the request was successful.
if err != nil {
t.Fatalf("Failed to send request with custom TLS config: %v", err)
}
if response == nil {
t.Fatal("Expected non-nil response")
}
}
func createTestRetryServer(t *testing.T) *httptest.Server {
var requestCount int
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestCount++
switch requestCount {
case 1:
w.WriteHeader(http.StatusInternalServerError) // Simulate server error on first attempt
case 2:
w.WriteHeader(http.StatusOK) // Successful on second attempt
default:
t.Fatalf("Unexpected number of requests: %d", requestCount)
}
}))
return server
}
func TestSetMaxRetriesAndRetryStrategy(t *testing.T) {
server := createTestRetryServer(t)
defer server.Close()
client := Create(&Config{BaseURL: server.URL})
retryCalled := false
client.SetMaxRetries(1).SetRetryStrategy(func(attempt int) time.Duration {
retryCalled = true
return 10 * time.Millisecond // Short delay for testing
})
// Make a request to the test server
_, err := client.Get("/").Send(context.Background())
if err != nil {
t.Fatalf("Failed to send request: %v", err)
}
if !retryCalled {
t.Error("Expected retry strategy to be called, but it wasn't")
}
}
func TestSetRetryIf(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError) // Always return server error
}))
defer server.Close()
client := Create(&Config{BaseURL: server.URL})
client.SetMaxRetries(2).SetRetryIf(func(req *http.Request, resp *http.Response, err error) bool {
// Only retry for 500 Internal Server Error
return resp.StatusCode == http.StatusInternalServerError
})
retryCount := 0
client.SetRetryStrategy(func(int) time.Duration {
retryCount++
return 10 * time.Millisecond // Short delay for testing
})
// Make a request to the test server
_, err := client.Get("/").Send(context.Background())
if err != nil {
t.Fatalf("Failed to send request: %v", err)
}
if retryCount != 2 {
t.Errorf("Expected 2 retries, got %d", retryCount)
}
}