forked from stripe/stripe-mock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server_test.go
289 lines (254 loc) · 7.59 KB
/
server_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
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"testing"
assert "github.com/stretchr/testify/require"
"github.com/stripe/stripe-mock/spec"
)
func TestStubServer(t *testing.T) {
resp, body := sendRequest(t, "POST", "/v1/charges",
"amount=123¤cy=usd", getDefaultHeaders())
assert.Equal(t, http.StatusOK, resp.StatusCode)
var data map[string]interface{}
err := json.Unmarshal(body, &data)
assert.NoError(t, err)
_, ok := data["id"]
assert.True(t, ok)
}
func TestStubServerError(t *testing.T) {
resp, body := sendRequest(t, "GET", "/a", "", nil)
assert.Equal(t, http.StatusUnauthorized, resp.StatusCode)
var data map[string]interface{}
err := json.Unmarshal(body, &data)
assert.NoError(t, err)
errorInfo, ok := data["error"].(map[string]interface{})
assert.True(t, ok)
errorType, ok := errorInfo["type"]
assert.Equal(t, errorType, "invalid_request_error")
assert.True(t, ok)
_, ok = errorInfo["message"]
assert.True(t, ok)
}
func TestStubServer_SetsSpecialHeaders(t *testing.T) {
resp, _ := sendRequest(t, "POST", "/", "", nil)
assert.Equal(t, http.StatusUnauthorized, resp.StatusCode)
assert.Equal(t, version, resp.Header.Get("Stripe-Mock-Version"))
_, ok := resp.Header["Request-Id"]
assert.False(t, ok)
resp, _ = sendRequest(t, "POST", "/", "", getDefaultHeaders())
assert.Equal(t, http.StatusNotFound, resp.StatusCode)
assert.Equal(t, version, resp.Header.Get("Stripe-Mock-Version"))
assert.Equal(t, "req_123", resp.Header.Get("Request-Id"))
}
func TestStubServer_ParameterValidation(t *testing.T) {
resp, body := sendRequest(t, "POST", "/v1/charges", "", getDefaultHeaders())
assert.Contains(t, string(body), "property 'amount' is required")
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
}
func TestStubServer_FormatsForCurl(t *testing.T) {
headers := getDefaultHeaders()
headers["User-Agent"] = "curl/1.2.3"
resp, body := sendRequest(t, "POST", "/v1/charges",
"amount=123¤cy=usd", headers)
// Note the two spaces in front of "id" which indicate that our JSON is
// pretty printed.
assert.Contains(t, string(body), ` "id"`)
assert.Equal(t, http.StatusOK, resp.StatusCode)
}
func TestStubServer_RoutesRequest(t *testing.T) {
server := getStubServer(t)
var route *stubServerRoute
route = server.routeRequest(
&http.Request{Method: "GET", URL: &url.URL{Path: "/v1/charges"}})
assert.NotNil(t, route)
assert.Equal(t, chargeAllMethod, route.operation)
route = server.routeRequest(
&http.Request{Method: "POST", URL: &url.URL{Path: "/v1/charges"}})
assert.NotNil(t, route)
assert.Equal(t, chargeCreateMethod, route.operation)
route = server.routeRequest(
&http.Request{Method: "GET", URL: &url.URL{Path: "/v1/charges/ch_123"}})
assert.NotNil(t, route)
assert.Equal(t, chargeGetMethod, route.operation)
route = server.routeRequest(
&http.Request{Method: "DELETE", URL: &url.URL{Path: "/v1/charges/ch_123"}})
assert.NotNil(t, route)
assert.Equal(t, chargeDeleteMethod, route.operation)
route = server.routeRequest(
&http.Request{Method: "GET", URL: &url.URL{Path: "/v1/doesnt-exist"}})
assert.Equal(t, (*stubServerRoute)(nil), route)
}
// ---
func TestCompilePath(t *testing.T) {
assert.Equal(t, `\A/v1/charges\z`,
compilePath(spec.Path("/v1/charges")).String())
assert.Equal(t, `\A/v1/charges/(?P<id>[\w-_.]+)\z`,
compilePath(spec.Path("/v1/charges/{id}")).String())
}
func TestGetValidator(t *testing.T) {
operation := &spec.Operation{RequestBody: &spec.RequestBody{
Content: map[string]spec.MediaType{
"application/x-www-form-urlencoded": {
Schema: &spec.Schema{
Properties: map[string]*spec.Schema{
"name": {
Type: "string",
},
},
},
},
},
}}
schema := getRequestBodySchema(operation)
assert.NotNil(t, schema)
validator, err := spec.GetValidatorForOpenAPI3Schema(schema, nil)
assert.NoError(t, err)
assert.NotNil(t, validator)
goodData := map[string]interface{}{
"name": "foo",
}
assert.NoError(t, validator.Validate(goodData))
badData := map[string]interface{}{
"name": 7,
}
assert.Error(t, validator.Validate(badData))
}
func TestGetValidator_NoSuitableParameter(t *testing.T) {
method := &spec.Operation{Parameters: []*spec.Parameter{
{Schema: nil},
}}
schema := getRequestBodySchema(method)
assert.Nil(t, schema)
}
func TestIsCurl(t *testing.T) {
testCases := []struct {
userAgent string
want bool
}{
{"curl/7.51.0", true},
// false because it's not something (to my knowledge) that cURL would
// ever return
{"curl", false},
{"Mozilla", false},
{"", false},
}
for _, tc := range testCases {
t.Run(tc.userAgent, func(t *testing.T) {
assert.Equal(t, tc.want, isCurl(tc.userAgent))
})
}
}
func TestParseExpansionLevel(t *testing.T) {
emptyExpansionLevel := &ExpansionLevel{
expansions: make(map[string]*ExpansionLevel),
}
testCases := []struct {
expansions []string
want *ExpansionLevel
}{
{
[]string{"charge", "customer"},
&ExpansionLevel{expansions: map[string]*ExpansionLevel{
"charge": emptyExpansionLevel,
"customer": emptyExpansionLevel,
}},
},
{
[]string{"charge.customer", "customer", "charge.source"},
&ExpansionLevel{expansions: map[string]*ExpansionLevel{
"charge": {expansions: map[string]*ExpansionLevel{
"customer": emptyExpansionLevel,
"source": emptyExpansionLevel,
}},
"customer": emptyExpansionLevel,
}},
},
{
[]string{"charge.customer.default_source", "charge"},
&ExpansionLevel{expansions: map[string]*ExpansionLevel{
"charge": {expansions: map[string]*ExpansionLevel{
"customer": {expansions: map[string]*ExpansionLevel{
"default_source": emptyExpansionLevel,
}},
}},
}},
},
{
[]string{"*"},
&ExpansionLevel{
expansions: map[string]*ExpansionLevel{},
wildcard: true,
},
},
}
for _, tc := range testCases {
t.Run(fmt.Sprintf("%+v", tc.expansions), func(t *testing.T) {
assert.Equal(t, tc.want, ParseExpansionLevel(tc.expansions))
})
}
}
func TestValidateAuth(t *testing.T) {
testCases := []struct {
auth string
want bool
}{
{"Basic " + encode64("sk_test_123"), true},
{"Bearer sk_test_123", true},
{"", false},
{"Bearer", false},
{"Basic", false},
{"Bearer ", false},
{"Basic ", false},
{"Basic 123", false}, // "123" is not a valid key when base64 decoded
{"Basic " + encode64("sk_test"), false},
{"Bearer sk_test_123 extra", false},
{"Bearer sk_test", false},
{"Bearer sk_test_123_extra", false},
{"Bearer sk_live_123", false},
{"Bearer sk_test_", false},
}
for _, tc := range testCases {
t.Run("Authorization: "+tc.auth, func(t *testing.T) {
assert.Equal(t, tc.want, validateAuth(tc.auth))
})
}
}
//
// ---
//
func encode64(s string) string {
return base64.StdEncoding.EncodeToString([]byte(s))
}
func getStubServer(t *testing.T) *StubServer {
server := &StubServer{spec: &testSpec, fixtures: &testFixtures}
err := server.initializeRouter()
assert.NoError(t, err)
return server
}
func getDefaultHeaders() map[string]string {
headers := make(map[string]string)
headers["Authorization"] = "Bearer sk_test_123"
return headers
}
func sendRequest(t *testing.T, method string, url string, params string,
headers map[string]string) (*http.Response, []byte) {
server := getStubServer(t)
fullUrl := fmt.Sprintf("https://stripe.com%s", url)
req := httptest.NewRequest(method, fullUrl, bytes.NewBufferString(params))
for k, v := range headers {
req.Header.Set(k, v)
}
w := httptest.NewRecorder()
server.HandleRequest(w, req)
resp := w.Result()
body, err := ioutil.ReadAll(resp.Body)
assert.NoError(t, err)
return resp, body
}