forked from PagerDuty/go-pagerduty
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client_test.go
944 lines (816 loc) · 20.6 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
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
package pagerduty
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"runtime"
"strings"
"sync/atomic"
"testing"
"github.com/google/go-cmp/cmp"
)
var (
// mux is the HTTP request multiplexer used with the test server.
mux *http.ServeMux
// client is the PagerDuty client being tested.
client *Client
// server is a test HTTP server used to provide mock API responses.
server *httptest.Server
)
func setup() {
mux = http.NewServeMux()
server = httptest.NewServer(mux)
authToken := "foo"
client = NewClient(authToken)
}
func teardown() {
server.Close()
}
func defaultTestClient(serverURL, authToken string) *Client {
return &Client{
v2EventsAPIEndpoint: serverURL,
apiEndpoint: serverURL,
authToken: authToken,
HTTPClient: defaultHTTPClient,
debugFlag: new(uint64),
lastRequest: &atomic.Value{},
lastResponse: &atomic.Value{},
retryPolicy: defaultRetryPolicy,
}
}
func testMethod(t *testing.T, r *http.Request, want string) {
t.Helper()
if got := r.Method; got != want {
t.Errorf("Request method: %v, want %v", got, want)
}
}
func testEqual(t *testing.T, want interface{}, got interface{}) {
t.Helper()
if diff := cmp.Diff(want, got); diff != "" {
t.Errorf("values not equal (-want / +got):\n%s", diff)
}
}
// testErrCheck looks to see if errContains is a substring of err.Error(). If
// not, this calls t.Fatal(). It also calls t.Fatal() if there was an error, but
// errContains is empty. Returns true if you should continue running the test,
// or false if you should stop the test.
func testErrCheck(t *testing.T, name string, errContains string, err error) bool {
t.Helper()
if len(errContains) > 0 {
if err == nil {
t.Fatalf("%s error = <nil>, should contain %q", name, errContains)
return false
}
if errStr := err.Error(); !strings.Contains(errStr, errContains) {
t.Fatalf("%s error = %q, should contain %q", name, errStr, errContains)
return false
}
return false
}
if err != nil && len(errContains) == 0 {
t.Fatalf("%s unexpected error: %v", name, err)
return false
}
return true
}
func TestGetBasePrefix(t *testing.T) {
testTable := []struct {
in string
out string
}{
{"base.com/noparams", "base.com/noparams?"},
{"base.com/?/noparams", "base.com/?/noparams?"},
{"base.com/params?value=1", "base.com/params?value=1&"},
{"base.com/?/params?value=1", "base.com/?/params?value=1&"},
{"noslashes", "noslashes?"}, // this is what it will do... tbd what it should actually do
}
for _, tt := range testTable {
s := getBasePrefix(tt.in)
if s != tt.out {
t.Errorf("got %q, want %q", s, tt.out)
}
}
}
func TestAPIError_Error(t *testing.T) {
t.Run("json_tests", func(t *testing.T) {
tests := []struct {
name string
input string
want string
}{
{
name: "one_error",
input: `{"error":{"code": 420, "message": "Enhance Your Calm", "errors":["No Seriously, Enhance Your Calm"]}}`,
want: "HTTP response failed with status code 429, message: Enhance Your Calm (code: 420): No Seriously, Enhance Your Calm",
},
{
name: "two_error",
input: `{"error":{"code": 420, "message": "Enhance Your Calm", "errors":["No Seriously, Enhance Your Calm", "Slow Your Roll"]}}`,
want: "HTTP response failed with status code 429, message: Enhance Your Calm (code: 420): No Seriously, Enhance Your Calm (and 1 more error...)",
},
{
name: "three_error",
input: `{"error":{"code": 420, "message": "Enhance Your Calm", "errors":["No Seriously, Enhance Your Calm", "Slow Your Roll", "No, really..."]}}`,
want: "HTTP response failed with status code 429, message: Enhance Your Calm (code: 420): No Seriously, Enhance Your Calm (and 2 more errors...)",
},
{
name: "issue_478",
input: `{"error":["links should have at most 50 item(s)"]}`,
want: "HTTP response failed with status code 429, message: none (code: 0): links should have at most 50 item(s)",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var a APIError
if err := json.Unmarshal([]byte(tt.input), &a); err != nil {
t.Fatalf("failed to unmarshal JSON: %s", err)
}
a.StatusCode = 429
if got := a.Error(); got != tt.want {
t.Errorf("a.Error() = %q, want %q", got, tt.want)
}
})
}
})
tests := []struct {
name string
a APIError
want string
}{
{
name: "message",
a: APIError{
message: "test message",
},
want: "test message",
},
{
name: "APIError_nil",
a: APIError{
StatusCode: http.StatusServiceUnavailable,
},
want: "HTTP response failed with status code 503 and no JSON error object was present",
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
if got := tt.a.Error(); got != tt.want {
fmt.Println(got)
fmt.Println(tt.want)
t.Fatalf("tt.a.Error() = %q, want %q", got, tt.want)
}
})
}
}
func TestAPIError_RateLimited(t *testing.T) {
tests := []struct {
name string
a APIError
want bool
}{
{
name: "rate_limited",
a: APIError{
StatusCode: http.StatusTooManyRequests,
APIError: NullAPIErrorObject{
Valid: true,
ErrorObject: APIErrorObject{
Code: 420,
Message: "Enhance Your Calm",
Errors: []string{"Enhance Your Calm"},
},
},
},
want: true,
},
{
name: "not_found",
a: APIError{
StatusCode: http.StatusNotFound,
APIError: NullAPIErrorObject{
Valid: true,
ErrorObject: APIErrorObject{
Code: 2100,
Message: "Not Found",
Errors: []string{"Not Found"},
},
},
},
want: false,
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
if got := tt.a.RateLimited(); got != tt.want {
t.Fatalf("tt.a.RateLimited() = %t, want %t", got, tt.want)
}
})
}
}
func TestAPIError_Temporary(t *testing.T) {
tests := []struct {
name string
a APIError
want bool
}{
{
name: "rate_limited",
a: APIError{
StatusCode: http.StatusTooManyRequests,
APIError: NullAPIErrorObject{
Valid: true,
ErrorObject: APIErrorObject{
Code: 420,
Message: "Enhance Your Calm",
Errors: []string{"Enhance Your Calm"},
},
},
},
want: true,
},
{
name: "not_found",
a: APIError{
StatusCode: http.StatusNotFound,
APIError: NullAPIErrorObject{
Valid: true,
ErrorObject: APIErrorObject{
Code: 2100,
Message: "Not Found",
Errors: []string{"Not Found"},
},
},
},
want: false,
},
{
name: "InternalServerError",
a: APIError{
StatusCode: http.StatusInternalServerError,
},
want: true,
},
{
name: "ServiceUnavailable",
a: APIError{
StatusCode: http.StatusServiceUnavailable,
},
want: true,
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
if got := tt.a.Temporary(); got != tt.want {
t.Fatalf("tt.a.Temporary() = %t, want %t", got, tt.want)
}
})
}
}
func TestAPIError_NotFound(t *testing.T) {
tests := []struct {
name string
a APIError
want bool
}{
{
name: "rate_limited",
a: APIError{
StatusCode: http.StatusTooManyRequests,
APIError: NullAPIErrorObject{
Valid: true,
ErrorObject: APIErrorObject{
Code: 420,
Message: "Enhance Your Calm",
Errors: []string{"Enhance Your Calm"},
},
},
},
want: false,
},
{
name: "not_found",
a: APIError{
StatusCode: http.StatusNotFound,
APIError: NullAPIErrorObject{
Valid: true,
ErrorObject: APIErrorObject{
Code: 2100,
Message: "Not Found",
Errors: []string{"Not Found"},
},
},
},
want: true,
},
{
name: "not_found_weird_status",
a: APIError{
StatusCode: http.StatusBadRequest,
APIError: NullAPIErrorObject{
Valid: true,
ErrorObject: APIErrorObject{
Code: 2100,
Message: "Not Found",
Errors: []string{"Not Found"},
},
},
},
want: true,
},
{
name: "not_found_weird_error_code",
a: APIError{
StatusCode: http.StatusNotFound,
APIError: NullAPIErrorObject{
ErrorObject: APIErrorObject{
Code: 2101,
Message: "Not Found",
Errors: []string{"Not Found"},
},
},
},
want: true,
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
if got := tt.a.NotFound(); got != tt.want {
t.Fatalf("tt.a.NotFound() = %t, want %t", got, tt.want)
}
})
}
}
func TestClient_SetDebugFlag(t *testing.T) {
c := defaultTestClient("", "")
c.SetDebugFlag(42)
tests := []struct {
name string
flag DebugFlag
}{
{
name: "zero_flag",
},
{
name: "capture_response_flag",
flag: DebugCaptureLastResponse,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c.SetDebugFlag(tt.flag)
got := atomic.LoadUint64(c.debugFlag)
if got != uint64(tt.flag) {
t.Fatalf("got = %64b, want = %64b", got, tt.flag)
}
})
}
}
func TestClient_LastAPIRequest(t *testing.T) {
t.Run("unit", func(t *testing.T) {
c := defaultTestClient("", "")
got, ok := c.LastAPIRequest()
if ok {
t.Fatal("new client ok = true, want false")
}
if got != nil {
t.Fatal("got != nil")
}
tests := []struct {
name string
req *http.Request
ok bool
}{
{
name: "nil_response",
},
{
name: "non-nil_response",
req: &http.Request{},
ok: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c.lastRequest.Store(tt.req)
got, ok = c.LastAPIRequest()
if ok != tt.ok {
t.Fatalf("ok = %t, want %t", ok, tt.ok)
}
if !ok {
if got != nil {
t.Fatal("got != nil")
}
return
}
if got != tt.req {
t.Fatalf("got = %v, want %v", got, tt.req)
}
})
}
})
t.Run("integration", func(t *testing.T) {
const requestBody = `{"user":{"id":"1","name":"","email":"[email protected]"}}`
setup()
defer teardown()
mux.HandleFunc("/users/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, http.MethodPut)
_, _ = w.Write([]byte(`{"user": {"id": "1", "email":"[email protected]"}}`))
})
c := defaultTestClient(server.URL, "foo")
c.SetDebugFlag(DebugCaptureLastRequest)
_, err := c.UpdateUserWithContext(context.Background(), User{
APIObject: APIObject{
ID: "1",
},
Email: "[email protected]",
})
testErrCheck(t, "c.UpdateUserWithContext()", "", err)
got, ok := c.LastAPIRequest()
if !ok {
t.Fatal("ok = false, want true")
}
if got == nil {
t.Fatal("got == nil")
}
if got.Method != http.MethodPut {
t.Fatalf("got.Method = %s, want %s", got.Method, http.MethodPut)
}
body, err := ioutil.ReadAll(got.Body)
testErrCheck(t, "ioutil.ReadAll()", "", err)
if jb := string(body); jb != requestBody {
t.Fatalf("got.Body = %q, want %q", jb, requestBody)
}
})
}
func TestClient_LastAPIResponse(t *testing.T) {
t.Run("unit", func(t *testing.T) {
c := defaultTestClient("", "")
got, ok := c.LastAPIResponse()
if ok {
t.Fatal("new client ok = true, want false")
}
if got != nil {
t.Fatal("got != nil")
}
tests := []struct {
name string
resp *http.Response
ok bool
}{
{
name: "nil_response",
},
{
name: "non-nil_response",
resp: &http.Response{},
ok: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c.lastResponse.Store(tt.resp)
got, ok = c.LastAPIResponse()
if ok != tt.ok {
t.Fatalf("ok = %t, want %t", ok, tt.ok)
}
if !ok {
if got != nil {
t.Fatal("got != nil")
}
return
}
if got != tt.resp {
t.Fatalf("got = %v, want %v", got, tt.resp)
}
})
}
})
t.Run("integration", func(t *testing.T) {
const responseBody = `{"user": {"id": "1", "email":"[email protected]"}}`
setup()
defer teardown()
mux.HandleFunc("/users/1", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, http.MethodGet)
_, _ = w.Write([]byte(responseBody))
})
c := defaultTestClient(server.URL, "foo")
c.SetDebugFlag(DebugCaptureLastResponse)
_, err := c.GetUser("1", GetUserOptions{})
testErrCheck(t, "c.GetUser()", "", err)
got, ok := c.LastAPIResponse()
if !ok {
t.Fatal("ok = false, want true")
}
if got == nil {
t.Fatal("got == nil")
}
if got.StatusCode != 200 {
t.Errorf("got.StatusCode = %d, want 200", got.StatusCode)
}
body, err := ioutil.ReadAll(got.Body)
testErrCheck(t, "ioutil.ReadAll()", "", err)
if jb := string(body); jb != responseBody {
t.Fatalf("got.Body = %q, want %q", jb, responseBody)
}
})
}
func clientDoHandler(t *testing.T, needsAuth bool) func(w http.ResponseWriter, r *http.Request) {
t.Helper()
return func(w http.ResponseWriter, r *http.Request) {
t.Helper()
testMethod(t, r, http.MethodPost)
auth := r.Header.Get("Authorization")
if needsAuth && auth != "Token token=foo" {
_, _ = w.Write([]byte("badAuth"))
w.WriteHeader(http.StatusUnauthorized)
return
}
if !needsAuth && len(auth) > 0 {
_, _ = w.Write([]byte("Authentication header should not be provided"))
w.WriteHeader(http.StatusBadRequest)
return
}
if accept := r.Header.Get("Accept"); accept != acceptHeader {
_, _ = w.Write([]byte(fmt.Sprintf("%q Accept unexpected", accept)))
w.WriteHeader(http.StatusNotAcceptable)
return
}
if ua := r.Header.Get("User-Agent"); ua != userAgentHeader {
_, _ = w.Write([]byte(fmt.Sprintf("%q User-Agent unexpected", ua)))
w.WriteHeader(http.StatusBadRequest)
return
}
if ct := r.Header.Get("Content-Type"); ct != contentTypeHeader {
_, _ = w.Write([]byte(fmt.Sprintf("%q Content-Type unexpected", ct)))
w.WriteHeader(http.StatusUnsupportedMediaType)
return
}
_, _ = w.Write([]byte("ok"))
}
}
func TestClient_Do(t *testing.T) {
c := defaultTestClient(server.URL, "foo")
tests := []struct {
name string
auth bool
}{
{
name: "no_auth",
auth: false,
},
{
name: "auth",
auth: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
setup()
defer teardown()
mux.HandleFunc("/test", clientDoHandler(t, tt.auth))
req, err := http.NewRequest(http.MethodPost, server.URL+"/test", strings.NewReader(`{"empty":"object"}`))
testErrCheck(t, "http.NewRequest()", "", err)
resp, err := c.Do(req, tt.auth)
testErrCheck(t, "c.Do()", "", err)
defer func() {
_, _ = io.Copy(ioutil.Discard, resp.Body)
_ = resp.Body.Close()
}()
body, err := ioutil.ReadAll(resp.Body)
testErrCheck(t, "ioutil.ReadAll()", "", err)
if resp.StatusCode != 200 {
t.Fatalf("request failed with status %q: %s", resp.Status, string(body))
}
if bs := string(body); bs != "ok" {
t.Fatalf("body = %s, want ok", bs)
}
})
}
}
func TestClient_RetriesHandleRequestBodies(t *testing.T) {
setup()
defer teardown()
attempt := 1
mux.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
_, err := io.Copy(io.Discard, r.Body)
if err != nil {
t.Fatalf("expected no error, got %v", err)
}
if attempt == 1 {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusTooManyRequests)
w.Write([]byte(`{"empty":"object"}`))
attempt++
} else {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
w.Write([]byte(`{"empty":"object"}`))
}
})
client := NewClient("foo",
WithAPIEndpoint(server.URL),
WithRetryPolicy(2, 1),
)
_, err := client.do(context.Background(), "POST", "/test", strings.NewReader("some data\n"), nil)
if err != nil {
t.Fatalf("expected no error, got %v", err)
}
if attempt < 2 {
t.Fatalf("expected 2 attempts, got %d", attempt)
}
}
func TestClient_RetriesOnVariousConditions(t *testing.T) {
tests := []struct {
name string
status int
expectedAttempts int
}{
{
name: "rate_limited",
status: http.StatusTooManyRequests,
expectedAttempts: 3,
},
{
name: "server_error",
status: http.StatusInternalServerError,
expectedAttempts: 3,
},
{
name: "bad_request",
status: http.StatusBadRequest,
expectedAttempts: 1,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
setup()
defer teardown()
c := NewClient("foo",
WithAPIEndpoint(server.URL),
WithRetryPolicy(2, 1),
)
attempt := 0
mux.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
attempt++
defer r.Body.Close()
_, err := io.Copy(io.Discard, r.Body)
if err != nil {
t.Fatalf("expected no error, got %v", err)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(tt.status)
w.Write([]byte(`{"empty":"object"}`))
})
resp, err := c.do(context.Background(), "GET", "/test", nil, nil)
testErrCheck(t, "client.do()", "response failed with status code", err)
defer resp.Body.Close()
_, _ = io.Copy(io.Discard, resp.Body)
if attempt != tt.expectedAttempts {
t.Fatalf("expected %d attempts, got %d", tt.expectedAttempts, attempt)
}
})
}
}
func TestClient_UserAgentDefault(t *testing.T) {
setup()
defer teardown()
defaultUserAgent := userAgentHeader
mux.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
userAgentHeader := r.Header.Get("User-Agent")
if userAgentHeader != defaultUserAgent {
t.Fatalf("want %q, but got %q", defaultUserAgent, userAgentHeader)
}
w.WriteHeader(http.StatusOK)
})
client := defaultTestClient(server.URL, "foo")
_, err := client.do(context.Background(), "GET", "/foo", nil, nil)
if err != nil {
t.Fatal(err)
}
}
func TestClient_UserAgentOverwrite(t *testing.T) {
setup()
defer teardown()
terraformVersion := "terraform-version-for-testing"
newUserAgent := fmt.Sprintf("(%s %s) Terraform/%s", runtime.GOOS, runtime.GOARCH, terraformVersion)
mux.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
userAgentHeader := r.Header.Get("User-Agent")
if userAgentHeader != newUserAgent {
t.Fatalf("want %q, but got %q", newUserAgent, userAgentHeader)
}
w.WriteHeader(http.StatusOK)
})
client := NewClient("foo",
WithAPIEndpoint(server.URL),
WithTerraformProvider(terraformVersion),
)
_, err := client.do(context.Background(), "GET", "/foo", nil, nil)
if err != nil {
t.Fatal(err)
}
}
func TestNullAPIErrorObject_UnmarshalJSON(t *testing.T) {
tests := []struct {
name string
json string
err string
want *NullAPIErrorObject
}{
{
name: "error_per_api_spec",
json: `{"code":42,"message":"test message","errors":["first error","second error"]}`,
want: &NullAPIErrorObject{
Valid: true,
ErrorObject: APIErrorObject{
Code: 42,
Message: "test message",
Errors: []string{
"first error",
"second error",
},
},
},
},
{
name: "issue_339",
json: `{"code":84,"message":"other message","errors":"only error"}`,
want: &NullAPIErrorObject{
Valid: true,
ErrorObject: APIErrorObject{
Code: 84,
Message: "other message",
Errors: []string{
"only error",
},
},
},
},
{
name: "returns_type_errors",
json: `{"code":"42","message":"test message","errors":"first error"}`,
err: "json: cannot unmarshal string into Go struct field APIErrorObject.code of type int",
},
{
name: "returns_syntax_errors",
json: `}`,
err: "invalid character '}' looking for beginning of value",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := &NullAPIErrorObject{}
err := json.Unmarshal([]byte(tt.json), &got)
if !testErrCheck(t, "*NullAPIErrorObject.UnmarshalJSON()", tt.err, err) {
return
}
testEqual(t, tt.want, got)
})
}
}
func Test_dupeRequest(t *testing.T) {
reqA, _ := http.NewRequest(http.MethodGet, "http://localhost/api/v1/foo", strings.NewReader("some data\n"))
reqB, _ := http.NewRequest(http.MethodGet, "http://localhost/api/v1/foo", nil)
tests := []struct {
name string
req *http.Request
}{
{
name: "ok",
req: reqA,
},
{
name: "ok_nil_body",
req: reqB,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotr, err := dupeRequest(tt.req)
testErrCheck(t, "dupeRequest()", "", err)
var gotb, wantb []byte
if gotr.Body != nil {
gotb, err = ioutil.ReadAll(gotr.Body)
testErrCheck(t, "ioutil.ReadAll(gotr.Body)", "", err)
}
if tt.req.Body != nil {
wantb, err = ioutil.ReadAll(tt.req.Body)
testErrCheck(t, "ioutil.ReadAll(tt.req.Body)", "", err)
}
if !bytes.Equal(gotb, wantb) {
t.Fatalf("gotb = %q, want %q", gotb, wantb)
}
})
}
}