-
Notifications
You must be signed in to change notification settings - Fork 5
/
test_coupons.py
276 lines (250 loc) · 12.1 KB
/
test_coupons.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
import time
from datetime import datetime
import requests_mock
import simplejson as json
from django.contrib.auth import get_user_model
from django.core.management import call_command
from django.utils import timezone
from freezegun import freeze_time
from rest_framework.reverse import reverse
from tests.test_utils import BaseTestCase
from aa_stripe.forms import StripeCouponForm
from aa_stripe.models import StripeCoupon
UserModel = get_user_model()
class TestCoupons(BaseTestCase):
@freeze_time("2016-01-01 00:00:00")
def test_create(self):
# test creating simple coupon with no coupon_id specified (will be generated by Stripe)
stripe_response = {
"id": "25OFF",
"object": "coupon",
"amount_off": 1,
"created": int(time.mktime(datetime.now().timetuple())),
"currency": "usd",
"duration": StripeCoupon.DURATION_FOREVER,
"duration_in_months": None,
"livemode": False,
"max_redemptions": None,
"metadata": {},
"percent_off": 25,
"redeem_by": None,
"times_redeemed": 0,
"valid": True
}
with requests_mock.Mocker() as m:
m.register_uri("POST", "https://api.stripe.com/v1/coupons", text=json.dumps(stripe_response))
coupon = StripeCoupon.objects.create(
duration=StripeCoupon.DURATION_FOREVER,
percent_off=25
)
self.assertEqual(coupon.coupon_id, stripe_response["id"])
self.assertEqual(coupon.created, timezone.make_aware(datetime.fromtimestamp(stripe_response["created"])))
self.assertEqual(coupon.stripe_response, stripe_response)
# test creating coupon with coupon_id
stripe_response["id"] = "YOLO1"
m.register_uri("POST", "https://api.stripe.com/v1/coupons", text=json.dumps(stripe_response))
coupon = StripeCoupon.objects.create(
coupon_id=stripe_response["id"],
duration=StripeCoupon.DURATION_FOREVER
)
self.assertEqual(coupon.coupon_id, stripe_response["id"])
def test_update(self):
with requests_mock.Mocker() as m:
stripe_response = {
"id": "25OFF",
"object": "coupon",
"amount_off": 1,
"created": int(time.mktime(datetime.now().timetuple())),
"currency": "usd",
"duration": StripeCoupon.DURATION_FOREVER,
"duration_in_months": None,
"livemode": False,
"max_redemptions": None,
"metadata": {},
"percent_off": 25,
"redeem_by": None,
"times_redeemed": 0,
"valid": True
}
coupon = self._create_coupon(coupon_id="25OFF", duration=StripeCoupon.DURATION_FOREVER, amount_off=1)
self.assertFalse(coupon.is_deleted)
# try accessing coupon that does not exist - should delete the coupon from our database
m.register_uri("GET", "https://api.stripe.com/v1/coupons/25OFF", status_code=404, text=json.dumps({
"error": {
"type": "invalid_request_error"
}
}))
coupon.metadata = {"yes": "no"}
coupon.save()
coupon.refresh_from_db()
self.assertTrue(coupon.is_deleted)
# try changing other Stripe data than coupon's metadata
m.register_uri("GET", "https://api.stripe.com/v1/coupons/25OFF", text=json.dumps(stripe_response))
m.register_uri("POST", "https://api.stripe.com/v1/coupons/25OFF", text=json.dumps(stripe_response))
coupon = self._create_coupon(coupon_id="25OFF", duration=StripeCoupon.DURATION_FOREVER, amount_off=1)
coupon.duration = StripeCoupon.DURATION_ONCE
coupon.save()
coupon.refresh_from_db()
self.assertNotEqual(coupon.duration, StripeCoupon.DURATION_ONCE)
def test_delete(self):
coupon = self._create_coupon(coupon_id="CPON", amount_off=1, duration=StripeCoupon.DURATION_FOREVER)
self.assertFalse(coupon.is_deleted)
stripe_response = {
"id": "CPON",
"object": "coupon",
"amount_off": 1,
"created": int(time.mktime(datetime.now().timetuple())),
"currency": "usd",
"duration": StripeCoupon.DURATION_FOREVER,
"duration_in_months": None,
"livemode": False,
"max_redemptions": None,
"metadata": {},
"percent_off": 25,
"redeem_by": None,
"times_redeemed": 0,
"valid": True
}
with requests_mock.Mocker() as m:
for method in ["GET", "DELETE"]:
m.register_uri(method, "https://api.stripe.com/v1/coupons/CPON", text=json.dumps(stripe_response))
coupon.delete()
coupon.refresh_from_db()
self.assertTrue(coupon.is_deleted)
def test_admin_form(self):
# test correct creation
data = {
"coupon_id": "25OFF",
"amount_off": 1,
"currency": "usd",
"duration": StripeCoupon.DURATION_ONCE,
"metadata": {},
"times_redeemed": 0,
"valid": True
}
self.assertTrue(StripeCouponForm(data=data).is_valid())
# test passing none of amount_off or percent_off
del data["amount_off"]
self.assertFalse(StripeCouponForm(data=data).is_valid())
# test passing both of amount_off and percent_off
data["amount_off"] = 100
data["percent_off"] = 10
self.assertFalse(StripeCouponForm(data=data).is_valid())
del data["percent_off"]
# test passing duration repeating with empty duration_in_months
data["duration"] = StripeCoupon.DURATION_REPEATING
self.assertFalse(StripeCouponForm(data=data).is_valid())
# test passing duration_in_months when duration is not repeating
data["duration"] = StripeCoupon.DURATION_ONCE
data["duration_in_months"] = 1
self.assertFalse(StripeCouponForm(data=data).is_valid())
del data["duration_in_months"]
stripe_response = {
"id": "25OFF",
"object": "coupon",
"amount_off": 1,
"created": int(time.mktime(datetime.now().timetuple())),
"currency": "usd",
"duration": StripeCoupon.DURATION_FOREVER,
"duration_in_months": None,
"livemode": False,
"max_redemptions": None,
"metadata": {},
"percent_off": 25,
"redeem_by": None,
"times_redeemed": 0,
"valid": True
}
with requests_mock.Mocker() as m:
for method in ["GET", "POST", "DELETE"]:
m.register_uri(method, "https://api.stripe.com/v1/coupons/25OFF", text=json.dumps(stripe_response))
coupon = self._create_coupon(data["coupon_id"], amount_off=1)
# test creating a new coupon, when there is one that is not deleted
self.assertTrue(StripeCoupon.objects.filter(coupon_id=data["coupon_id"], is_deleted=False).exists())
self.assertFalse(StripeCouponForm(data=data).is_valid())
# delete and try again
coupon.is_deleted = True
coupon.save()
self.assertTrue(StripeCouponForm(data=data).is_valid())
def test_details_api(self):
# test accessing without authentication
url = reverse("stripe-coupon-details", kwargs={"coupon_id": "FAKE-COUPON"})
response = self.client.get(url, format="json")
self.assertEqual(response.status_code, 403)
user = UserModel.objects.create(email="foo@bar.bar", username="foo", password="dump-password")
self.client.force_authenticate(user=user)
# test accessing coupon that does not exist
response = self.client.get(url, format="json")
self.assertEqual(response.status_code, 404)
# test regular
coupon = self._create_coupon("COUPON")
url = reverse("stripe-coupon-details", kwargs={"coupon_id": coupon.coupon_id})
response = self.client.get(url, format="json")
self.assertEqual(response.status_code, 200)
self.assertEqual(set(response.data.keys()), {
"coupon_id", "amount_off", "currency", "duration", "duration_in_months", "livemode", "max_redemptions",
"metadata", "percent_off", "redeem_by", "times_redeemed", "valid", "is_created_at_stripe", "created",
"updated", "is_deleted"
})
# test accessing coupon that has already been deleted
# update does not call object's .save(), so we do not need to mock Stripe API
StripeCoupon.objects.filter(pk=coupon.pk).update(is_deleted=True)
response = self.client.get(url, format="json")
self.assertEqual(response.status_code, 404)
def test_refresh_coupons_command(self):
coupons = {
"1A": self._create_coupon("1A"),
"2A": self._create_coupon("2A"),
"3A": self._create_coupon("3A"),
"4A": self._create_coupon("4A", amount_off=100)
}
self.assertEqual(StripeCoupon.objects.count(), 4)
# fake deleted coupon, this coupon should be recreated in the database
StripeCoupon.objects.filter(pk=coupons["3A"].pk).update(is_deleted=True)
coupon_1a_new_response = coupons["1A"].stripe_response.copy()
coupon_1a_new_response["metadata"] = {"new": "data"}
coupon_4a_new_response = coupons["4A"].stripe_response.copy()
coupon_4a_new_response["created"] += 1
coupon_4a_new_response["amount_off"] = 99
# fake limit
stripe_response_part1 = {
"object": "list",
"url": "/v1/coupons",
"has_more": True,
"data": [
coupon_1a_new_response, # 1A will be updated, # 2A will be deleted
coupons["3A"].stripe_response, # 3A will be recreated
coupon_4a_new_response, # 4A will be deleted and recreated with the same name
]
}
new_coupon_stripe_response = coupons["1A"].stripe_response.copy()
new_coupon_stripe_response["id"] = "1B"
stripe_response_part2 = stripe_response_part1.copy()
stripe_response_part2.update({
"has_more": False,
"data": [new_coupon_stripe_response]
})
with requests_mock.Mocker() as m:
m.register_uri("GET", "https://api.stripe.com/v1/coupons", text=json.dumps(stripe_response_part1))
m.register_uri("GET", "https://api.stripe.com/v1/coupons?starting_after=4A",
text=json.dumps(stripe_response_part2))
# 3A will be recreated
m.register_uri("GET", "https://api.stripe.com/v1/coupons/3A",
text=json.dumps(coupons["3A"].stripe_response))
# 4A will be recreated with new data
m.register_uri("GET", "https://api.stripe.com/v1/coupons/4A", text=json.dumps(coupon_4a_new_response))
# 1B will be created
m.register_uri("GET", "https://api.stripe.com/v1/coupons/1B", text=json.dumps(new_coupon_stripe_response))
call_command("refresh_coupons")
self.assertEqual(StripeCoupon.objects.count(), 7) # 4 + 3 were created
for coupon in coupons.values():
coupon.refresh_from_db()
self.assertEqual(coupons["1A"].metadata, coupon_1a_new_response["metadata"])
self.assertTrue(coupons["2A"].is_deleted)
new_3a_coupon = StripeCoupon.objects.get(coupon_id="3A", is_deleted=False)
self.assertNotEqual(new_3a_coupon.pk, coupons["3A"].pk)
self.assertTrue(coupons["4A"].is_deleted)
new_4a_coupon = StripeCoupon.objects.get(coupon_id="4A", is_deleted=False)
self.assertNotEqual(new_4a_coupon.pk, coupons["4A"].pk)
self.assertEqual(new_4a_coupon.amount_off, coupon_4a_new_response["amount_off"])
self.assertTrue(StripeCoupon.objects.filter(coupon_id="1B", is_deleted=False).exists)