forked from blacklightcms/recurly
-
Notifications
You must be signed in to change notification settings - Fork 0
/
recurly_test.go
378 lines (338 loc) · 12 KB
/
recurly_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
package recurly_test
import (
"bytes"
"context"
"encoding/base64"
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"net/http"
"regexp"
"strings"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"github.com/toggl/recurly"
)
// MustOpenFile opens a file in the testdata directory.
func MustOpenFile(file string) []byte {
b, err := ioutil.ReadFile("testdata/" + file)
if err != nil {
panic(fmt.Sprintf("error reading file %q: %#v", "testdata/"+file, err))
}
if strings.HasSuffix(file, ".xml") {
return MustCompact(b)
}
return b
}
var rxStripXMLTags = regexp.MustCompile(`>\s+<`)
// Removes all spaces between XML tags.
func MustCompact(b []byte) []byte {
return bytes.TrimSpace(rxStripXMLTags.ReplaceAll(b, []byte("><")))
}
// Removes all spaces between XML tags.
func MustCompactString(str string) string {
return strings.TrimSpace(rxStripXMLTags.ReplaceAllString(str, "><"))
}
// Removes the opening <?xml ...?> tag.
func MustStripXMLTag(b []byte) []byte {
return bytes.Replace(b, []byte(`<?xml version="1.0" encoding="UTF-8"?>`), []byte(""), 1)
}
// Opens an xml file from testdata directory, but removes all spaces between
// tags and the opening <?xml ...?> tag for simple marshaler comparisons.
func MustOpenCompactXMLFile(file string) []byte {
return MustStripXMLTag(MustCompact(MustOpenFile(file)))
}
// MustParseTime parses a string into time.Time, panicing if there is an error.
func MustParseTime(str string) time.Time {
t, err := time.Parse(recurly.DateTimeFormat, str)
if err != nil {
panic(err)
}
return t
}
// MustReadAll reads everything from r.
func MustReadAll(r io.ReadCloser) []byte {
defer r.Close()
b, err := ioutil.ReadAll(r)
if err != nil {
panic(err)
}
return b
}
// MustReadAllString reads everything from r.
func MustReadAllString(r io.ReadCloser) string {
return string(MustReadAll(r))
}
// TestClient tests that requests are properly structured and all of the
// expected data is sent correctly to Recurly (e.g. api key, body, etc).
func TestClient(t *testing.T) {
// Tests a GET method.
t.Run("GET", func(t *testing.T) {
client, s := recurly.NewTestServer()
defer s.Close()
timestamp := MustParseTime("2011-10-17T17:24:53Z")
s.HandleFunc("GET", "/v2/accounts", func(w http.ResponseWriter, r *http.Request) {
// API key should be base64 encoded.
encoded := base64.StdEncoding.EncodeToString([]byte("foo"))
if r.Host != "test.recurly.com" {
t.Fatalf("unexpected host: %q", r.Host)
} else if h := r.Header.Get("Authorization"); h != fmt.Sprintf("Basic %s", encoded) {
t.Fatalf("unexpected Authorization header: %q", h)
} else if h := r.Header.Get("Accept"); h != "application/xml" {
t.Fatalf("unexpected Accept header: %q", h)
} else if h := r.Header.Get("Content-Type"); h != "" {
t.Fatalf("unexpected Content-Type: %q", h)
}
w.WriteHeader(http.StatusOK)
w.Write([]byte(MustOpenFile("accounts.xml")))
}, t)
pager := client.Accounts.List(&recurly.PagerOptions{
State: "active",
Sort: "created_at",
Order: "asc",
PerPage: 25,
BeginTime: recurly.NewTime(timestamp),
EndTime: recurly.NewTime(timestamp),
})
pager.Next()
var a []recurly.Account
if err := pager.Fetch(context.Background(), &a); err != nil {
t.Fatal(err)
}
})
// Tests a POST method to ensure the request body is sent.
t.Run("POST", func(t *testing.T) {
client, s := recurly.NewTestServer()
defer s.Close()
s.HandleFunc("POST", "/v2/accounts", func(w http.ResponseWriter, r *http.Request) {
if b := MustReadAll(r.Body); !bytes.Equal(b, []byte(`<account><account_code>foo</account_code></account>`)) {
t.Fatal(string(b))
}
w.WriteHeader(http.StatusCreated)
w.Write(MustOpenFile("account.xml"))
}, t)
if a, err := client.Accounts.Create(context.Background(), recurly.Account{Code: "foo"}); !s.Invoked {
t.Fatal("expected fn invocation")
} else if err != nil {
t.Fatal(err)
} else if diff := cmp.Diff(a, NewTestAccount()); diff != "" {
t.Fatal(diff)
}
})
}
// Ensure that client errors are handled.
func TestClient_ClientErrors(t *testing.T) {
// 404 Not Found should return a ClientError.
t.Run("404", func(t *testing.T) {
// 404 response with validation errors
t.Run("OK", func(t *testing.T) {
client, s := recurly.NewTestServer()
defer s.Close()
s.HandleFunc("POST", "/v2/accounts", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
w.Write(MustOpenFile("error_not_found.xml"))
}, t)
_, err := client.Accounts.Create(context.Background(), recurly.Account{})
if !s.Invoked {
t.Fatal("expected invocation")
} else if err == nil {
t.Fatal(err)
} else if e, ok := err.(*recurly.ClientError); !ok {
t.Fatalf("unexpected error: %T %#v", err, err)
} else if e.Response == nil {
t.Fatal("expected *http.Response")
} else if e.Response.StatusCode != http.StatusNotFound {
t.Fatalf("unexpected status code: %d", e.Response.StatusCode)
} else if diff := cmp.Diff(e.ValidationErrors, []recurly.ValidationError{{
Symbol: "not_found",
Description: "The record could not be located.",
}}); diff != "" {
t.Fatal(diff)
}
})
// 404 response with empty body
t.Run("EmptyBody", func(t *testing.T) {
client, s := recurly.NewTestServer()
defer s.Close()
s.HandleFunc("POST", "/v2/accounts", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}, t)
_, err := client.Accounts.Create(context.Background(), recurly.Account{})
if !s.Invoked {
t.Fatal("expected invocation")
} else if err == nil {
t.Fatal(err)
} else if e, ok := err.(*recurly.ClientError); !ok {
t.Fatalf("unexpected error: %T %#v", err, err)
} else if e.Response == nil {
t.Fatal("expected *http.Response")
} else if e.Response.StatusCode != http.StatusNotFound {
t.Fatalf("unexpected status code: %d", e.Response.StatusCode)
} else if len(e.ValidationErrors) > 0 {
t.Fatalf("unexpected validation errors: %#v", e.ValidationErrors)
}
})
})
t.Run("422", func(t *testing.T) {
// Ensure a top-level <error> tag is properly handled.
t.Run("SingleError", func(t *testing.T) {
client, s := recurly.NewTestServer()
defer s.Close()
s.HandleFunc("POST", "/v2/accounts", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusUnprocessableEntity)
w.Write([]byte(`
<?xml version="1.0" encoding="UTF-8"?>
<error>
<symbol>simultaneous_request</symbol>
<description>A change for subscription 3cf89f0c3fcda0b15c50134f63856d4e is already in progress.</description>
</error>
`))
}, t)
_, err := client.Accounts.Create(context.Background(), recurly.Account{})
if !s.Invoked {
t.Fatal("expected invocation")
} else if err == nil {
t.Fatal(err)
} else if e, ok := err.(*recurly.ClientError); !ok {
t.Fatalf("unexpected error: %T %#v", err, err)
} else if e.Response == nil {
t.Fatal("expected *http.Response")
} else if e.Response.StatusCode != http.StatusUnprocessableEntity {
t.Fatalf("unexpected status code: %d", e.Response.StatusCode)
} else if diff := cmp.Diff(e.ValidationErrors, []recurly.ValidationError{{
Symbol: "simultaneous_request",
Description: "A change for subscription 3cf89f0c3fcda0b15c50134f63856d4e is already in progress.",
}}); diff != "" {
t.Fatal(diff)
}
})
// Ensure a top-level <errors> tag is properly handled.
t.Run("MultiErrors", func(t *testing.T) {
client, s := recurly.NewTestServer()
defer s.Close()
s.HandleFunc("POST", "/v2/accounts", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusUnprocessableEntity)
w.Write([]byte(`
<?xml version="1.0" encoding="UTF-8"?>
<errors>
<error field="model_name.field_name" symbol="not_a_number" lang="en-US">is not a number</error>
<error field="subscription.base" symbol="already_subscribed">You already have a subscription to this plan.</error>
</errors>
`))
}, t)
_, err := client.Accounts.Create(context.Background(), recurly.Account{})
if !s.Invoked {
t.Fatal("expected invocation")
} else if err == nil {
t.Fatal(err)
} else if e, ok := err.(*recurly.ClientError); !ok {
t.Fatalf("unexpected error: %T %#v", err, err)
} else if e.Response == nil {
t.Fatal("expected *http.Response")
} else if e.Response.StatusCode != http.StatusUnprocessableEntity {
t.Fatalf("unexpected status code: %d", e.Response.StatusCode)
} else if diff := cmp.Diff(e.ValidationErrors, []recurly.ValidationError{
{
Field: "model_name.field_name",
Symbol: "not_a_number",
Description: "is not a number",
},
{
Field: "subscription.base",
Symbol: "already_subscribed",
Description: "You already have a subscription to this plan.",
},
}); diff != "" {
t.Fatal(diff)
}
})
})
t.Run("Is", func(t *testing.T) {
t.Run("SingleError", func(t *testing.T) {
if err := (&recurly.ClientError{
ValidationErrors: []recurly.ValidationError{{
Symbol: "number_of_unique_codes",
Description: "You are limited to generating 200 at a time",
}},
}); !err.Is("number_of_unique_codes") {
t.Fatal("expected true")
} else if err.Is("not_found") {
t.Fatal("expected false")
}
})
t.Run("MultiErrors", func(t *testing.T) {
if err := (&recurly.ClientError{
ValidationErrors: []recurly.ValidationError{
{
Symbol: "number_of_unique_codes",
Description: "You are limited to generating 200 at a time",
},
{
Symbol: "will_not_invoice",
Description: "No adjustments to invoice",
},
},
}); !err.Is("number_of_unique_codes") {
t.Fatal("expected true")
} else if !err.Is("will_not_invoice") {
t.Fatal("expected true")
} else if err.Is("not_found") {
t.Fatal("expected false")
}
})
})
}
// Ensure transaction errors return TransactionFailedError.
func TestClient_TransactionFailedError(t *testing.T) {
client, s := recurly.NewTestServer()
defer s.Close()
s.HandleFunc("POST", "/v2/accounts", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusUnprocessableEntity)
w.Write(MustOpenFile("errors_transaction_failed.xml"))
}, t)
_, err := client.Accounts.Create(context.Background(), recurly.Account{})
if !s.Invoked {
t.Fatal("expected invocation")
} else if err == nil {
t.Fatal(err)
} else if e, ok := err.(*recurly.TransactionFailedError); !ok {
t.Fatalf("unexpected error: %T %#v", err, err)
} else if e.Response == nil {
t.Fatal("expected *http.Response")
} else if e.Response.StatusCode != http.StatusUnprocessableEntity {
t.Fatalf("unexpected status code: %d", e.Response.StatusCode)
} else if diff := cmp.Diff(e.TransactionError, recurly.TransactionError{
XMLName: xml.Name{Local: "transaction_error"},
ErrorCode: "fraud_security_code",
ErrorCategory: "fraud",
MerchantMessage: "The payment gateway declined the transaction because the security code (CVV) did not match.",
CustomerMessage: "The security code you entered does not match. Please update the CVV and try again.",
GatewayErrorCode: "301",
ThreeDSecureActionTokenID: "ABCDEFGHIJKL012345",
}); diff != "" {
t.Fatal(diff)
} else if diff := cmp.Diff(e.Transaction, NewTestTransactionFailed()); diff != "" {
t.Fatal(diff)
}
}
func TestClient_ServerErrors(t *testing.T) {
client, s := recurly.NewTestServer()
defer s.Close()
s.HandleFunc("POST", "/v2/accounts", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
}, t)
_, err := client.Accounts.Create(context.Background(), recurly.Account{})
if !s.Invoked {
t.Fatal("expected invocation")
} else if err == nil {
t.Fatal(err)
} else if e, ok := err.(*recurly.ServerError); !ok {
t.Fatalf("unexpected error: %T %#v", err, err)
} else if e.Response == nil {
t.Fatal("expected *http.Response")
} else if e.Response.StatusCode != http.StatusInternalServerError {
t.Fatalf("unexpected status code: %d", e.Response.StatusCode)
}
}