-
Notifications
You must be signed in to change notification settings - Fork 5
/
test_webhooks.py
320 lines (305 loc) · 11.6 KB
/
test_webhooks.py
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
import mock
import requests_mock
import simplejson as json
from rest_framework.reverse import reverse
from tests.test_utils import BaseTestCase
from aa_stripe.exceptions import StripeWebhookAlreadyParsed
from aa_stripe.models import StripeCoupon, StripeWebhook
class TestWebhook(BaseTestCase):
def test_subscription_creation(self):
self.assertEqual(StripeWebhook.objects.count(), 0)
payload = json.loads("""{
"created": 1326853478,
"livemode": false,
"id": "evt_00000000000000",
"type": "charge.failed",
"object": "event",
"request": null,
"pending_webhooks": 1,
"api_version": "2017-06-05",
"data": {
"object": {
"id": "ch_00000000000000",
"object": "charge",
"amount": 100,
"amount_refunded": 0,
"application": null,
"application_fee": null,
"balance_transaction": "txn_00000000000000",
"captured": false,
"created": 1496953100,
"currency": "usd",
"customer": null,
"description": "My First Test Charge (created for API docs)",
"destination": null,
"dispute": null,
"failure_code": null,
"failure_message": null,
"fraud_details": {
},
"invoice": null,
"livemode": false,
"metadata": {
},
"on_behalf_of": null,
"order": null,
"outcome": null,
"paid": false,
"receipt_email": null,
"receipt_number": null,
"refunded": false,
"refunds": {
"object": "list",
"data": [
],
"has_more": false,
"total_count": 0,
"url": "/v1/charges/ch_1ASX5ELoWm2f6pRwC6ZyewYR/refunds"
},
"review": null,
"shipping": null,
"source": {
"id": "card_00000000000000",
"object": "card",
"address_city": null,
"address_country": null,
"address_line1": null,
"address_line1_check": null,
"address_line2": null,
"address_state": null,
"address_zip": null,
"address_zip_check": null,
"brand": "Visa",
"country": "US",
"customer": null,
"cvc_check": null,
"dynamic_last4": null,
"exp_month": 8,
"exp_year": 2018,
"fingerprint": "DsGmBIQwiNOvChPk",
"funding": "credit",
"last4": "4242",
"metadata": {
},
"name": null,
"tokenization_method": null
},
"source_transfer": null,
"statement_descriptor": null,
"status": "succeeded",
"transfer_group": null
}
}
}""")
url = reverse("stripe-webhooks")
response = self.client.post(url, data=payload, format="json")
self.assertEqual(response.status_code, 400) # not signed
headers = {
"HTTP_STRIPE_SIGNATURE": "wrong", # todo: generate signature
}
self.client.credentials(**headers)
response = self.client.post(url, data=payload, format="json")
self.assertEqual(response.status_code, 400) # wrong signature
self.client.credentials(**self._get_signature_headers(payload))
response = self.client.post(url, data=payload, format="json")
self.assertEqual(response.status_code, 201)
self.assertEqual(StripeWebhook.objects.count(), 1)
webhook = StripeWebhook.objects.first()
self.assertEqual(webhook.id, payload["id"])
self.assertEqual(webhook.raw_data, payload)
self.assertTrue(webhook.is_parsed)
def test_coupon_create(self):
self.assertEqual(StripeCoupon.objects.count(), 0)
payload = json.loads("""{
"id": "evt_1AtuXzLoWm2f6pRwC5YntNLU",
"object": "event",
"api_version": "2017-06-05",
"created": 1503478151,
"data": {
"object": {
"id": "nicecoupon",
"object": "coupon",
"amount_off": 1000,
"created": 1503478151,
"currency": "usd",
"duration": "once",
"duration_in_months": null,
"livemode": false,
"max_redemptions": null,
"metadata": {
},
"percent_off": null,
"redeem_by": null,
"times_redeemed": 0,
"valid": true
}
},
"livemode": false,
"pending_webhooks": 1,
"request": {
"id": "req_RzV8JI9bg7fPiR",
"idempotency_key": null
},
"type": "coupon.created"
}""")
stripe_response = json.loads("""{
"id": "nicecoupon",
"object": "coupon",
"amount_off": 1000,
"created": 1503478151,
"currency": "usd",
"duration": "once",
"duration_in_months": null,
"livemode": false,
"max_redemptions": null,
"metadata": {
},
"percent_off": null,
"redeem_by": null,
"times_redeemed": 0,
"valid": true
}""")
with requests_mock.Mocker() as m:
m.register_uri("GET", "https://api.stripe.com/v1/coupons/nicecoupon", text=json.dumps(stripe_response))
url = reverse("stripe-webhooks")
self.client.credentials(**self._get_signature_headers(payload))
response = self.client.post(url, data=payload, format="json")
self.assertEqual(response.status_code, 201)
self.assertEqual(StripeCoupon.objects.count(), 1)
coupon = StripeCoupon.objects.first()
# the rest of the data is retrieved from Stripe API, which is stubbed above
# so there is no need to compare it
self.assertEqual(coupon.coupon_id, "nicecoupon")
def test_coupon_update(self):
coupon = self._create_coupon("nicecoupon", amount_off=10000, duration=StripeCoupon.DURATION_ONCE,
metadata={"nie": "tak", "lol1": "rotfl"})
payload = json.loads("""{
"id": "evt_1AtuTOLoWm2f6pRw6dYfQzWh",
"object": "event",
"api_version": "2017-06-05",
"created": 1503477866,
"data": {
"object": {
"id": "nicecoupon",
"object": "coupon",
"amount_off": 10000,
"created": 1503412710,
"currency": "usd",
"duration": "forever",
"duration_in_months": null,
"livemode": false,
"max_redemptions": null,
"metadata": {
"lol1": "rotfl2",
"lol2": "yeah"
},
"percent_off": null,
"redeem_by": null,
"times_redeemed": 0,
"valid": true
},
"previous_attributes": {
"metadata": {
"nie": "tak",
"lol1": "rotfl",
"lol2": null
}
}
},
"livemode": false,
"pending_webhooks": 1,
"request": {
"id": "req_putcEg4hE9bkUb",
"idempotency_key": null
},
"type": "coupon.updated"
}""")
url = reverse("stripe-webhooks")
self.client.credentials(**self._get_signature_headers(payload))
response = self.client.post(url, data=payload, format="json")
coupon.refresh_from_db()
self.assertEqual(response.status_code, 201)
self.assertEqual(coupon.metadata, {
"lol1": "rotfl2",
"lol2": "yeah"
})
def test_coupon_delete(self):
coupon = self._create_coupon("nicecoupon", amount_off=10000, duration=StripeCoupon.DURATION_ONCE)
self.assertFalse(coupon.is_deleted)
payload = json.loads("""{
"id": "evt_1Atthtasdsaf6pRwkdLOSKls",
"object": "event",
"api_version": "2017-06-05",
"created": 1503474921,
"data": {
"object": {
"id": "nicecoupon",
"object": "coupon",
"amount_off": 10000,
"created": 1503474890,
"currency": "usd",
"duration": "once",
"duration_in_months": null,
"livemode": false,
"max_redemptions": null,
"metadata": {
},
"percent_off": null,
"redeem_by": null,
"times_redeemed": 0,
"valid": false
}
},
"livemode": false,
"pending_webhooks": 1,
"request": {
"id": "req_9UO71nsJyOhQfi",
"idempotency_key": null
},
"type": "coupon.deleted"
}""")
url = reverse("stripe-webhooks")
self.client.credentials(**self._get_signature_headers(payload))
with mock.patch("aa_stripe.models.webhook_pre_parse.send") as mocked_signal:
response = self.client.post(url, data=payload, format="json")
coupon.refresh_from_db()
self.assertEqual(response.status_code, 201)
self.assertTrue(coupon.is_deleted)
webhook = StripeWebhook.objects.first()
self.assertTrue(webhook.is_parsed)
mocked_signal.assert_called_with(event_action="deleted", event_model="coupon", event_type="coupon.deleted",
instance=webhook, sender=StripeWebhook)
# test deleting event that has already been deleted - should not raise any errors
# it will just make sure is_deleted is set for this coupon
payload["id"] = "evt_someother"
payload["request"]["id"] = ["req_someother"]
self.client.credentials(**self._get_signature_headers(payload))
response = self.client.post(url, data=payload, format="json")
coupon.refresh_from_db()
self.assertEqual(response.status_code, 201)
self.assertTrue(coupon.is_deleted)
# make sure trying to parse already parsed webhook is impossible
self.assertTrue(webhook.is_parsed)
with self.assertRaises(StripeWebhookAlreadyParsed):
webhook.parse()
# test receiving ping event (the only event without "." inside the event name)
StripeWebhook.objects.all().delete()
payload = json.loads("""{
"id": "evt_1Atthtasdsaf6pRwkdLOhKls",
"object": "event",
"api_version": "2017-06-05",
"created": 1503474921,
"livemode": false,
"pending_webhooks": 1,
"request": {
"id": "req_9UO71nsJyzhQfi",
"idempotency_key": null
},
"type": "ping"
}""")
self.client.credentials(**self._get_signature_headers(payload))
with mock.patch("aa_stripe.models.webhook_pre_parse.send") as mocked_signal:
response = self.client.post(url, data=payload, format="json")
self.assertEqual(response.status_code, 201)
mocked_signal.assert_called_with(event_action=None, event_model=None, event_type="ping",
instance=StripeWebhook.objects.first(), sender=StripeWebhook)