-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrequest_test.go
1371 lines (1100 loc) · 52 KB
/
request_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 routerosv7_restfull_api
import (
"bytes"
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
)
func TestRequestConfig(t *testing.T) {
// Create a sample requestConfig
config := requestConfig{
URL: "https://example.com", // Set the URL
Method: "GET", // Set the method
Payload: []byte("sample payload"), // Set the payload
Username: "user", // Set the username
Password: "pass", // Set the password
}
// Test URL
expectedURL := "https://example.com"
if config.URL != expectedURL {
t.Errorf("Expected URL to be %s, got %s", expectedURL, config.URL)
}
// Test Method
expectedMethod := "GET"
if config.Method != expectedMethod {
t.Errorf("Expected Method to be %s, got %s", expectedMethod, config.Method)
}
// Test Payload
expectedPayload := []byte("sample payload")
if string(config.Payload) != string(expectedPayload) {
t.Errorf("Expected Payload to be %v, got %v", expectedPayload, config.Payload)
}
// Test Username
expectedUsername := "user"
if config.Username != expectedUsername {
t.Errorf("Expected Username to be %s, got %s", expectedUsername, config.Username)
}
// Test Password
expectedPassword := "pass"
if config.Password != expectedPassword {
t.Errorf("Expected Password to be %s, got %s", expectedPassword, config.Password)
}
}
// TestIsValidURL tests the isValidURL function with various inputs and expected outputs for each test case defined
// in the tests array of struct below it.
func TestIsValidURL(t *testing.T) {
// Test case 1: Valid HTTP URL
tests := []struct {
name string // Test case name
url string // URL
expected bool // Expected result
}{
{"Valid HTTP URL", "http://example.com", true},
{"Valid HTTPS URL", "https://example.com", true},
{"Invalid URL", "invalid_url", false},
{"Empty URL", "", false},
}
// Run the isValidURL function with the test cases defined above
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := isValidURL(tt.url)
if result != tt.expected {
t.Errorf("isValidURL(%s) = %v; want %v", tt.url, result, tt.expected)
}
})
}
}
// mustParseURL parses a raw URL and panics if there is an error. This is used for creating a URL for testing.
// This function is used in the TestParseURL function below. It is not exported. It is only used in this file.
// It is not used in any other file.
func mustParseURL(rawURL string) *url.URL {
// Parse the raw URL
parsedURL, err := url.Parse(rawURL)
// If there is an error, panic
if err != nil {
panic(err)
}
// Return the parsed URL
return parsedURL
}
// TestIsValidHTTPMethod tests the isValidHTTPMethod function with various inputs and expected outputs for each test
// case defined in the tests array of struct below it
func TestIsValidHTTPMethod(t *testing.T) {
// Test case 1: Valid HTTP method
tests := []struct {
name string // Test case name
method string // HTTP method
expected bool // Expected result
}{
{"Valid GET method", "GET", true},
{"Valid POST method", "POST", true},
{"Invalid method", "INVALID_METHOD", false},
{"Empty method", "", false},
}
// Run the isValidHTTPMethod function with the test cases defined above
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := isValidHTTPMethod(tt.method)
if result != tt.expected {
t.Errorf("isValidHTTPMethod(%s) = %v; want %v", tt.method, result, tt.expected)
}
})
}
}
// TestParseURL tests the parseURL function with various inputs and expected outputs for each test case defined in the tests array of struct below it.
func TestParseURL(t *testing.T) {
// Test case 1: Valid URL
tests := []struct {
name string // Test case name
rawURL string // Raw URL
expected *url.URL // Expected parsed URL
wantErr bool // Expected error
}{
{"Valid URL", "https://example.com/path", mustParseURL("https://example.com/path"), false},
{"Invalid URL", "invalid_url", nil, true},
{"Empty URL", "", nil, false},
}
// Run the parseURL function with the test cases defined above
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := parseURL(tt.rawURL)
// Check if the error is as expected for invalid URLs
if (err != nil) != tt.wantErr {
t.Errorf("parseURL(%s) error = %v, wantErr %v", tt.rawURL, err, tt.wantErr)
return
}
// Check if the result is as expected for valid URLs
if tt.expected != nil && (result == nil || result.String() != tt.expected.String()) {
t.Errorf("parseURL(%s) = %v, want %v", tt.rawURL, result, tt.expected)
}
})
}
}
// TestCreateRequestURL tests the createRequestURL function with various inputs and expected outputs for each test case defined in the tests array of struct below it.
func TestCreateRequestBody(t *testing.T) {
// Non-empty payload with valid JSON
payload := []byte(`{"key": "value"}`)
// Create a request body with the non-empty payload
body := createRequestBody(payload)
// Check if the body is not nil
if body == nil {
t.Error("Expected non-nil body for non-empty payload")
}
// Empty payload
var emptyPayload []byte
// Create a request body with the empty payload
emptyBody := createRequestBody(emptyPayload)
// Check if the body is nil
if emptyBody != nil {
t.Error("Expected nil body for empty payload")
}
}
type mockErrorReaderCloser struct{} // Mock a reader closer with an error on read and close
// Mock the Read method to return an error
func (m *mockErrorReaderCloser) Read(_ []byte) (n int, err error) {
return 0, errors.New("mocked read error") // Mock the Read method to return an error
}
// Mock the Close method to return an error
func (m *mockErrorReaderCloser) Close() error {
return errors.New("mocked close error") // Mock the Close method to return an error
}
// TestCloseResponseBody tests is the closeResponseBody function with various inputs and expected outputs for each test case defined in the tests array of struct below it.
func TestCloseResponseBody(t *testing.T) {
// Mock a response body with an error on close
errorBody := &mockErrorReaderCloser{} // Mock a response body with an error on close
// Close the response body
closeResponseBody(errorBody) // This should log the error, you can capture logs and check
}
// TestValidateRequestConfig tests the validateRequestConfig function with various inputs and expected outputs for each test case defined in the tests array of struct below it.
func TestValidateRequestConfig(t *testing.T) {
// Test case 1: Valid Config
tests := []struct {
name string // Test case name
config requestConfig // Request config
expectedError bool // Expected error
}{
{"Valid Config", requestConfig{URL: "https://example.com", Method: "GET"}, false},
{"Invalid URL", requestConfig{URL: "invalid_url", Method: "GET"}, true},
{"Invalid Method", requestConfig{URL: "https://example.com", Method: "INVALID"}, true},
{"Empty Config", requestConfig{}, true},
}
// Run the validateRequestConfig function with the test cases defined above
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := validateRequestConfig(tt.config)
// Check if the error is as expected
if tt.expectedError && err == nil {
t.Error("validateRequestConfig() did not return the expected error.")
}
// Check if the error is as expected
if !tt.expectedError && err != nil {
t.Errorf("validateRequestConfig() returned an unexpected error: %v", err)
}
})
}
}
// TestCreateHTTPClient tests the createHTTPClient function with various inputs and expected outputs for each test case
// defined in the tests array of struct below it.
func TestCreateHTTPClient(t *testing.T) {
// Test for HTTPS protocol
client := createHTTPClient(httpsProtocol)
// Check if the TLS config is set for HTTPS protocol and not set for HTTP protocol for the client created above
//and below respectively in the test cases.
if client.Transport == nil || client.Transport.(*http.Transport).TLSClientConfig == nil {
t.Error("Expected TLS config to be set for HTTPS protocol")
}
// Test for HTTP protocol (no TLS config)
client = createHTTPClient(httpProtocol)
// Check if the TLS config is not set for HTTP protocol for the client created above and below respectively in the test cases.
if client.Transport != nil {
t.Error("Expected no TLS config for HTTP protocol") // Check if the TLS config is not set for HTTP protocol for the client created above and below respectively in the test cases.
}
}
// TestHandleHTTPError_Non2xxWithBody tests the handleHTTPError function with a non-2xx status code and a response body
func TestHandleHTTPError_Non2xxWithBody(t *testing.T) {
responseBody := "Error response body" // Set the response body to a non-empty string
statusCode := http.StatusNotFound // Set the status code to 404
response := httptest.NewRecorder() // Create a new recorder
response.WriteHeader(statusCode) // Set the status code to 404
response.Body.WriteString(responseBody) // Write the response body to the response
err := handleHTTPError(response.Result()) // Handle the HTTP error
// Check if the error is as expected
expectedError := fmt.Sprintf("HTTP error: %d %s, Response body: %s", statusCode, http.StatusText(statusCode), responseBody)
// TestHandleHTTPError_Non2xxWithBody tests the handleHTTPError function with a non-2xx status code and a response body
assertErrorEquality(t, err, expectedError)
}
// TestHandleHTTPError_Non2xxWithoutBody tests the handleHTTPError function with a non-2xx status code and no response body
func TestHandleHTTPError_Non2xxWithoutBody(t *testing.T) {
statusCode := http.StatusInternalServerError // Set the status code to 500
response := httptest.NewRecorder() // Create a new recorder
response.WriteHeader(statusCode) // Set the status code to 500
err := handleHTTPError(response.Result()) // Handle the HTTP error
// Check if the error is as expected
expectedError := fmt.Sprintf("HTTP error: %d %s, Response body: ", statusCode, http.StatusText(statusCode))
// TestHandleHTTPError_Non2xxWithoutBody tests the handleHTTPError function with a non-2xx status code and no response body
assertErrorEquality(t, err, expectedError)
}
// TestHandleHTTPError_Non2xxEmptyBody tests the handleHTTPError function with a non-2xx status code and an empty response body
func TestHandleHTTPError_Non2xxEmptyBody(t *testing.T) {
statusCode := http.StatusBadRequest // Set the status code to 400
response := httptest.NewRecorder() // Create a new recorder
response.WriteHeader(statusCode) // Set the status code to 400
err := handleHTTPError(response.Result()) // Handle the HTTP error
// Check if the error is as expected
expectedError := fmt.Sprintf("HTTP error: %d %s, Response body: ", statusCode, http.StatusText(statusCode))
// TestHandleHTTPError_Non2xxEmptyBody tests the handleHTTPError function with a non-2xx status code and an empty response body
assertErrorEquality(t, err, expectedError)
}
// TestHandleHTTPError_Non2xxLargeBody tests the handleHTTPError function with a non-2xx status code and a large response body
func TestHandleHTTPError_Non2xxLargeBody(t *testing.T) {
statusCode := http.StatusUnauthorized // Set the status code to 401
response := httptest.NewRecorder() // Create a new recorder
response.WriteHeader(statusCode) // Set the status code to 401
largeBody := "This is a very large response body. " + string(make([]byte, 1024*1024)) // 1 MB
response.Body.WriteString(largeBody) // Write the large body to the response
err := handleHTTPError(response.Result()) // Handle the HTTP error
// Check if the error is as expected
expectedError := fmt.Sprintf("HTTP error: %d %s, Response body: %s", statusCode, http.StatusText(statusCode), largeBody)
// TestHandleHTTPError_Non2xxLargeBody tests the handleHTTPError function with a non-2xx status code and a large response body
assertErrorEquality(t, err, expectedError)
}
// TestHandleHTTPError_NilResponseBody tests the handleHTTPError function with a nil response body
func TestHandleHTTPError_NilResponseBody(t *testing.T) {
statusCode := http.StatusNotFound // Set the status code to 404
// Create a nil response body
response := &http.Response{
Status: fmt.Sprintf("%d %s", statusCode, http.StatusText(statusCode)), // Set the status code to 404
StatusCode: statusCode, // Set the status code to 404
Body: nil, // Set the body to nil
}
// Handle the HTTP error
err := handleHTTPError(response)
// Check if the error is as expected
expectedError := "nil HTTP response body"
// TestHandleHTTPError_NilResponseBody tests the handleHTTPError function with a nil response body
assertErrorEquality(t, err, expectedError)
}
func TestHandleHTTPError_ResponseBodyReadError(t *testing.T) {
statusCode := http.StatusNotFound // Set the status code to 404
// Create a response with a mock error reader closer
response := &http.Response{
Status: fmt.Sprintf("%d %s", statusCode, http.StatusText(statusCode)), // Set the status code to 404
Body: &mockErrorReaderCloser{}, // Set the body to a mock error reader closer
}
// Handle the HTTP error
err := handleHTTPError(response)
// Check if the error is as expected
expectedError := "HTTP error: 404 Not Found, Response body: "
// TestHandleHTTPError_ResponseBodyReadError tests the handleHTTPError function with a response body that returns an error on read
assertErrorEquality(t, err, expectedError)
}
// TestHandleHTTPError_ResponseBodyCloseError tests the handleHTTPError function with a response body that returns an error on close
func TestHandleHTTPError_ResponseBodyCloseError(t *testing.T) {
statusCode := http.StatusNotFound // Set the status code to 404
// Create a response with a mock error reader closer
response := &http.Response{
Status: fmt.Sprintf("%d %s", statusCode, http.StatusText(statusCode)), // Set the status code to 404
Body: &mockErrorReaderCloser{}, // Set the body to a mock error reader closer
}
// Handle the HTTP error
err := handleHTTPError(response)
// Check if the error is as expected
expectedError := "HTTP error: 404 Not Found, Response body: "
// TestHandleHTTPError_ResponseBodyCloseError tests the handleHTTPError function with a response body that returns an error on close
assertErrorEquality(t, err, expectedError)
}
// Helper functions assertErrorEquality is used to check if the error is as expected
func assertErrorEquality(t *testing.T, actualError error, expectedError string) {
// Check if the error is as expected
if actualError == nil || actualError.Error() != expectedError {
t.Errorf("Expected error: %s, Got: %v", expectedError, actualError) // Check if the error is as expected
}
}
type emptyReadCloser struct{} // Mock a reader closer with an EOF on read and no error on close
// Mock the Read method to return an EOF
func (erc *emptyReadCloser) Read(_ []byte) (n int, err error) {
return 0, io.EOF // Mock the Read method to return an EOF
}
// Mock the Close method to return no error
func (erc *emptyReadCloser) Close() error {
return nil // Mock the Close method to return no error
}
// TestDecodeJSONBody tests the decodeJSONBody function with various inputs and expected outputs for each test case
type stringReadCloser struct {
io.Reader // Mock a reader closer with a string reader
}
// Mock the Close method to return no error
func (src *stringReadCloser) Close() error {
return nil // Mock the Close method to return no error
}
// TestDecodeJSONBody tests the decodeJSONBody function with various inputs and expected outputs for each test case
func TestDecodeJSONBody(t *testing.T) {
// Create a response with an empty body
response := &http.Response{
StatusCode: http.StatusOK, // Set the status code to 200
Body: &emptyReadCloser{}, // Set the body to an empty reader closer
}
// Attempt to decode an empty body
result, err := decodeJSONBody(response.Body)
// Ensure there is no error or EOF
if err != nil && err != io.EOF {
t.Errorf("Expected no error or EOF, got %v", err) // Attempt to decode an empty body
}
// Ensure the result is nil
if result != nil {
t.Error("Expected a nil result for an empty JSON body") // Ensure the result is nil
}
// Create a response with a non-empty body
response = &http.Response{
StatusCode: http.StatusOK, // Set the status code to 200
Body: &stringReadCloser{strings.NewReader(`{"key": "value"}`)}, // Set the body to a non-empty JSON string
}
// Attempt to decode a non-empty body
result, err = decodeJSONBody(response.Body)
// Ensure there is no error or EOF
if err != nil {
t.Errorf("Expected no error, got %v", err)
}
// Ensure the result is not nil
if result == nil {
t.Error("Expected a non-nil result for a non-empty JSON body")
}
// Create another response with a different non-empty body
response = &http.Response{
StatusCode: http.StatusOK,
Body: &stringReadCloser{strings.NewReader(`{"anotherKey": "anotherValue"}`)},
}
// Attempt to decode the different non-empty body
result, err = decodeJSONBody(response.Body)
if err != nil {
t.Errorf("Expected no error, got %v", err)
}
// Ensure the result is not nil
if result == nil {
t.Error("Expected a non-nil result for a different non-empty JSON body")
}
}
// TestSetRequestAuth tests the setRequestAuth function with various inputs and expected outputs for each test case
func TestSetRequestAuth(t *testing.T) {
// Test case 1: Set BasicAuth with valid username and password
request := &http.Request{Header: make(http.Header)} // Create a new request
username := "user" // Set the username to a non-empty value
password := "pass" // Set the password to a non-empty value
setRequestAuth(request, username, password) // Set the BasicAuth
// Check if BasicAuth is set correctly
if user, pass, ok := request.BasicAuth(); !ok || user != username || pass != password {
t.Errorf("Test case 1: BasicAuth not set correctly. Expected (%s, %s), got (%s, %s)", username, password, user, pass)
}
// Test case 2: Do not set BasicAuth if username and password are empty
request = &http.Request{Header: make(http.Header)}
setRequestAuth(request, "", "")
if user, pass, ok := request.BasicAuth(); ok || user != "" || pass != "" {
t.Error("Test case 2: BasicAuth set incorrectly. Expected not set, but it is set.")
}
}
// TestSetRequestContentType tests the setRequestContentType function with various inputs and expected outputs for each test case
func TestSetRequestContentType(t *testing.T) {
// Test case 1: Content-Type is set to application/json
request := &http.Request{Header: make(http.Header)}
// Set the Content-Type to application/json
setRequestContentType(request)
// Check if Content-Type is set correctly
if contentType := request.Header.Get("Content-Type"); contentType != "application/json" {
t.Errorf("Test case 1: Content-Type not set correctly. Expected application/json, got %s", contentType)
}
}
// TestSetRequestHeaders tests the setRequestHeaders function with various inputs and expected outputs for each test case
func TestNewHTTPRequest(t *testing.T) {
// Test case 1: Valid GET request without authentication
ctx := context.Background() // Create a new context
method := http.MethodGet // Set the method to GET
urls := "http://example.com" // Set the URL to a valid URL
var body io.Reader = nil // Set the body to nil
username := "" // Set the username to an empty string
password := "" // Set the password to an empty string
// Create a new HTTP request
request, err := newHTTPRequest(ctx, method, urls, body, username, password)
// Check if there is no error for a valid GET request without authentication
if err != nil {
t.Errorf("Test case 1: Expected no error, but got an error: %v", err)
}
// Check if the request is not nil for a valid GET request without authentication
if request == nil {
t.Error("Test case 1: Expected a non-nil request, but got nil")
}
// Test case 2: Valid POST request with authentication
method = http.MethodPost // Change the method to POST
body = strings.NewReader(`{"key": "value"}`) // Change the body to a non-nil value
username = "user" // Change the username to a non-empty value
password = "pass" // Change the password to a non-empty value
// Create a new HTTP request
request, err = newHTTPRequest(ctx, method, urls, body, username, password)
// Check if there is no error for a valid POST request with authentication
if err != nil {
t.Errorf("Test case 2: Expected no error, but got an error: %v", err)
}
// Check if the request is not nil for a valid POST request with authentication
if request == nil {
t.Error("Test case 2: Expected a non-nil request, but got nil")
}
// Test case 3: Invalid URL
urls = ":invalid-url"
// Create a new HTTP request with an invalid URL
_, err = newHTTPRequest(ctx, method, urls, body, username, password)
// Check if there is an error for an invalid URL
if err == nil {
t.Error("Test case 3: Expected an error for an invalid URL, but got nil")
}
}
// TestCreateRequestValidGet tests the createRequest function for a valid GET request
func TestCreateRequestValidGet(t *testing.T) {
ctx := context.Background() // Create a new context
method := http.MethodGet // Set the method to GET
ulrs := "http://example.com" // Set the URL to a valid URL
body := io.Reader(nil) // Set the body to nil
username := "user" // Set the username to a non-empty value
password := "pass" // Set the password to a non-empty value
// Create a new HTTP request
request, err := createRequest(ctx, method, ulrs, body, username, password)
// Check if there is no error for a valid GET request
if err != nil {
t.Errorf("Expected no error, got %v", err)
}
// Check if the request is not nil for a valid GET request
if request == nil {
t.Error("Expected non-nil request, got nil")
}
}
// TestCreateRequestValidPost tests the createRequest function for a valid POST request
func TestCreateRequestValidPost(t *testing.T) {
ctx := context.Background() // Create a new context
method := http.MethodPost // Set the method to POST
myURL := "http://example.com" // Set the URL to a valid URL
body := io.Reader(nil) // Set the body to nil
username := "user" // Set the username to a non-empty value
password := "pass" // Set the password to a non-empty value
// Create a new HTTP request with a valid POST request
request, err := createRequest(ctx, method, myURL, body, username, password)
// Check if there is no error for a valid POST request
if err != nil {
t.Errorf("Expected no error, got %v", err) // Check if there is no error for a valid POST request
}
// Check if the request is not nil for a valid POST request
if request == nil {
t.Error("Expected non-nil request, got nil") // Check if the request is not nil for a valid POST request
}
}
// TestCreateRequestValidWithBody tests the createRequest function for a valid request with a body
func TestCreateRequestValidWithBody(t *testing.T) {
ctx := context.Background() // Create a new context
method := http.MethodPut // Set the method to PUT
myURL := "http://example.com" // Set the URL to a valid URL
body := bytes.NewBufferString(`{"key": "value"}`) // Set the body to a non-nil value
username := "user" // Set the username to a non-empty value
password := "pass" // Set the password to a non-empty value
// Create a new HTTP request with a valid request with a body
request, err := createRequest(ctx, method, myURL, body, username, password)
// Check if there is no error for a valid request with a body
if err != nil {
t.Errorf("Expected no error, got %v", err) // Check if there is no error for a valid request with a body
}
// Check if the request is not nil for a valid request with a body
if request == nil {
t.Error("Expected non-nil request, got nil") // Check if the request is not nil for a valid request with a body
}
}
// TestCreateRequestInvalidURL tests the createRequest function for an invalid URL
func TestCreateRequestInvalidURL(t *testing.T) {
ctx := context.Background() // Create a new context
method := http.MethodPut // Set the method to PUT
myURL := ":invalid-url" // Set the URL to an invalid URL
body := io.Reader(nil) // Set the body to nil
username := "user" // Set the username to a non-empty value
password := "pass" // Set the password to a non-empty value
// Create a new HTTP request with an invalid URL
_, err := createRequest(ctx, method, myURL, body, username, password)
// Check if there is an error for an invalid URL
if err == nil {
t.Error("Expected error for invalid URL, got nil")
}
}
// TestCreateRequestErrorParsingURL tests the createRequest function for an error parsing the URL
func TestCreateRequestErrorParsingURL(t *testing.T) {
ctx := context.Background() // Create a new context
method := http.MethodGet // Set the method to GET
myURL := "http://example.com" // Set the URL to a valid URL
body := io.Reader(nil) // Set the body to nil
username := "user" // Set the username to a non-empty value
password := "pass" // Set the password to a non-empty value
// Create a new HTTP request with an error parsing the URL
_, err := createRequest(ctx, method, myURL, body, username, password)
// Check if there is an error for an error parsing the URL
if err != nil {
t.Errorf("Expected no error while creating request, got %v", err) // Check if there is an error for an error parsing the URL
}
}
// TestCreateRequestInvalidHTTPMethod tests the createRequest function for an invalid HTTP method
func TestCreateRequestInvalidHTTPMethod(t *testing.T) {
ctx := context.Background() // Create a new context
method := "INVALID" // Set the method to an invalid HTTP method
myURL := "http://example.com" // Set the URL to a valid URL
body := io.Reader(nil) // Set the body to nil
username := "user" // Set the username to a non-empty value
password := "pass" // Set the password to a non-empty value
// Create a new HTTP request with an invalid HTTP method
_, err := createRequest(ctx, method, myURL, body, username, password)
// Check if there is an error for an invalid HTTP method
if err == nil {
t.Error("Expected error for invalid HTTP method, got nil") // Check if there is an error for an invalid HTTP method
}
}
// TestCreateRequestErrorCreatingRequest tests the createRequest function for an error creating the request
func TestCreateRequestErrorCreatingRequest(t *testing.T) {
ctx := context.Background() // Create a new context
method := http.MethodGet // Set the method to GET
myURL := "http://example.com" // Set the URL to a valid URL
body := io.Reader(nil) // Set the body to nil
username := "user" // Set the username to a non-empty value
password := "pass" // Set the password to a non-empty value
// Create a new HTTP request with an error creating the request
_, err := createRequest(ctx, method, myURL, body, username, password)
// Check if there is an error for an error creating the request
if err != nil {
t.Errorf("Expected no error, got %v", err) // Check if there is an error for an error creating the request
}
}
// TestCreateRequestErrorCreatingRequestWithInvalidURL tests the createRequest function for an error creating the request with an invalid URL
func TestCreateRequestErrorCreatingRequestWithInvalidURL(t *testing.T) {
ctx := context.Background() // Create a new context
method := http.MethodGet // Set the method to GET
myURL := ":invalid-url" // Set the URL to an invalid URL
body := io.Reader(nil) // Set the body to nil
username := "user" // Set the username to a non-empty value
password := "pass" // Set the password to a non-empty value
// Create a new HTTP request with an error creating the request with an invalid URL
_, err := createRequest(ctx, method, myURL, body, username, password)
// Check if there is an error for an error creating the request with an invalid URL
if err == nil {
t.Error("Expected error for invalid URL, got nil") // Check if there is an error for an error creating the request with an invalid URL
}
}
// TestCreateRequestErrorCreatingRequestWithInvalidHTTPMethod tests the createRequest function for an error creating the request with an invalid HTTP method
func TestCreateRequestErrorCreatingRequestWithInvalidHTTPMethod(t *testing.T) {
ctx := context.Background() // Create a new context
method := "INVALID" // Set the method to an invalid HTTP method
myURL := "http://example.com" // Set the URL to a valid URL
body := io.Reader(nil) // Set the body to nil
username := "user" // Set the username to a non-empty value
password := "pass" // Set the password to a non-empty value
// Create a new HTTP request with an error creating the request with an invalid HTTP method
_, err := createRequest(ctx, method, myURL, body, username, password)
// Check if there is an error for an error creating the request with an invalid HTTP method
if err == nil {
t.Error("Expected error for invalid HTTP method, got nil") // Check if there is an error for an error creating the request with an invalid HTTP method
}
}
// TestCreateRequestErrorCreatingRequestWithInvalidHTTPMethodAndURL tests the createRequest function for an error creating the request with an invalid HTTP method and invalid URL
func TestCreateRequestErrorCreatingRequestWithInvalidHTTPMethodAndURL(t *testing.T) {
ctx := context.Background() // Create a new context
method := "INVALID" // Set the method to an invalid HTTP method
myURL := ":invalid-url" // Set the URL to an invalid URL
body := io.Reader(nil) // Set the body to nil
username := "user" // Set the username to a non-empty value
password := "pass" // Set the password to a non-empty value
// Create a new HTTP request with an error creating the request with an invalid HTTP method and invalid URL
_, err := createRequest(ctx, method, myURL, body, username, password)
// Check if there is an error for an error creating the request with an invalid HTTP method and invalid URL
if err == nil {
t.Error("Expected error for invalid HTTP method and invalid URL, got nil") // Check if there is an error for an error creating the request with an invalid HTTP method and invalid URL
}
}
// TestCreateRequestNoErrorWithEmptyBody tests the createRequest function for no error with an empty body
func TestCreateRequestNoErrorWithEmptyBody(t *testing.T) {
ctx := context.Background() // Create a new context
method := http.MethodGet // Set the method to GET
myURL := "http://example.com" // Set the URL to a valid URL
body := io.Reader(nil) // Set the body to nil
username := "user" // Set the username to a non-empty value
password := "pass" // Set the password to a non-empty value
// Create a new HTTP request with no error with an empty body
_, err := createRequest(ctx, method, myURL, body, username, password)
// Check if there is no error for no error with an empty body
if err != nil {
t.Errorf("Expected no error, got %v", err) // Check if there is no error for no error with an empty body
}
}
// TestRetryTlsErrorRequest tests the retryTlsErrorRequest function with a mock HTTP server
func TestRetryTlsErrorRequest(t *testing.T) {
// Create a mock HTTP server with a handler that returns a 500 status code for the first request
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Simulate a TLS handshake failure for the first request
if r.URL.Scheme == httpsProtocol {
w.WriteHeader(http.StatusInternalServerError)
_, err := w.Write([]byte("Simulated TLS handshake failure"))
if err != nil {
return
}
return
}
// Return a 200 status code for the second request
w.WriteHeader(http.StatusOK)
// Return a success message for the second request
_, err := w.Write([]byte("Success")) // Write the response body
if err != nil {
return
}
}))
defer server.Close()
// Create a request configuration with the mock server URL and a valid HTTP method and payload
config := requestConfig{
URL: server.URL, // URL of the mock server
Method: http.MethodGet, // Default to GET method
Payload: nil, // No payload
Username: "", // No username
Password: "", // No password
}
// Make an HTTP client with a transport that injects an error for the first request (TLS handshake failure)
client := &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{},
},
}
// Create an HTTP request with the mock server URL and a valid HTTP method and payload
request, err := http.NewRequest(http.MethodGet, server.URL, nil)
if err != nil {
t.Fatalf("Failed to create HTTP request: %v", err)
}
// Run the retryTlsErrorRequest function with the mock server URL and a valid HTTP method and payload and the
//HTTP client with a transport that injects an error for the first request (
//TLS handshake failure) and the request configuration with the mock server URL and a valid HTTP method and payload
response, err := retryTlsErrorRequest(client, request, config)
// Check if there is no error for the second request (
//TLS handshake success) and the request configuration with the mock server URL and a valid HTTP method and
//payload and the HTTP client with a transport that injects an error for the first request (TLS handshake failure)
if err != nil {
t.Fatalf("RetryTlsErrorRequest failed: %v", err)
}
// Check if the response has the expected status code for the second request (
//TLS handshake success) and the request configuration with the mock server URL and a valid HTTP method and
//payload and the HTTP client with a transport that injects an error for the first request (TLS handshake failure)
if response.StatusCode != http.StatusOK {
t.Fatalf("Expected status code %d, got %d", http.StatusOK, response.StatusCode)
}
// Check if the response body is as expected for the second request
expectedResponse := "Success"
// Check if the response body is as expected for the second request ( TLS handshake success) and the request
actualResponse := readResponseBody(response)
// Check if the response body is as expected for the second request ( TLS handshake success) and the request
if actualResponse != expectedResponse {
t.Fatalf("Expected response body %s, got %s", expectedResponse, actualResponse)
}
}
// Helper function for reading the response body
func readResponseBody(response *http.Response) string {
body, _ := io.ReadAll(response.Body) // read the response body
defer closeResponseBody(response.Body) // close the response body
return string(body) // return the response body as a string
}
// TestSendRequest_Success tests the sendRequest function with a successful HTTP request
func TestSendRequest_Success(t *testing.T) {
// Create a mock HTTP server
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, err := w.Write([]byte("Success"))
if err != nil {
return
}
}))
defer server.Close()
// Create a request configuration
config := requestConfig{
URL: server.URL, // URL of the mock server
Method: http.MethodGet, // Default to GET method
Payload: nil, // No payload
Username: "", // No username
Password: "", // No password
}
// Create an HTTP client with a transport that injects an error
client := &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{},
},
}
// Create an HTTP request
request, err := createRequest(context.Background(), config.Method, config.URL, nil, config.Username, config.Password)
if err != nil {
t.Fatalf("Failed to create HTTP request: %v", err)
}
// Run the sendRequest function
response, err := sendRequest(client, request, config)
// Check if there is no error
if err != nil {
t.Fatalf("sendRequest failed: %v", err)
}
// Check if the response has the expected status code
if response.StatusCode != http.StatusOK {
t.Fatalf("Expected status code %d, got %d", http.StatusOK, response.StatusCode)
}
// Check if the response body is as expected
expectedResponse := "Success"
// Check if the response body is as expected
actualResponse := readResponseBody(response)
// Check if the response body is as expected
if actualResponse != expectedResponse {
t.Fatalf("Expected response body %s, got %s", expectedResponse, actualResponse)
}
}
// TestSendRequest_TlsErrorRetry tests the sendRequest function with TLS error retry logic
func TestSendRequest_TlsErrorRetry(t *testing.T) {
// Create a mock HTTP server
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, err := w.Write([]byte("Success"))
if err != nil {
return
}
}))
defer server.Close()
// Create a request configuration
config := requestConfig{
URL: server.URL, // URL of the mock server
Method: http.MethodGet, // Default to GET method
Payload: nil, // No payload
Username: "", // No username
Password: "", // No password
}
// Create an HTTP client with a transport that injects a TLS error
client := &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{},
},
}
// Create an HTTP request
request, err := createRequest(context.Background(), config.Method, config.URL, nil, config.Username, config.Password)
if err != nil {
t.Fatalf("Failed to create HTTP request: %v", err)
}
// Force a TLS error
client.Transport = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
// Run the sendRequest function
response, err := sendRequest(client, request, config)
// Check if there is no error
if err != nil {
t.Fatalf("sendRequest failed: %v", err)
}
// Check if the response has the expected status code
if response.StatusCode != http.StatusOK {
t.Fatalf("Expected status code %d, got %d", http.StatusOK, response.StatusCode)
}
// Check if the response body is as expected
expectedResponse := "Success"
// Check if the response body is as expected
actualResponse := readResponseBody(response)
// Check if the response body is as expected
if actualResponse != expectedResponse {
t.Fatalf("Expected response body %s, got %s", expectedResponse, actualResponse)
} else {
t.Logf("Expected response body %s, got %s", expectedResponse, actualResponse)
}
}
// TestSendRequest_TlsErrorRetrySendRequest tests the sendRequest function with TLS error retry logic
func TestSendRequest_TlsErrorRetrySendRequest(t *testing.T) {
// Create a mock HTTP server
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, err := w.Write([]byte("Success"))
if err != nil {
return
}