-
Notifications
You must be signed in to change notification settings - Fork 460
/
stripe_test.go
976 lines (793 loc) · 24.7 KB
/
stripe_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
package stripe
import (
"bytes"
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"net/http/httptest"
"os"
"regexp"
"runtime"
"sync"
"sync/atomic"
"testing"
"time"
assert "github.com/stretchr/testify/require"
)
func TestBearerAuth(t *testing.T) {
c := GetBackend(APIBackend).(*BackendImplementation)
key := "apiKey"
req, err := c.NewRequest("", "", key, "", nil)
assert.NoError(t, err)
assert.Equal(t, "Bearer "+key, req.Header.Get("Authorization"))
}
func TestContext(t *testing.T) {
c := GetBackend(APIBackend).(*BackendImplementation)
p := &Params{Context: context.Background()}
req, err := c.NewRequest("", "", "", "", p)
assert.NoError(t, err)
// We assume that contexts are sufficiently tested in the standard library
// and here we just check that the context sent in to `NewRequest` is
// indeed properly set on the request that's returned.
assert.Equal(t, p.Context, req.Context())
}
// Tests client retries.
//
// You can get pretty good visibility into what's going on by running just this
// test on verbose:
//
// go test . -run TestDo_Retry -test.v
//
func TestDo_Retry(t *testing.T) {
type testServerResponse struct {
APIResource
Message string `json:"message"`
}
message := "Hello, client."
requestNum := 0
testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
assert.NoError(t, err)
// The body should always be the same with every retry. We've
// previously had regressions in this behavior as we switched to HTTP/2
// and `Request` became non-reusable, so we want to check it with every
// request.
assert.Equal(t, "bar", r.Form.Get("foo"))
switch requestNum {
case 0:
w.WriteHeader(http.StatusConflict)
w.Write([]byte(`{"error":"Conflict (this should be retried)."}`))
case 1:
response := testServerResponse{Message: message}
data, err := json.Marshal(response)
assert.NoError(t, err)
_, err = w.Write(data)
assert.NoError(t, err)
default:
assert.Fail(t, "Should not have reached request %v", requestNum)
}
requestNum++
}))
defer testServer.Close()
backend := GetBackendWithConfig(
APIBackend,
&BackendConfig{
LogLevel: 3,
MaxNetworkRetries: 5,
URL: testServer.URL,
},
).(*BackendImplementation)
// Disable sleeping duration our tests.
backend.SetNetworkRetriesSleep(false)
request, err := backend.NewRequest(
http.MethodPost,
"/hello",
"sk_test_123",
"application/x-www-form-urlencoded",
nil,
)
assert.NoError(t, err)
bodyBuffer := bytes.NewBufferString("foo=bar")
var response testServerResponse
err = backend.Do(request, bodyBuffer, &response)
assert.NoError(t, err)
assert.Equal(t, message, response.Message)
// We should have seen exactly two requests.
assert.Equal(t, 2, requestNum)
}
func TestShouldRetry(t *testing.T) {
MaxNetworkRetries := 3
c := GetBackendWithConfig(
APIBackend,
&BackendConfig{
MaxNetworkRetries: MaxNetworkRetries,
},
).(*BackendImplementation)
// Exceeded maximum number of retries
assert.False(t, c.shouldRetry(
nil,
&http.Request{},
&http.Response{},
MaxNetworkRetries,
))
// Doesn't retry most Stripe errors (they must also match a status code
// below to be retried)
assert.False(t, c.shouldRetry(
&Error{Msg: "An error from Stripe"},
&http.Request{},
&http.Response{StatusCode: http.StatusBadRequest},
0,
))
// Currently retries on any non-Stripe error (which we should fix)
assert.True(t, c.shouldRetry(
fmt.Errorf("an error"),
&http.Request{},
nil,
0,
))
// `Stripe-Should-Retry: false`
assert.False(t, c.shouldRetry(
nil,
&http.Request{},
&http.Response{
Header: http.Header(map[string][]string{
"Stripe-Should-Retry": {"false"},
}),
// Note we send status 409 here, which would normally be retried
StatusCode: http.StatusConflict,
},
0,
))
// `Stripe-Should-Retry: true`
assert.True(t, c.shouldRetry(
nil,
&http.Request{},
&http.Response{
Header: http.Header(map[string][]string{
"Stripe-Should-Retry": {"true"},
}),
// Note we send status 400 here, which would normally not be
// retried
StatusCode: http.StatusBadRequest,
},
0,
))
// 409 Conflict
assert.True(t, c.shouldRetry(
nil,
&http.Request{},
&http.Response{StatusCode: http.StatusConflict},
0,
))
// 429 Too Many Requests -- retry on lock timeout
assert.True(t, c.shouldRetry(
&Error{Code: ErrorCodeLockTimeout},
&http.Request{},
&http.Response{StatusCode: http.StatusTooManyRequests},
0,
))
// 429 Too Many Requests -- don't retry normally
assert.False(t, c.shouldRetry(
nil,
&http.Request{},
&http.Response{StatusCode: http.StatusTooManyRequests},
0,
))
// 500 Internal Server Error -- retry if non-POST
assert.True(t, c.shouldRetry(
nil,
&http.Request{Method: http.MethodGet},
&http.Response{StatusCode: http.StatusInternalServerError},
0,
))
// 500 Internal Server Error -- don't retry POST
assert.False(t, c.shouldRetry(
nil,
&http.Request{Method: http.MethodPost},
&http.Response{StatusCode: http.StatusInternalServerError},
0,
))
// 503 Service Unavailable
assert.True(t, c.shouldRetry(
nil,
&http.Request{},
&http.Response{StatusCode: http.StatusServiceUnavailable},
0,
))
}
func TestDo_RetryOnTimeout(t *testing.T) {
type testServerResponse struct {
APIResource
Message string `json:"message"`
}
timeout := time.Second
var counter uint32
testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
atomic.AddUint32(&counter, 1)
time.Sleep(timeout)
}))
defer testServer.Close()
backend := GetBackendWithConfig(
APIBackend,
&BackendConfig{
LogLevel: 3,
MaxNetworkRetries: 1,
URL: testServer.URL,
HTTPClient: &http.Client{Timeout: timeout},
},
).(*BackendImplementation)
backend.SetNetworkRetriesSleep(false)
request, err := backend.NewRequest(
http.MethodPost,
"/hello",
"sk_test_123",
"application/x-www-form-urlencoded",
nil,
)
assert.NoError(t, err)
var body = bytes.NewBufferString("foo=bar")
var response testServerResponse
err = backend.Do(request, body, &response)
assert.Error(t, err)
// timeout should not prevent retry
assert.Equal(t, uint32(2), atomic.LoadUint32(&counter))
}
func TestDo_LastResponsePopulated(t *testing.T) {
type testServerResponse struct {
APIResource
Message string `json:"message"`
}
message := "Hello, client."
expectedResponse := testServerResponse{Message: message}
rawJSON, err := json.Marshal(expectedResponse)
assert.NoError(t, err)
testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Idempotency-Key", "key_123")
w.Header().Set("Other-Header", "other_header")
w.Header().Set("Request-Id", "req_123")
w.WriteHeader(http.StatusCreated)
_, err = w.Write(rawJSON)
assert.NoError(t, err)
}))
defer testServer.Close()
backend := GetBackendWithConfig(
APIBackend,
&BackendConfig{
LogLevel: 3,
MaxNetworkRetries: 0,
URL: testServer.URL,
},
).(*BackendImplementation)
request, err := backend.NewRequest(
http.MethodGet,
"/hello",
"sk_test_123",
"application/x-www-form-urlencoded",
nil,
)
assert.NoError(t, err)
var resource testServerResponse
err = backend.Do(request, nil, &resource)
assert.NoError(t, err)
assert.Equal(t, message, resource.Message)
assert.Equal(t, "key_123", resource.LastResponse.IdempotencyKey)
assert.Equal(t, "other_header", resource.LastResponse.Header.Get("Other-Header"))
assert.Equal(t, rawJSON, resource.LastResponse.RawJSON)
assert.Equal(t, "req_123", resource.LastResponse.RequestID)
assert.Equal(t,
fmt.Sprintf("%v %v", http.StatusCreated, http.StatusText(http.StatusCreated)),
resource.LastResponse.Status)
assert.Equal(t, http.StatusCreated, resource.LastResponse.StatusCode)
}
// Test that telemetry metrics are not sent by default
func TestDo_TelemetryDisabled(t *testing.T) {
type testServerResponse struct {
APIResource
Message string `json:"message"`
}
message := "Hello, client."
requestNum := 0
testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// none of the requests should include telemetry metrics
assert.Equal(t, r.Header.Get("X-Stripe-Client-Telemetry"), "")
response := testServerResponse{Message: message}
data, err := json.Marshal(response)
assert.NoError(t, err)
_, err = w.Write(data)
assert.NoError(t, err)
requestNum++
}))
defer testServer.Close()
backend := GetBackendWithConfig(
APIBackend,
&BackendConfig{
LogLevel: 3,
MaxNetworkRetries: 0,
URL: testServer.URL,
},
).(*BackendImplementation)
// When telemetry is enabled, the metrics for a request are sent with the
// _next_ request via the `X-Stripe-Client-Telemetry header`. To test that
// metrics aren't being sent, we need to fire off two requests in sequence.
for i := 0; i < 2; i++ {
request, err := backend.NewRequest(
http.MethodGet,
"/hello",
"sk_test_123",
"application/x-www-form-urlencoded",
nil,
)
assert.NoError(t, err)
var response testServerResponse
err = backend.Do(request, nil, &response)
assert.NoError(t, err)
assert.Equal(t, message, response.Message)
}
// We should have seen exactly two requests.
assert.Equal(t, 2, requestNum)
}
// Test that telemetry metrics are sent on subsequent requests when
// EnableTelemetry = true.
func TestDo_TelemetryEnabled(t *testing.T) {
type testServerResponse struct {
APIResource
Message string `json:"message"`
}
type requestMetrics struct {
RequestDurationMS int `json:"request_duration_ms"`
RequestID string `json:"request_id"`
}
type requestTelemetry struct {
LastRequestMetrics requestMetrics `json:"last_request_metrics"`
}
message := "Hello, client."
requestNum := 0
testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestNum++
telemetryStr := r.Header.Get("X-Stripe-Client-Telemetry")
switch requestNum {
case 1:
// the first request should not receive any metrics
assert.Equal(t, telemetryStr, "")
time.Sleep(21 * time.Millisecond)
case 2:
assert.True(t, len(telemetryStr) > 0, "telemetryStr should not be empty")
// the telemetry should properly unmarshal into RequestTelemetry
var telemetry requestTelemetry
err := json.Unmarshal([]byte(telemetryStr), &telemetry)
assert.NoError(t, err)
// the second request should include the metrics for the first request
assert.Equal(t, telemetry.LastRequestMetrics.RequestID, "req_1")
assert.True(t, telemetry.LastRequestMetrics.RequestDurationMS > 20,
"request_duration_ms should be > 20ms")
default:
assert.Fail(t, "Should not have reached request %v", requestNum)
}
w.Header().Set("Request-Id", fmt.Sprintf("req_%d", requestNum))
response := testServerResponse{Message: message}
data, err := json.Marshal(response)
assert.NoError(t, err)
_, err = w.Write(data)
assert.NoError(t, err)
}))
defer testServer.Close()
backend := GetBackendWithConfig(
APIBackend,
&BackendConfig{
LogLevel: 3,
MaxNetworkRetries: 0,
URL: testServer.URL,
EnableTelemetry: true,
},
).(*BackendImplementation)
for i := 0; i < 2; i++ {
request, err := backend.NewRequest(
http.MethodGet,
"/hello",
"sk_test_123",
"application/x-www-form-urlencoded",
nil,
)
assert.NoError(t, err)
var response testServerResponse
err = backend.Do(request, nil, &response)
assert.NoError(t, err)
assert.Equal(t, message, response.Message)
}
// We should have seen exactly two requests.
assert.Equal(t, 2, requestNum)
}
// This test does not perform any super valuable assertions - instead, it checks
// that our logic for buffering requestMetrics when EnableTelemetry = true does
// not trigger any data races. This test should pass when the -race flag is
// passed to `go test`.
func TestDo_TelemetryEnabledNoDataRace(t *testing.T) {
type testServerResponse struct {
APIResource
Message string `json:"message"`
}
message := "Hello, client."
var requestNum int32
testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
reqID := atomic.AddInt32(&requestNum, 1)
w.Header().Set("Request-Id", fmt.Sprintf("req_%d", reqID))
response := testServerResponse{Message: message}
data, err := json.Marshal(response)
assert.NoError(t, err)
_, err = w.Write(data)
assert.NoError(t, err)
}))
defer testServer.Close()
backend := GetBackendWithConfig(
APIBackend,
&BackendConfig{
LogLevel: 3,
MaxNetworkRetries: 0,
URL: testServer.URL,
EnableTelemetry: true,
},
).(*BackendImplementation)
times := 20 // 20 > telemetryBufferSize, so some metrics could be discarded
done := make(chan struct{})
for i := 0; i < times; i++ {
go func() {
request, err := backend.NewRequest(
http.MethodGet,
"/hello",
"sk_test_123",
"application/x-www-form-urlencoded",
nil,
)
assert.NoError(t, err)
var response testServerResponse
err = backend.Do(request, nil, &response)
assert.NoError(t, err)
assert.Equal(t, message, response.Message)
done <- struct{}{}
}()
}
for i := 0; i < times; i++ {
<-done
}
assert.Equal(t, int32(times), requestNum)
}
func TestFormatURLPath(t *testing.T) {
assert.Equal(t, "/v1/resources/1/subresources/2",
FormatURLPath("/v1/resources/%s/subresources/%s", "1", "2"))
// Tests that each parameter is escaped for use in URLs
assert.Equal(t, "/v1/resources/%25",
FormatURLPath("/v1/resources/%s", "%"))
}
func TestGetBackendWithConfig_Loggers(t *testing.T) {
leveledLogger := &LeveledLogger{}
logger := log.New(os.Stdout, "", 0)
// Prefers a LeveledLogger
{
backend := GetBackendWithConfig(
APIBackend,
&BackendConfig{
LeveledLogger: leveledLogger,
Logger: logger,
},
).(*BackendImplementation)
assert.Equal(t, leveledLogger, backend.LeveledLogger)
}
// Falls back to Logger
{
backend := GetBackendWithConfig(
APIBackend,
&BackendConfig{
Logger: logger,
},
).(*BackendImplementation)
assert.NotNil(t, backend.LeveledLogger)
}
}
func TestGetBackendWithConfig_TrimV1Suffix(t *testing.T) {
{
backend := GetBackendWithConfig(
APIBackend,
&BackendConfig{
URL: "https://api.com/v1",
},
).(*BackendImplementation)
// The `/v1` suffix has been stripped.
assert.Equal(t, "https://api.com", backend.URL)
}
// Also support trimming a `/v1/` with an extra trailing slash which is
// probably an often seen mistake.
{
backend := GetBackendWithConfig(
APIBackend,
&BackendConfig{
URL: "https://api.com/v1/",
},
).(*BackendImplementation)
assert.Equal(t, "https://api.com", backend.URL)
}
// No-op otherwise.
{
backend := GetBackendWithConfig(
APIBackend,
&BackendConfig{
URL: "https://api.com",
},
).(*BackendImplementation)
assert.Equal(t, "https://api.com", backend.URL)
}
}
func TestParseID(t *testing.T) {
// JSON string
{
id, ok := ParseID([]byte(`"ch_123"`))
assert.Equal(t, "ch_123", id)
assert.True(t, ok)
}
// JSON object
{
id, ok := ParseID([]byte(`{"id":"ch_123"}`))
assert.Equal(t, "", id)
assert.False(t, ok)
}
// Other JSON scalar (this should never be used, but check the results anyway)
{
id, ok := ParseID([]byte(`123`))
assert.Equal(t, "", id)
assert.False(t, ok)
}
}
// TestMultipleAPICalls will fail the test run if a race condition is thrown while running multiple NewRequest calls.
func TestMultipleAPICalls(t *testing.T) {
wg := &sync.WaitGroup{}
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
c := GetBackend(APIBackend).(*BackendImplementation)
key := "apiKey"
req, err := c.NewRequest("", "", key, "", nil)
assert.NoError(t, err)
assert.Equal(t, "Bearer "+key, req.Header.Get("Authorization"))
}()
}
wg.Wait()
}
func TestIdempotencyKey(t *testing.T) {
c := GetBackend(APIBackend).(*BackendImplementation)
p := &Params{IdempotencyKey: String("idempotency-key")}
req, err := c.NewRequest("", "", "", "", p)
assert.NoError(t, err)
assert.Equal(t, "idempotency-key", req.Header.Get("Idempotency-Key"))
}
func TestNewBackends(t *testing.T) {
httpClient := &http.Client{}
backends := NewBackends(httpClient)
assert.Equal(t, httpClient, backends.API.(*BackendImplementation).HTTPClient)
assert.Equal(t, httpClient, backends.Uploads.(*BackendImplementation).HTTPClient)
}
func TestStripeAccount(t *testing.T) {
c := GetBackend(APIBackend).(*BackendImplementation)
p := &Params{}
p.SetStripeAccount("acct_123")
req, err := c.NewRequest("", "", "", "", p)
assert.NoError(t, err)
assert.Equal(t, "acct_123", req.Header.Get("Stripe-Account"))
}
func TestUnmarshalJSONVerbose(t *testing.T) {
type testServerResponse struct {
Message string `json:"message"`
}
backend := GetBackend(APIBackend).(*BackendImplementation)
// Valid JSON
{
type testServerResponse struct {
Message string `json:"message"`
}
var sample testServerResponse
err := backend.UnmarshalJSONVerbose(200, []byte(`{"message":"hello"}`), &sample)
assert.NoError(t, err)
assert.Equal(t, "hello", sample.Message)
}
// Invalid JSON (short)
{
body := `server error`
var sample testServerResponse
err := backend.UnmarshalJSONVerbose(200, []byte(body), &sample)
assert.Regexp(t,
fmt.Sprintf(`^Couldn't deserialize JSON \(response status: 200, body sample: '%s'\): invalid character`, body),
err)
}
// Invalid JSON (long, and therefore truncated)
{
// Assembles a body that's at least as long as our maximum sample.
// body is ~130 characters * 5.
bodyText := `this is a really long body that will be truncated when added to the error message to protect against dumping huge responses in logs `
body := bodyText + bodyText + bodyText + bodyText + bodyText
var sample testServerResponse
err := backend.UnmarshalJSONVerbose(200, []byte(body), &sample)
assert.Regexp(t,
fmt.Sprintf(`^Couldn't deserialize JSON \(response status: 200, body sample: '%s ...'\): invalid character`, body[0:500]),
err)
}
}
func TestUserAgent(t *testing.T) {
c := GetBackend(APIBackend).(*BackendImplementation)
req, err := c.NewRequest("", "", "", "", nil)
assert.NoError(t, err)
// We keep out version constant private to the package, so use a regexp
// match instead.
expectedPattern := regexp.MustCompile(`^Stripe/v1 GoBindings/[1-9][0-9.]+[0-9]$`)
match := expectedPattern.MatchString(req.Header.Get("User-Agent"))
assert.True(t, match)
}
func TestUserAgentWithAppInfo(t *testing.T) {
appInfo := &AppInfo{
Name: "MyAwesomePlugin",
PartnerID: "partner_1234",
URL: "https://myawesomeplugin.info",
Version: "1.2.34",
}
SetAppInfo(appInfo)
defer SetAppInfo(nil)
c := GetBackend(APIBackend).(*BackendImplementation)
req, err := c.NewRequest("", "", "", "", nil)
assert.NoError(t, err)
//
// User-Agent
//
// We keep out version constant private to the package, so use a regexp
// match instead.
expectedPattern := regexp.MustCompile(`^Stripe/v1 GoBindings/[1-9][0-9.]+[0-9] MyAwesomePlugin/1.2.34 \(https://myawesomeplugin.info\)$`)
match := expectedPattern.MatchString(req.Header.Get("User-Agent"))
assert.True(t, match)
//
// X-Stripe-Client-User-Agent
//
encodedUserAgent := req.Header.Get("X-Stripe-Client-User-Agent")
assert.NotEmpty(t, encodedUserAgent)
var userAgent map[string]interface{}
err = json.Unmarshal([]byte(encodedUserAgent), &userAgent)
assert.NoError(t, err)
application := userAgent["application"].(map[string]interface{})
assert.Equal(t, "MyAwesomePlugin", application["name"])
assert.Equal(t, "partner_1234", application["partner_id"])
assert.Equal(t, "https://myawesomeplugin.info", application["url"])
assert.Equal(t, "1.2.34", application["version"])
}
func TestStripeClientUserAgent(t *testing.T) {
c := GetBackend(APIBackend).(*BackendImplementation)
req, err := c.NewRequest("", "", "", "", nil)
assert.NoError(t, err)
encodedUserAgent := req.Header.Get("X-Stripe-Client-User-Agent")
assert.NotEmpty(t, encodedUserAgent)
var userAgent map[string]string
err = json.Unmarshal([]byte(encodedUserAgent), &userAgent)
assert.NoError(t, err)
//
// Just test a few headers that we know to be stable.
//
assert.Empty(t, userAgent["application"])
assert.Equal(t, "go", userAgent["lang"])
assert.Equal(t, runtime.Version(), userAgent["lang_version"])
// Anywhere these tests are running can reasonable be expected to have a
// `uname` to run, so do this basic check.
assert.NotEqual(t, UnknownPlatform, userAgent["lang_version"])
}
func TestStripeClientUserAgentWithAppInfo(t *testing.T) {
appInfo := &AppInfo{
Name: "MyAwesomePlugin",
URL: "https://myawesomeplugin.info",
Version: "1.2.34",
}
SetAppInfo(appInfo)
defer SetAppInfo(nil)
c := GetBackend(APIBackend).(*BackendImplementation)
req, err := c.NewRequest("", "", "", "", nil)
assert.NoError(t, err)
encodedUserAgent := req.Header.Get("X-Stripe-Client-User-Agent")
assert.NotEmpty(t, encodedUserAgent)
var userAgent map[string]interface{}
err = json.Unmarshal([]byte(encodedUserAgent), &userAgent)
assert.NoError(t, err)
decodedAppInfo := userAgent["application"].(map[string]interface{})
assert.Equal(t, appInfo.Name, decodedAppInfo["name"])
assert.Equal(t, appInfo.URL, decodedAppInfo["url"])
assert.Equal(t, appInfo.Version, decodedAppInfo["version"])
}
func TestResponseToError(t *testing.T) {
c := GetBackend(APIBackend).(*BackendImplementation)
// A test response that includes a status code and request ID.
res := &http.Response{
Header: http.Header{
"Request-Id": []string{"request-id"},
},
StatusCode: 402,
}
// An error that contains expected fields which we're going to serialize to
// JSON and inject into our conversion function.
expectedErr := &Error{
Code: ErrorCodeMissing,
Msg: "That card was declined",
Param: "expiry_date",
Type: ErrorTypeCard,
}
bytes, err := json.Marshal(expectedErr)
assert.NoError(t, err)
// Unpack the error that we just serialized so that we can inject a
// type-specific field into it ("decline_code"). This will show up in a
// field on a special CardError type which is attached to the common
// Error.
var raw map[string]string
err = json.Unmarshal(bytes, &raw)
assert.NoError(t, err)
expectedDeclineCode := DeclineCodeInvalidCVC
raw["decline_code"] = string(expectedDeclineCode)
bytes, err = json.Marshal(raw)
assert.NoError(t, err)
// A generic Golang error.
err = c.ResponseToError(res, wrapError(bytes))
// An error containing Stripe-specific fields that we cast back from the
// generic Golang error.
stripeErr := err.(*Error)
assert.Equal(t, expectedErr.Code, stripeErr.Code)
assert.Equal(t, expectedErr.Msg, stripeErr.Msg)
assert.Equal(t, expectedErr.Param, stripeErr.Param)
assert.Equal(t, res.Header.Get("Request-Id"), stripeErr.RequestID)
assert.Equal(t, res.StatusCode, stripeErr.HTTPStatusCode)
assert.Equal(t, expectedErr.Type, stripeErr.Type)
// Not exhaustive, but verify LastResponse is basically working as
// expected.
assert.Equal(t, res.Header.Get("Request-Id"), stripeErr.LastResponse.RequestID)
assert.Equal(t, res.StatusCode, stripeErr.LastResponse.StatusCode)
// Just a bogus type coercion to demonstrate how this code might be
// written. Because we've assigned ErrorTypeCard as the error's type, Err
// should always come out as a CardError.
_, ok := stripeErr.Err.(*InvalidRequestError)
assert.False(t, ok)
cardErr, ok := stripeErr.Err.(*CardError)
assert.True(t, ok)
assert.Equal(t, expectedDeclineCode, cardErr.DeclineCode)
}
func TestStringSlice(t *testing.T) {
input := []string{"a", "b", "c"}
result := StringSlice(input)
assert.Equal(t, "a", *result[0])
assert.Equal(t, "b", *result[1])
assert.Equal(t, "c", *result[2])
assert.Equal(t, 0, len(StringSlice(nil)))
}
func TestInt64Slice(t *testing.T) {
input := []int64{8, 7, 6}
result := Int64Slice(input)
assert.Equal(t, int64(8), *result[0])
assert.Equal(t, int64(7), *result[1])
assert.Equal(t, int64(6), *result[2])
assert.Equal(t, 0, len(Int64Slice(nil)))
}
func TestFloat64Slice(t *testing.T) {
input := []float64{8, 7, 6}
result := Float64Slice(input)
assert.Equal(t, float64(8), *result[0])
assert.Equal(t, float64(7), *result[1])
assert.Equal(t, float64(6), *result[2])
assert.Equal(t, 0, len(Float64Slice(nil)))
}
func TestBoolSlice(t *testing.T) {
input := []bool{true, false, true, false}
result := BoolSlice(input)
assert.Equal(t, true, *result[0])
assert.Equal(t, false, *result[1])
assert.Equal(t, true, *result[2])
assert.Equal(t, false, *result[3])
assert.Equal(t, 0, len(BoolSlice(nil)))
}
//
// ---
//
// A simple function that allows us to represent an error response from Stripe
// which comes wrapper in a JSON object with a single field of "error".
func wrapError(serialized []byte) []byte {
return []byte(`{"error":` + string(serialized) + `}`)
}