-
Notifications
You must be signed in to change notification settings - Fork 717
/
resty_test.go
917 lines (786 loc) · 26.5 KB
/
resty_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
// Copyright (c) 2015-2024 Jeevanandam M (jeeva@myjeeva.com), All rights reserved.
// resty source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.
package resty
import (
"compress/gzip"
"crypto/md5"
"encoding/base64"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"reflect"
"strconv"
"strings"
"sync/atomic"
"testing"
"time"
)
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// Testing Unexported methods
//___________________________________
func getTestDataPath() string {
pwd, _ := os.Getwd()
return filepath.Join(pwd, ".testdata")
}
func createGetServer(t *testing.T) *httptest.Server {
var attempt int32
var sequence int32
var lastRequest time.Time
ts := createTestServer(func(w http.ResponseWriter, r *http.Request) {
t.Logf("Method: %v", r.Method)
t.Logf("Path: %v", r.URL.Path)
if r.Method == MethodGet {
switch r.URL.Path {
case "/":
_, _ = w.Write([]byte("TestGet: text response"))
case "/no-content":
_, _ = w.Write([]byte(""))
case "/json":
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"TestGet": "JSON response"}`))
case "/json-invalid":
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte("TestGet: Invalid JSON"))
case "/long-text":
_, _ = w.Write([]byte("TestGet: text response with size > 30"))
case "/long-json":
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"TestGet": "JSON response with size > 30"}`))
case "/mypage":
w.WriteHeader(http.StatusBadRequest)
case "/mypage2":
_, _ = w.Write([]byte("TestGet: text response from mypage2"))
case "/set-retrycount-test":
attp := atomic.AddInt32(&attempt, 1)
if attp <= 4 {
time.Sleep(time.Second * 6)
}
_, _ = w.Write([]byte("TestClientRetry page"))
case "/set-retrywaittime-test":
// Returns time.Duration since last request here
// or 0 for the very first request
if atomic.LoadInt32(&attempt) == 0 {
lastRequest = time.Now()
_, _ = fmt.Fprint(w, "0")
} else {
now := time.Now()
sinceLastRequest := now.Sub(lastRequest)
lastRequest = now
_, _ = fmt.Fprintf(w, "%d", uint64(sinceLastRequest))
}
atomic.AddInt32(&attempt, 1)
case "/set-retry-error-recover":
w.Header().Set(hdrContentTypeKey, "application/json; charset=utf-8")
if atomic.LoadInt32(&attempt) == 0 {
w.WriteHeader(http.StatusTooManyRequests)
_, _ = w.Write([]byte(`{ "message": "too many" }`))
} else {
_, _ = w.Write([]byte(`{ "message": "hello" }`))
}
atomic.AddInt32(&attempt, 1)
case "/set-timeout-test-with-sequence":
seq := atomic.AddInt32(&sequence, 1)
time.Sleep(time.Second * 2)
_, _ = fmt.Fprintf(w, "%d", seq)
case "/set-timeout-test":
time.Sleep(time.Second * 6)
_, _ = w.Write([]byte("TestClientTimeout page"))
case "/my-image.png":
fileBytes, _ := os.ReadFile(filepath.Join(getTestDataPath(), "test-img.png"))
w.Header().Set("Content-Type", "image/png")
w.Header().Set("Content-Length", strconv.Itoa(len(fileBytes)))
_, _ = w.Write(fileBytes)
case "/get-method-payload-test":
body, err := io.ReadAll(r.Body)
if err != nil {
t.Errorf("Error: could not read get body: %s", err.Error())
}
_, _ = w.Write(body)
case "/host-header":
_, _ = w.Write([]byte(r.Host))
case "/not-found-with-error":
w.Header().Set(hdrContentTypeKey, "application/json")
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`{"error": "Not found"}`))
case "/not-found-no-error":
w.Header().Set(hdrContentTypeKey, "application/json")
w.WriteHeader(http.StatusNotFound)
case "/unescape-query-params":
initOne := r.URL.Query().Get("initone")
fromClient := r.URL.Query().Get("fromclient")
registry := r.URL.Query().Get("registry")
assertEqual(t, "cáfe", initOne)
assertEqual(t, "hey unescape", fromClient)
assertEqual(t, "nacos://test:6801", registry)
_, _ = w.Write([]byte(`query params looks good`))
}
switch {
case strings.HasPrefix(r.URL.Path, "/v1/users/sample@sample.com/100002"):
if strings.HasSuffix(r.URL.Path, "details") {
_, _ = w.Write([]byte("TestGetPathParams: text response: " + r.URL.String()))
} else {
_, _ = w.Write([]byte("TestPathParamURLInput: text response: " + r.URL.String()))
}
}
}
})
return ts
}
func handleLoginEndpoint(t *testing.T, w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/login" {
user := &User{}
// JSON
if IsJSONType(r.Header.Get(hdrContentTypeKey)) {
jd := json.NewDecoder(r.Body)
err := jd.Decode(user)
if r.URL.Query().Get("ct") == "problem" {
w.Header().Set(hdrContentTypeKey, "application/problem+json; charset=utf-8")
} else if r.URL.Query().Get("ct") == "rpc" {
w.Header().Set(hdrContentTypeKey, "application/json-rpc")
} else {
w.Header().Set(hdrContentTypeKey, "application/json")
}
if err != nil {
t.Logf("Error: %#v", err)
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{ "id": "bad_request", "message": "Unable to read user info" }`))
return
}
if user.Username == "testuser" && user.Password == "testpass" {
_, _ = w.Write([]byte(`{ "id": "success", "message": "login successful" }`))
} else if user.Username == "testuser" && user.Password == "invalidjson" {
_, _ = w.Write([]byte(`{ "id": "success", "message": "login successful", }`))
} else {
w.WriteHeader(http.StatusUnauthorized)
_, _ = w.Write([]byte(`{ "id": "unauthorized", "message": "Invalid credentials" }`))
}
return
}
// XML
if IsXMLType(r.Header.Get(hdrContentTypeKey)) {
xd := xml.NewDecoder(r.Body)
err := xd.Decode(user)
w.Header().Set(hdrContentTypeKey, "application/xml")
if err != nil {
t.Logf("Error: %v", err)
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`<?xml version="1.0" encoding="UTF-8"?>`))
_, _ = w.Write([]byte(`<AuthError><Id>bad_request</Id><Message>Unable to read user info</Message></AuthError>`))
return
}
if user.Username == "testuser" && user.Password == "testpass" {
_, _ = w.Write([]byte(`<?xml version="1.0" encoding="UTF-8"?>`))
_, _ = w.Write([]byte(`<AuthSuccess><Id>success</Id><Message>login successful</Message></AuthSuccess>`))
} else if user.Username == "testuser" && user.Password == "invalidxml" {
_, _ = w.Write([]byte(`<?xml version="1.0" encoding="UTF-8"?>`))
_, _ = w.Write([]byte(`<AuthSuccess><Id>success</Id><Message>login successful</AuthSuccess>`))
} else {
w.Header().Set("Www-Authenticate", "Protected Realm")
w.WriteHeader(http.StatusUnauthorized)
_, _ = w.Write([]byte(`<?xml version="1.0" encoding="UTF-8"?>`))
_, _ = w.Write([]byte(`<AuthError><Id>unauthorized</Id><Message>Invalid credentials</Message></AuthError>`))
}
return
}
}
}
func handleUsersEndpoint(t *testing.T, w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/users" {
// JSON
if IsJSONType(r.Header.Get(hdrContentTypeKey)) {
var users []ExampleUser
jd := json.NewDecoder(r.Body)
err := jd.Decode(&users)
w.Header().Set(hdrContentTypeKey, "application/json")
if err != nil {
t.Logf("Error: %v", err)
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{ "id": "bad_request", "message": "Unable to read user info" }`))
return
}
// logic check, since we are excepting to reach 3 records
if len(users) != 3 {
t.Log("Error: Excepted count of 3 records")
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{ "id": "bad_request", "message": "Expected record count doesn't match" }`))
return
}
eu := users[2]
if eu.FirstName == "firstname3" && eu.ZipCode == "10003" {
w.WriteHeader(http.StatusAccepted)
_, _ = w.Write([]byte(`{ "message": "Accepted" }`))
}
return
}
}
}
func createPostServer(t *testing.T) *httptest.Server {
ts := createTestServer(func(w http.ResponseWriter, r *http.Request) {
t.Logf("Method: %v", r.Method)
t.Logf("Path: %v", r.URL.Path)
t.Logf("RawQuery: %v", r.URL.RawQuery)
t.Logf("Content-Type: %v", r.Header.Get(hdrContentTypeKey))
if r.Method == MethodPost {
handleLoginEndpoint(t, w, r)
handleUsersEndpoint(t, w, r)
switch r.URL.Path {
case "/login-json-html":
w.Header().Set(hdrContentTypeKey, "text/html")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`<htm><body>Test JSON request with HTML response</body></html>`))
return
case "/usersmap":
// JSON
if IsJSONType(r.Header.Get(hdrContentTypeKey)) {
if r.URL.Query().Get("status") == "500" {
body, err := io.ReadAll(r.Body)
if err != nil {
t.Errorf("Error: could not read post body: %s", err.Error())
}
t.Logf("Got query param: status=500 so we're returning the post body as response and a 500 status code. body: %s", string(body))
w.Header().Set(hdrContentTypeKey, "application/json; charset=utf-8")
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write(body)
return
}
var users []map[string]interface{}
jd := json.NewDecoder(r.Body)
err := jd.Decode(&users)
w.Header().Set(hdrContentTypeKey, "application/json; charset=utf-8")
if err != nil {
t.Logf("Error: %v", err)
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{ "id": "bad_request", "message": "Unable to read user info" }`))
return
}
// logic check, since we are excepting to reach 1 map records
if len(users) != 1 {
t.Log("Error: Excepted count of 1 map records")
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{ "id": "bad_request", "message": "Expected record count doesn't match" }`))
return
}
w.WriteHeader(http.StatusAccepted)
_, _ = w.Write([]byte(`{ "message": "Accepted" }`))
return
}
case "/redirect":
w.Header().Set(hdrLocationKey, "/login")
w.WriteHeader(http.StatusTemporaryRedirect)
case "/redirect-with-body":
body, _ := io.ReadAll(r.Body)
query := url.Values{}
query.Add("body", string(body))
w.Header().Set(hdrLocationKey, "/redirected-with-body?"+query.Encode())
w.WriteHeader(http.StatusTemporaryRedirect)
case "/redirected-with-body":
body, _ := io.ReadAll(r.Body)
assertEqual(t, r.URL.Query().Get("body"), string(body))
w.WriteHeader(http.StatusOK)
case "/curl-cmd-post":
cookie := http.Cookie{
Name: "testserver",
Domain: "localhost",
Path: "/",
Expires: time.Now().AddDate(0, 0, 1),
Value: "yes",
}
http.SetCookie(w, &cookie)
w.WriteHeader(http.StatusOK)
}
}
})
return ts
}
func createFormPostServer(t *testing.T) *httptest.Server {
ts := createTestServer(func(w http.ResponseWriter, r *http.Request) {
t.Logf("Method: %v", r.Method)
t.Logf("Path: %v", r.URL.Path)
t.Logf("Content-Type: %v", r.Header.Get(hdrContentTypeKey))
if r.Method == MethodPost {
_ = r.ParseMultipartForm(10e6)
if r.URL.Path == "/profile" {
t.Logf("FirstName: %v", r.FormValue("first_name"))
t.Logf("LastName: %v", r.FormValue("last_name"))
t.Logf("City: %v", r.FormValue("city"))
t.Logf("Zip Code: %v", r.FormValue("zip_code"))
_, _ = w.Write([]byte("Success"))
return
} else if r.URL.Path == "/search" {
formEncodedData := r.Form.Encode()
t.Logf("Received Form Encoded values: %v", formEncodedData)
assertEqual(t, true, strings.Contains(formEncodedData, "search_criteria=pencil"))
assertEqual(t, true, strings.Contains(formEncodedData, "search_criteria=glass"))
_, _ = w.Write([]byte("Success"))
return
} else if r.URL.Path == "/upload" {
t.Logf("FirstName: %v", r.FormValue("first_name"))
t.Logf("LastName: %v", r.FormValue("last_name"))
targetPath := filepath.Join(getTestDataPath(), "upload")
_ = os.MkdirAll(targetPath, 0700)
for _, fhdrs := range r.MultipartForm.File {
for _, hdr := range fhdrs {
t.Logf("Name: %v", hdr.Filename)
t.Logf("Header: %v", hdr.Header)
dotPos := strings.LastIndex(hdr.Filename, ".")
fname := fmt.Sprintf("%s-%v%s", hdr.Filename[:dotPos], time.Now().Unix(), hdr.Filename[dotPos:])
t.Logf("Write name: %v", fname)
infile, _ := hdr.Open()
f, err := os.OpenFile(filepath.Join(targetPath, fname), os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
t.Logf("Error: %v", err)
return
}
defer func() {
_ = f.Close()
}()
_, _ = io.Copy(f, infile)
_, _ = w.Write([]byte(fmt.Sprintf("File: %v, uploaded as: %v\n", hdr.Filename, fname)))
}
}
return
}
}
})
return ts
}
func createFormPatchServer(t *testing.T) *httptest.Server {
ts := createTestServer(func(w http.ResponseWriter, r *http.Request) {
t.Logf("Method: %v", r.Method)
t.Logf("Path: %v", r.URL.Path)
t.Logf("Content-Type: %v", r.Header.Get(hdrContentTypeKey))
if r.Method == MethodPatch {
_ = r.ParseMultipartForm(10e6)
if r.URL.Path == "/upload" {
t.Logf("FirstName: %v", r.FormValue("first_name"))
t.Logf("LastName: %v", r.FormValue("last_name"))
targetPath := filepath.Join(getTestDataPath(), "upload")
_ = os.MkdirAll(targetPath, 0700)
for _, fhdrs := range r.MultipartForm.File {
for _, hdr := range fhdrs {
t.Logf("Name: %v", hdr.Filename)
t.Logf("Header: %v", hdr.Header)
dotPos := strings.LastIndex(hdr.Filename, ".")
fname := fmt.Sprintf("%s-%v%s", hdr.Filename[:dotPos], time.Now().Unix(), hdr.Filename[dotPos:])
t.Logf("Write name: %v", fname)
infile, _ := hdr.Open()
f, err := os.OpenFile(filepath.Join(targetPath, fname), os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
t.Logf("Error: %v", err)
return
}
defer func() {
_ = f.Close()
}()
_, _ = io.Copy(f, infile)
_, _ = w.Write([]byte(fmt.Sprintf("File: %v, uploaded as: %v\n", hdr.Filename, fname)))
}
}
return
}
}
})
return ts
}
func createFilePostServer(t *testing.T) *httptest.Server {
ts := createTestServer(func(w http.ResponseWriter, r *http.Request) {
t.Logf("Method: %v", r.Method)
t.Logf("Path: %v", r.URL.Path)
t.Logf("Content-Type: %v", r.Header.Get(hdrContentTypeKey))
if r.Method != MethodPost {
t.Log("createPostServer:: Not a Post request")
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, http.StatusText(http.StatusBadRequest))
return
}
targetPath := filepath.Join(getTestDataPath(), "upload-large")
_ = os.MkdirAll(targetPath, 0700)
defer cleanupFiles(targetPath)
switch r.URL.Path {
case "/upload":
f, err := os.OpenFile(filepath.Join(targetPath, "large-file.png"),
os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
t.Logf("Error: %v", err)
return
}
defer func() {
_ = f.Close()
}()
size, _ := io.Copy(f, r.Body)
fmt.Fprintf(w, "File Uploaded successfully, file size: %v", size)
case "/set-reset-multipart-readers-test":
w.Header().Set(hdrContentTypeKey, "application/json; charset=utf-8")
w.WriteHeader(http.StatusInternalServerError)
_, _ = fmt.Fprintf(w, `{ "message": "error" }`)
}
})
return ts
}
func createAuthServer(t *testing.T) *httptest.Server {
return createAuthServerTLSOptional(t, true)
}
func createAuthServerTLSOptional(t *testing.T, useTLS bool) *httptest.Server {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Logf("Method: %v", r.Method)
t.Logf("Path: %v", r.URL.Path)
t.Logf("Content-Type: %v", r.Header.Get(hdrContentTypeKey))
if r.Method == MethodGet {
if r.URL.Path == "/profile" {
// 004DDB79-6801-4587-B976-F093E6AC44FF
auth := r.Header.Get("Authorization")
t.Logf("Bearer Auth: %v", auth)
w.Header().Set(hdrContentTypeKey, "application/json; charset=utf-8")
if !strings.HasPrefix(auth, "Bearer ") {
w.Header().Set("Www-Authenticate", "Protected Realm")
w.WriteHeader(http.StatusUnauthorized)
_, _ = w.Write([]byte(`{ "id": "unauthorized", "message": "Invalid credentials" }`))
return
}
if auth[7:] == "004DDB79-6801-4587-B976-F093E6AC44FF" || auth[7:] == "004DDB79-6801-4587-B976-F093E6AC44FF-Request" {
_, _ = w.Write([]byte(`{ "id": "success", "message": "login successful" }`))
}
}
return
}
if r.Method == MethodPost {
if r.URL.Path == "/login" {
auth := r.Header.Get("Authorization")
t.Logf("Basic Auth: %v", auth)
w.Header().Set(hdrContentTypeKey, "application/json; charset=utf-8")
password, err := base64.StdEncoding.DecodeString(auth[6:])
if err != nil || string(password) != "myuser:basicauth" {
w.Header().Set("Www-Authenticate", "Protected Realm")
w.WriteHeader(http.StatusUnauthorized)
_, _ = w.Write([]byte(`{ "id": "unauthorized", "message": "Invalid credentials" }`))
return
}
_, _ = w.Write([]byte(`{ "id": "success", "message": "login successful" }`))
}
return
}
})
if useTLS {
return httptest.NewTLSServer(handler)
}
return httptest.NewServer(handler)
}
func createGenServer(t *testing.T) *httptest.Server {
ts := createTestServer(func(w http.ResponseWriter, r *http.Request) {
t.Logf("Method: %v", r.Method)
t.Logf("Path: %v", r.URL.Path)
if r.Method == MethodGet {
if r.URL.Path == "/json-no-set" {
// Set empty header value for testing, since Go server sets to
// text/plain; charset=utf-8
w.Header().Set(hdrContentTypeKey, "")
_, _ = w.Write([]byte(`{"response":"json response no content type set"}`))
} else if r.URL.Path == "/gzip-test" {
w.Header().Set(hdrContentTypeKey, plainTextType)
w.Header().Set(hdrContentEncodingKey, "gzip")
zw := gzip.NewWriter(w)
_, _ = zw.Write([]byte("This is Gzip response testing"))
zw.Close()
} else if r.URL.Path == "/gzip-test-gziped-empty-body" {
w.Header().Set(hdrContentTypeKey, plainTextType)
w.Header().Set(hdrContentEncodingKey, "gzip")
zw := gzip.NewWriter(w)
// write gziped empty body
_, _ = zw.Write([]byte(""))
zw.Close()
} else if r.URL.Path == "/gzip-test-no-gziped-body" {
w.Header().Set(hdrContentTypeKey, plainTextType)
w.Header().Set(hdrContentEncodingKey, "gzip")
// don't write body
}
return
}
if r.Method == MethodPut {
if r.URL.Path == "/plaintext" {
_, _ = w.Write([]byte("TestPut: plain text response"))
} else if r.URL.Path == "/json" {
w.Header().Set(hdrContentTypeKey, "application/json; charset=utf-8")
_, _ = w.Write([]byte(`{"response":"json response"}`))
} else if r.URL.Path == "/xml" {
w.Header().Set(hdrContentTypeKey, "application/xml")
_, _ = w.Write([]byte(`<?xml version="1.0" encoding="UTF-8"?><Response>XML response</Response>`))
}
return
}
if r.Method == MethodOptions && r.URL.Path == "/options" {
w.Header().Set("Access-Control-Allow-Origin", "localhost")
w.Header().Set("Access-Control-Allow-Methods", "PUT, PATCH")
w.Header().Set("Access-Control-Expose-Headers", "x-go-resty-id")
w.WriteHeader(http.StatusOK)
return
}
if r.Method == MethodPatch && r.URL.Path == "/patch" {
w.WriteHeader(http.StatusOK)
return
}
if r.Method == "REPORT" && r.URL.Path == "/report" {
body, _ := io.ReadAll(r.Body)
if len(body) == 0 {
w.WriteHeader(http.StatusOK)
}
return
}
})
return ts
}
func createRedirectServer(t *testing.T) *httptest.Server {
ts := createTestServer(func(w http.ResponseWriter, r *http.Request) {
t.Logf("Method: %v", r.Method)
t.Logf("Path: %v", r.URL.Path)
if r.Method == MethodGet {
if strings.HasPrefix(r.URL.Path, "/redirect-host-check-") {
cntStr := strings.SplitAfter(r.URL.Path, "-")[3]
cnt, _ := strconv.Atoi(cntStr)
if cnt != 7 { // Testing hard stop via logical
if cnt >= 5 {
http.Redirect(w, r, "http://httpbin.org/get", http.StatusTemporaryRedirect)
} else {
http.Redirect(w, r, fmt.Sprintf("/redirect-host-check-%d", cnt+1), http.StatusTemporaryRedirect)
}
}
} else if strings.HasPrefix(r.URL.Path, "/redirect-") {
cntStr := strings.SplitAfter(r.URL.Path, "-")[1]
cnt, _ := strconv.Atoi(cntStr)
http.Redirect(w, r, fmt.Sprintf("/redirect-%d", cnt+1), http.StatusTemporaryRedirect)
}
}
})
return ts
}
func createUnixSocketEchoServer(t *testing.T) string {
socketPath := filepath.Join(os.TempDir(), strconv.FormatInt(time.Now().Unix(), 10)) + ".sock"
// Create a Unix domain socket and listen for incoming connections.
socket, err := net.Listen("unix", socketPath)
if err != nil {
t.Fatal(err)
}
m := http.NewServeMux()
m.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hi resty client from a server running on Unix domain socket!\n"))
})
m.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello resty client from a server running on endpoint /hello!\n"))
})
go func(t *testing.T) {
server := http.Server{Handler: m}
if err := server.Serve(socket); err != nil {
t.Error(err)
}
}(t)
return socketPath
}
type digestServerConfig struct {
realm, qop, nonce, opaque, algo, uri, charset, username, password string
}
func defaultDigestServerConf() *digestServerConfig {
return &digestServerConfig{
realm: "testrealm@host.com",
qop: "auth",
nonce: "dcd98b7102dd2f0e8b11d0f600bfb0c093",
opaque: "5ccc069c403ebaf9f0171e9517f40e41",
algo: "MD5",
uri: "/dir/index.html",
charset: "utf-8",
username: "Mufasa",
password: "Circle Of Life",
}
}
func createDigestServer(t *testing.T, conf *digestServerConfig) *httptest.Server {
if conf == nil {
conf = defaultDigestServerConf()
}
setWWWAuthHeader := func(w http.ResponseWriter, v string) {
w.Header().Set("WWW-Authenticate", v)
w.WriteHeader(http.StatusUnauthorized)
}
ts := createTestServer(func(w http.ResponseWriter, r *http.Request) {
t.Logf("Method: %v", r.Method)
t.Logf("Path: %v", r.URL.Path)
switch r.URL.Path {
case "/bad":
setWWWAuthHeader(w, "Bad Challenge")
return
case "/unknown_param":
setWWWAuthHeader(w, "Digest unknown_param=true")
return
case "/missing_value":
setWWWAuthHeader(w, `Digest realm="hello", domain`)
return
case "/unclosed_quote":
setWWWAuthHeader(w, `Digest realm="hello, qop=auth`)
return
case "/no_challenge":
setWWWAuthHeader(w, "")
return
case "/status_500":
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set(hdrContentTypeKey, "application/json; charset=utf-8")
if !authorizationHeaderValid(t, r, conf) {
setWWWAuthHeader(w,
fmt.Sprintf(`Digest realm="%s", domain="%s", qop="%s", algorithm=%s, nonce="%s", opaque="%s", userhash=true, charset=%s, stale=FALSE`,
conf.realm, conf.uri, conf.qop, conf.algo, conf.nonce, conf.opaque, conf.charset))
_, _ = w.Write([]byte(`{ "id": "unauthorized", "message": "Invalid credentials" }`))
} else {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{ "id": "success", "message": "login successful" }`))
}
})
return ts
}
func authorizationHeaderValid(t *testing.T, r *http.Request, conf *digestServerConfig) bool {
h := func(data string) (string, error) {
hf := md5.New()
_, err := io.WriteString(hf, data)
if err != nil {
return "", err
}
return fmt.Sprintf("%x", hf.Sum(nil)), nil
}
input := r.Header.Get(hdrAuthorizationKey)
if input == "" {
return false
}
const ws = " \n\r\t"
const qs = `"`
s := strings.Trim(input, ws)
assertEqual(t, true, strings.HasPrefix(s, "Digest "))
s = strings.Trim(s[7:], ws)
sl := strings.Split(s, ", ")
pairs := make(map[string]string, len(sl))
for i := range sl {
pair := strings.SplitN(sl[i], "=", 2)
pairs[pair[0]] = strings.Trim(pair[1], qs)
}
assertEqual(t, conf.opaque, pairs["opaque"])
assertEqual(t, conf.algo, pairs["algorithm"])
assertEqual(t, "true", pairs["userhash"])
userhash, err := h(fmt.Sprintf("%s:%s", conf.username, conf.realm))
assertError(t, err)
assertEqual(t, userhash, pairs["username"])
ha1, err := h(fmt.Sprintf("%s:%s:%s", conf.username, conf.realm, conf.password))
assertError(t, err)
if strings.HasSuffix(conf.algo, "-sess") {
ha1, err = h(fmt.Sprintf("%s:%s:%s", ha1, pairs["nonce"], pairs["cnonce"]))
assertError(t, err)
}
ha2, err := h(fmt.Sprintf("%s:%s", r.Method, conf.uri))
assertError(t, err)
nonceCount, err := strconv.Atoi(pairs["nc"])
assertError(t, err)
kd, err := h(fmt.Sprintf("%s:%s", ha1, fmt.Sprintf("%s:%08x:%s:%s:%s",
pairs["nonce"], nonceCount, pairs["cnonce"], pairs["qop"], ha2)))
assertError(t, err)
return kd == pairs["response"]
}
func createTestServer(fn func(w http.ResponseWriter, r *http.Request)) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(fn))
}
func dc() *Client {
c := New().
outputLogTo(io.Discard)
return c
}
func dcl() *Client {
c := New().
SetDebug(true).
outputLogTo(io.Discard)
return c
}
func dcr() *Request {
return dc().R()
}
func dclr() *Request {
c := dc().
SetDebug(true).
outputLogTo(io.Discard)
return c.R()
}
func assertNil(t *testing.T, v interface{}) {
t.Helper()
if !isNil(v) {
t.Errorf("[%v] was expected to be nil", v)
}
}
func assertNotNil(t *testing.T, v interface{}) {
if isNil(v) {
t.Errorf("[%v] was expected to be non-nil", v)
}
}
func assertType(t *testing.T, typ, v interface{}) {
if reflect.DeepEqual(reflect.TypeOf(typ), reflect.TypeOf(v)) {
t.Errorf("Expected type %t, got %t", typ, v)
}
}
func assertError(t *testing.T, err error) {
if err != nil {
t.Errorf("Error occurred [%v]", err)
}
}
func assertErrorIs(t *testing.T, e, g error) (r bool) {
if !errors.Is(g, e) {
t.Errorf("Expected [%v], got [%v]", e, g)
}
return true
}
func assertEqual(t *testing.T, e, g interface{}) (r bool) {
t.Helper()
if !equal(e, g) {
t.Errorf("Expected [%v], got [%v]", e, g)
}
return
}
func assertNotEqual(t *testing.T, e, g interface{}) (r bool) {
if equal(e, g) {
t.Errorf("Expected [%v], got [%v]", e, g)
} else {
r = true
}
return
}
func equal(expected, got interface{}) bool {
return reflect.DeepEqual(expected, got)
}
func isNil(v interface{}) bool {
if v == nil {
return true
}
rv := reflect.ValueOf(v)
kind := rv.Kind()
if kind >= reflect.Chan && kind <= reflect.Slice && rv.IsNil() {
return true
}
return false
}
func logResponse(t *testing.T, resp *Response) {
t.Logf("Response Status: %v", resp.Status())
t.Logf("Response Time: %v", resp.Time())
t.Logf("Response Headers: %v", resp.Header())
t.Logf("Response Cookies: %v", resp.Cookies())
t.Logf("Response Body: %v", resp)
}
func cleanupFiles(files ...string) {
pwd, _ := os.Getwd()
for _, f := range files {
if filepath.IsAbs(f) {
_ = os.RemoveAll(f)
} else {
_ = os.RemoveAll(filepath.Join(pwd, f))
}
}
}