-
Notifications
You must be signed in to change notification settings - Fork 463
/
stripe_test.go
668 lines (532 loc) · 17.5 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
package stripe_test
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"regexp"
"runtime"
"sync"
"sync/atomic"
"testing"
"time"
assert "github.com/stretchr/testify/require"
"github.com/stripe/stripe-go"
. "github.com/stripe/stripe-go/testing"
)
func TestBearerAuth(t *testing.T) {
c := stripe.GetBackend(stripe.APIBackend).(*stripe.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 := stripe.GetBackend(stripe.APIBackend).(*stripe.BackendImplementation)
p := &stripe.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 {
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 := stripe.GetBackendWithConfig(
stripe.APIBackend,
&stripe.BackendConfig{
LogLevel: 3,
MaxNetworkRetries: 5,
URL: testServer.URL,
},
).(*stripe.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 TestDo_RetryOnTimeout(t *testing.T) {
type testServerResponse struct {
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 := stripe.GetBackendWithConfig(
stripe.APIBackend,
&stripe.BackendConfig{
LogLevel: 3,
MaxNetworkRetries: 1,
URL: testServer.URL,
HTTPClient: &http.Client{Timeout: timeout},
},
).(*stripe.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))
}
// Test that telemetry metrics are not sent by default
func TestDo_TelemetryDisabled(t *testing.T) {
type testServerResponse struct {
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 := stripe.GetBackendWithConfig(
stripe.APIBackend,
&stripe.BackendConfig{
LogLevel: 3,
MaxNetworkRetries: 0,
URL: testServer.URL,
},
).(*stripe.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)
}
// Test that telemetry metrics are sent on subsequent requests when
// stripe.EnableTelemetry = true.
func TestDo_TelemetryEnabled(t *testing.T) {
type testServerResponse struct {
Message string `json:"message"`
}
type requestMetrics struct {
RequestID string `json:"request_id"`
RequestDurationMS int `json:"request_duration_ms"`
}
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, "")
case 2:
assert.True(t, len(telemetryStr) > 0, "telemetryStr should not be empty")
// the telemetry should properly unmarshal into stripe.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")
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 := stripe.GetBackendWithConfig(
stripe.APIBackend,
&stripe.BackendConfig{
LogLevel: 3,
MaxNetworkRetries: 0,
URL: testServer.URL,
EnableTelemetry: true,
},
).(*stripe.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)
}
func TestDo_TelemetryEnabledNoDataRace(t *testing.T) {
type testServerResponse struct {
Message string `json:"message"`
}
message := "Hello, client."
var requestNum int32 = 0
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 := stripe.GetBackendWithConfig(
stripe.APIBackend,
&stripe.BackendConfig{
LogLevel: 3,
MaxNetworkRetries: 0,
URL: testServer.URL,
EnableTelemetry: true,
},
).(*stripe.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",
stripe.FormatURLPath("/v1/resources/%s/subresources/%s", "1", "2"))
// Tests that each parameter is escaped for use in URLs
assert.Equal(t, "/v1/resources/%25",
stripe.FormatURLPath("/v1/resources/%s", "%"))
}
func TestGetBackendWithConfig_TrimV1Suffix(t *testing.T) {
{
backend := stripe.GetBackendWithConfig(
stripe.APIBackend,
&stripe.BackendConfig{
URL: "https://api.stripe.com/v1",
},
).(*stripe.BackendImplementation)
// The `/v1` suffix has been stripped.
assert.Equal(t, "https://api.stripe.com", backend.URL)
}
// Also support trimming a `/v1/` with an extra trailing slash which is
// probably an often seen mistake.
{
backend := stripe.GetBackendWithConfig(
stripe.APIBackend,
&stripe.BackendConfig{
URL: "https://api.stripe.com/v1/",
},
).(*stripe.BackendImplementation)
assert.Equal(t, "https://api.stripe.com", backend.URL)
}
// No-op otherwise.
{
backend := stripe.GetBackendWithConfig(
stripe.APIBackend,
&stripe.BackendConfig{
URL: "https://api.stripe.com",
},
).(*stripe.BackendImplementation)
assert.Equal(t, "https://api.stripe.com", backend.URL)
}
}
func TestParseID(t *testing.T) {
// JSON string
{
id, ok := stripe.ParseID([]byte(`"ch_123"`))
assert.Equal(t, "ch_123", id)
assert.True(t, ok)
}
// JSON object
{
id, ok := stripe.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 := stripe.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 := stripe.GetBackend(stripe.APIBackend).(*stripe.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 := stripe.GetBackend(stripe.APIBackend).(*stripe.BackendImplementation)
p := &stripe.Params{IdempotencyKey: stripe.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 := stripe.NewBackends(httpClient)
assert.Equal(t, httpClient, backends.API.(*stripe.BackendImplementation).HTTPClient)
assert.Equal(t, httpClient, backends.Uploads.(*stripe.BackendImplementation).HTTPClient)
}
func TestStripeAccount(t *testing.T) {
c := stripe.GetBackend(stripe.APIBackend).(*stripe.BackendImplementation)
p := &stripe.Params{}
p.SetStripeAccount(TestMerchantID)
req, err := c.NewRequest("", "", "", "", p)
assert.NoError(t, err)
assert.Equal(t, TestMerchantID, req.Header.Get("Stripe-Account"))
}
func TestUserAgent(t *testing.T) {
c := stripe.GetBackend(stripe.APIBackend).(*stripe.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 := &stripe.AppInfo{
Name: "MyAwesomePlugin",
PartnerID: "partner_1234",
URL: "https://myawesomeplugin.info",
Version: "1.2.34",
}
stripe.SetAppInfo(appInfo)
defer stripe.SetAppInfo(nil)
c := stripe.GetBackend(stripe.APIBackend).(*stripe.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 := stripe.GetBackend(stripe.APIBackend).(*stripe.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, stripe.UnknownPlatform, userAgent["lang_version"])
}
func TestStripeClientUserAgentWithAppInfo(t *testing.T) {
appInfo := &stripe.AppInfo{
Name: "MyAwesomePlugin",
URL: "https://myawesomeplugin.info",
Version: "1.2.34",
}
stripe.SetAppInfo(appInfo)
defer stripe.SetAppInfo(nil)
c := stripe.GetBackend(stripe.APIBackend).(*stripe.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 := stripe.GetBackend(stripe.APIBackend).(*stripe.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 := &stripe.Error{
Code: stripe.ErrorCodeMissing,
Msg: "That card was declined",
Param: "expiry_date",
Type: stripe.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 stripe.CardError type which is attached to the common
// stripe.Error.
var raw map[string]string
err = json.Unmarshal(bytes, &raw)
assert.NoError(t, err)
expectedDeclineCode := "decline-code"
raw["decline_code"] = 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.(*stripe.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)
// 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.(*stripe.InvalidRequestError)
assert.False(t, ok)
cardErr, ok := stripeErr.Err.(*stripe.CardError)
assert.True(t, ok)
assert.Equal(t, expectedDeclineCode, cardErr.DeclineCode)
}
//
// ---
//
// 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) + `}`)
}