forked from dj-stripe/dj-stripe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_customer.py
2390 lines (2057 loc) · 82.9 KB
/
test_customer.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
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
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Customer Model Tests.
"""
import decimal
from copy import deepcopy
from unittest.mock import ANY, patch
import pytest
from django.contrib.auth import get_user_model
from django.test import TestCase, override_settings
from django.utils import timezone
from stripe.error import InvalidRequestError
from djstripe.exceptions import MultipleSubscriptionException
from djstripe.models import (
Card,
Charge,
Coupon,
Customer,
DjstripePaymentMethod,
IdempotencyKey,
Invoice,
PaymentMethod,
Plan,
Price,
Product,
Source,
Subscription,
)
from djstripe.settings import djstripe_settings
from . import (
FAKE_BALANCE_TRANSACTION,
FAKE_CARD,
FAKE_CARD_AS_PAYMENT_METHOD,
FAKE_CARD_III,
FAKE_CHARGE,
FAKE_COUPON,
FAKE_CUSTOMER,
FAKE_CUSTOMER_II,
FAKE_CUSTOMER_III,
FAKE_CUSTOMER_IV,
FAKE_DISCOUNT_CUSTOMER,
FAKE_INVOICE,
FAKE_INVOICE_III,
FAKE_INVOICEITEM,
FAKE_PAYMENT_INTENT_I,
FAKE_PAYMENT_METHOD_I,
FAKE_PLAN,
FAKE_PLATFORM_ACCOUNT,
FAKE_PRICE,
FAKE_PRODUCT,
FAKE_SOURCE,
FAKE_SOURCE_II,
FAKE_SUBSCRIPTION,
FAKE_SUBSCRIPTION_II,
FAKE_UPCOMING_INVOICE,
AssertStripeFksMixin,
StripeList,
datetime_to_unix,
)
class TestCustomer(AssertStripeFksMixin, TestCase):
def setUp(self):
# create a Stripe Platform Account
self.account = FAKE_PLATFORM_ACCOUNT.create()
self.user = get_user_model().objects.create_user(
username="pydanny", email="[email protected]"
)
self.customer = FAKE_CUSTOMER.create_for_user(self.user)
self.payment_method, _ = DjstripePaymentMethod._get_or_create_source(
FAKE_CARD, "card"
)
self.card = self.payment_method.resolve()
self.customer.default_source = self.payment_method
self.customer.save()
def test___str__(self):
self.assertEqual(str(self.customer), str(self.user))
self.customer.subscriber = None
self.assertEqual(str(self.customer), self.customer.description)
def test_balance(self):
self.assertEqual(self.customer.balance, 0)
self.assertEqual(self.customer.credits, 0)
self.customer.balance = 1000
self.assertEqual(self.customer.balance, 1000)
self.assertEqual(self.customer.credits, 0)
self.assertEqual(self.customer.pending_charges, 1000)
self.customer.balance = -1000
self.assertEqual(self.customer.balance, -1000)
self.assertEqual(self.customer.credits, 1000)
self.assertEqual(self.customer.pending_charges, 0)
def test_customer_dashboard_url(self):
expected_url = f"https://dashboard.stripe.com/{self.customer.djstripe_owner_account.id}/test/customers/{self.customer.id}"
self.assertEqual(self.customer.get_stripe_dashboard_url(), expected_url)
self.customer.livemode = True
expected_url = f"https://dashboard.stripe.com/{self.customer.djstripe_owner_account.id}/customers/{self.customer.id}"
self.assertEqual(self.customer.get_stripe_dashboard_url(), expected_url)
unsaved_customer = Customer()
self.assertEqual(unsaved_customer.get_stripe_dashboard_url(), "")
def test_customer_sync_unsupported_source(self):
fake_customer = deepcopy(FAKE_CUSTOMER_II)
fake_customer["default_source"]["object"] = fake_customer["sources"]["data"][0][
"object"
] = "fish"
user = get_user_model().objects.create_user(
username="test_user_sync_unsupported_source"
)
self.assertRaisesRegex(
ValueError,
"Trying to fit a 'fish' into 'Card'. Aborting.",
fake_customer.create_for_user,
user,
)
def test_customer_sync_has_subscriber_metadata(self):
user = get_user_model().objects.create(username="test_metadata", id=12345)
fake_customer = deepcopy(FAKE_CUSTOMER)
fake_customer["id"] = "cus_sync_has_subscriber_metadata"
fake_customer["metadata"] = {"djstripe_subscriber": "12345"}
customer = Customer.sync_from_stripe_data(fake_customer)
self.assertEqual(customer.subscriber, user)
self.assertEqual(customer.metadata, {"djstripe_subscriber": "12345"})
@override_settings(DJSTRIPE_SUBSCRIBER_CUSTOMER_KEY="")
def test_customer_sync_has_subscriber_metadata_disabled(self):
user = get_user_model().objects.create(
username="test_metadata_disabled", id=98765
)
fake_customer = deepcopy(FAKE_CUSTOMER)
fake_customer["id"] = "cus_test_metadata_disabled"
fake_customer["metadata"] = {"djstripe_subscriber": "98765"}
customer = Customer.sync_from_stripe_data(fake_customer)
self.assertNotEqual(customer.subscriber, user)
self.assertNotEqual(customer.subscriber_id, 98765)
self.assert_fks(
customer,
expected_blank_fks={
"djstripe.Customer.coupon",
"djstripe.Customer.default_payment_method",
"djstripe.Customer.subscriber",
},
)
def test_customer_sync_has_bad_subscriber_metadata(self):
fake_customer = deepcopy(FAKE_CUSTOMER)
fake_customer["id"] = "cus_sync_has_bad_subscriber_metadata"
fake_customer["metadata"] = {"djstripe_subscriber": "does_not_exist"}
customer = Customer.sync_from_stripe_data(fake_customer)
self.assertEqual(customer.subscriber, None)
self.assertEqual(customer.metadata, {"djstripe_subscriber": "does_not_exist"})
self.assert_fks(
customer,
expected_blank_fks={
"djstripe.Customer.coupon",
"djstripe.Customer.default_payment_method",
"djstripe.Customer.subscriber",
},
)
@override_settings(DJSTRIPE_SUBSCRIBER_CUSTOMER_KEY="")
@patch("stripe.Customer.create", autospec=True)
def test_customer_create_metadata_disabled(self, customer_mock):
user = get_user_model().objects.create_user(
username="test_user_create_metadata_disabled"
)
fake_customer = deepcopy(FAKE_CUSTOMER)
fake_customer["id"] = "cus_test_create_metadata_disabled"
customer_mock.return_value = fake_customer
customer = Customer.create(user)
customer_mock.assert_called_once_with(
api_key=djstripe_settings.STRIPE_SECRET_KEY,
email="",
idempotency_key=None,
metadata={},
stripe_account=None,
)
self.assertEqual(customer.metadata, None)
self.assert_fks(
customer,
expected_blank_fks={
"djstripe.Customer.coupon",
"djstripe.Customer.default_payment_method",
"djstripe.Customer.default_source",
},
)
@patch.object(Card, "_get_or_create_from_stripe_object")
@patch("stripe.Customer.retrieve", autospec=True)
@patch(
"stripe.Card.retrieve",
autospec=True,
)
def test_customer_sync_non_local_card(
self, card_retrieve_mock, customer_retrieve_mock, card_get_or_create_mock
):
fake_customer = deepcopy(FAKE_CUSTOMER_II)
fake_customer["id"] = fake_customer["sources"]["data"][0][
"customer"
] = "cus_test_sync_non_local_card"
fake_customer["default_source"]["id"] = fake_customer["sources"]["data"][0][
"id"
] = "card_cus_test_sync_non_local_card"
customer_retrieve_mock.return_value = fake_customer
fake_card = deepcopy(fake_customer["default_source"])
fake_card["customer"] = "cus_test_sync_non_local_card"
card_retrieve_mock.return_value = fake_card
card_get_or_create_mock.return_value = fake_card
user = get_user_model().objects.create_user(
username="test_user_sync_non_local_card"
)
# create a source object so that FAKE_CUSTOMER_III with a default source
# can be created correctly.
fake_source_data = deepcopy(FAKE_SOURCE_II)
fake_source_data["card"] = deepcopy(fake_card)
fake_source_data["customer"] = fake_customer
Source.sync_from_stripe_data(fake_source_data)
customer = fake_customer.create_for_user(user)
self.assertEqual(customer.sources.count(), 1)
self.assertEqual(customer.legacy_cards.count(), 0)
self.assertEqual(
customer.default_source.id, fake_customer["default_source"]["id"]
)
@patch(
"stripe.BankAccount.retrieve",
return_value=FAKE_CUSTOMER_IV["default_source"],
autospec=True,
)
def test_customer_sync_bank_account_source(self, bank_account_retrieve_mock):
fake_customer = deepcopy(FAKE_CUSTOMER_IV)
user = get_user_model().objects.create_user(
username="test_user_sync_bank_account_source"
)
customer = fake_customer.create_for_user(user)
self.assertEqual(customer.deleted, False)
self.assertEqual(customer.sources.count(), 0)
self.assertEqual(customer.legacy_cards.count(), 0)
self.assertEqual(customer.bank_account.count(), 1)
self.assertEqual(
customer.default_source.id, fake_customer["default_source"]["id"]
)
self.assert_fks(
customer,
expected_blank_fks={
"djstripe.Customer.coupon",
"djstripe.Customer.default_payment_method",
},
)
@patch("stripe.Customer.create", autospec=True)
def test_customer_sync_no_sources(self, customer_mock):
fake_customer = deepcopy(FAKE_CUSTOMER)
fake_customer["id"] = "cus_test_sync_no_sources"
fake_customer["default_source"] = None
fake_customer["sources"] = None
customer_mock.return_value = fake_customer
user = get_user_model().objects.create_user(
username="test_user_sync_non_local_card"
)
customer = Customer.create(user)
self.assertEqual(
customer_mock.call_args_list[0][1].get("metadata"),
{"djstripe_subscriber": user.pk},
)
self.assertEqual(customer.sources.count(), 0)
self.assertEqual(customer.legacy_cards.count(), 0)
self.assertEqual(customer.default_source, None)
self.assert_fks(
customer,
expected_blank_fks={
"djstripe.Customer.coupon",
"djstripe.Customer.default_payment_method",
"djstripe.Customer.default_source",
},
)
def test_customer_sync_default_source_string(self):
Customer.objects.all().delete()
Card.objects.all().delete()
customer_fake = deepcopy(FAKE_CUSTOMER)
customer = Customer.sync_from_stripe_data(customer_fake)
self.assertEqual(
customer.default_source.id, customer_fake["default_source"]["id"]
)
self.assertEqual(customer.legacy_cards.count(), 2)
self.assertEqual(len(list(customer.customer_payment_methods)), 2)
self.assert_fks(
customer,
expected_blank_fks={
"djstripe.Customer.coupon",
"djstripe.Customer.default_payment_method",
"djstripe.Customer.subscriber",
},
)
@patch("stripe.Customer.retrieve", autospec=True)
@patch(
"stripe.PaymentMethod.retrieve", return_value=deepcopy(FAKE_PAYMENT_METHOD_I)
)
def test_customer_sync_default_payment_method_string(
self, attach_mock, customer_retrieve_mock
):
Customer.objects.all().delete()
PaymentMethod.objects.all().delete()
customer_fake = deepcopy(FAKE_CUSTOMER)
customer_fake["invoice_settings"][
"default_payment_method"
] = FAKE_PAYMENT_METHOD_I["id"]
customer_retrieve_mock.return_value = customer_fake
customer = Customer.sync_from_stripe_data(customer_fake)
self.assertEqual(
customer.default_payment_method.id,
customer_fake["invoice_settings"]["default_payment_method"],
)
self.assertEqual(customer.payment_methods.count(), 1)
self.assert_fks(
customer,
expected_blank_fks={
"djstripe.Customer.coupon",
"djstripe.Customer.subscriber",
},
)
@patch("stripe.Customer.retrieve", autospec=True)
@patch(
"stripe.PaymentMethod.retrieve", return_value=deepcopy(FAKE_PAYMENT_METHOD_I)
)
def test_customer_sync_null_default_payment_method(
self, attach_mock, customer_retrieve_mock
):
"""Test to make sure a custom'er default_payment_method gets updated to None
if they remove their only attached payment method"""
Customer.objects.all().delete()
PaymentMethod.objects.all().delete()
customer_fake = deepcopy(FAKE_CUSTOMER)
customer_fake["invoice_settings"][
"default_payment_method"
] = FAKE_PAYMENT_METHOD_I["id"]
customer_retrieve_mock.return_value = customer_fake
customer = Customer.sync_from_stripe_data(customer_fake)
self.assertEqual(
customer.default_payment_method.id,
customer_fake["invoice_settings"]["default_payment_method"],
)
self.assertEqual(customer.payment_methods.count(), 1)
self.assert_fks(
customer,
expected_blank_fks={
"djstripe.Customer.coupon",
"djstripe.Customer.subscriber",
},
)
# update customer_retrieve_mock return value
customer_fake = deepcopy(FAKE_CUSTOMER)
customer_fake["invoice_settings"]["default_payment_method"] = None
customer_retrieve_mock.return_value = customer_fake
# now detach the payment method from customer
is_detached = customer.default_payment_method.detach()
assert is_detached is True
# refresh customer from db
customer.refresh_from_db()
self.assertEqual(
customer.default_payment_method,
None,
)
self.assertEqual(customer.payment_methods.count(), 0)
self.assert_fks(
customer,
expected_blank_fks={
"djstripe.Customer.coupon",
"djstripe.Customer.subscriber",
"djstripe.Customer.default_payment_method",
},
)
@patch(
"stripe.Customer.delete_source",
autospec=True,
)
@patch("stripe.Customer.delete", autospec=True)
@patch("stripe.Customer.retrieve", autospec=True)
@patch(
"stripe.Customer.retrieve_source",
side_effect=[deepcopy(FAKE_CARD), deepcopy(FAKE_CARD_III)],
autospec=True,
)
def test_customer_purge_leaves_customer_record(
self,
customer_retrieve_source_mock,
customer_retrieve_fake,
customer_delete_mock,
customer_source_delete_mock,
):
self.customer.purge()
customer = Customer.objects.get(id=self.customer.id)
self.assertTrue(customer.subscriber is None)
self.assertTrue(customer.default_source is None)
self.assertTrue(customer.deleted is True)
self.assertTrue(not customer.legacy_cards.all())
self.assertTrue(not customer.sources.all())
self.assertTrue(get_user_model().objects.filter(pk=self.user.pk).exists())
@patch("stripe.Customer.create", autospec=True)
def test_customer_purge_detaches_sources(
self,
customer_api_create_fake,
):
fake_customer = deepcopy(FAKE_CUSTOMER_III)
customer_api_create_fake.return_value = fake_customer
user = get_user_model().objects.create_user(
username="blah", email=FAKE_CUSTOMER_III["email"]
)
Customer.get_or_create(user)
customer = Customer.sync_from_stripe_data(deepcopy(FAKE_CUSTOMER_III))
self.assertIsNotNone(customer.default_source)
self.assertNotEqual(customer.sources.count(), 0)
with patch("stripe.Customer.delete", autospec=True), patch(
"stripe.Source.retrieve", return_value=deepcopy(FAKE_SOURCE), autospec=True
):
customer.purge()
self.assertIsNone(customer.default_source)
self.assertEqual(customer.sources.count(), 0)
@patch(
"stripe.Customer.create", return_value=deepcopy(FAKE_CUSTOMER_II), autospec=True
)
def test_customer_purge_deletes_idempotency_key(self, customer_api_create_fake):
# We need to call Customer.get_or_create (which setUp doesn't)
# to get an idempotency key
user = get_user_model().objects.create_user(
username="blah", email=FAKE_CUSTOMER_II["email"]
)
idempotency_key_action = "customer:create:{}".format(user.pk)
self.assertFalse(
IdempotencyKey.objects.filter(action=idempotency_key_action).exists()
)
customer, created = Customer.get_or_create(user)
self.assertTrue(
IdempotencyKey.objects.filter(action=idempotency_key_action).exists()
)
with patch("stripe.Customer.delete", autospec=True):
customer.purge()
self.assertFalse(
IdempotencyKey.objects.filter(action=idempotency_key_action).exists()
)
@patch(
"stripe.Customer.delete_source",
autospec=True,
)
@patch("stripe.Customer.delete", autospec=True)
@patch(
"stripe.Customer.retrieve",
side_effect=InvalidRequestError("No such customer:", "blah"),
autospec=True,
)
def test_customer_purge_raises_customer_exception(
self, customer_retrieve_mock, customer_delete_mock, customer_source_delete_mock
):
self.customer.purge()
customer = Customer.objects.get(id=self.customer.id)
self.assertTrue(customer.subscriber is None)
self.assertTrue(customer.default_source is None)
self.assertTrue(not customer.legacy_cards.all())
self.assertTrue(not customer.sources.all())
self.assertTrue(get_user_model().objects.filter(pk=self.user.pk).exists())
customer_delete_mock.assert_called_once_with(
self.customer.id,
api_key=djstripe_settings.STRIPE_SECRET_KEY,
stripe_account=self.customer.djstripe_owner_account.id,
)
self.assertEqual(0, customer_retrieve_mock.call_count)
self.assertEqual(2, customer_source_delete_mock.call_count)
@patch("stripe.Customer.delete_source", autospec=True)
@patch("stripe.Customer.delete", autospec=True)
@patch("stripe.Customer.retrieve", autospec=True)
@patch(
"stripe.Customer.retrieve_source",
return_value=deepcopy(FAKE_CARD),
autospec=True,
)
def test_customer_delete_raises_unexpected_exception(
self,
customer_retrieve_source_mock,
customer_retrieve_mock,
customer_delete_mock,
customer_source_delete_mock,
):
customer_delete_mock.side_effect = InvalidRequestError(
"Unexpected Exception", "blah"
)
with self.assertRaisesMessage(InvalidRequestError, "Unexpected Exception"):
self.customer.purge()
customer_delete_mock.assert_called_once_with(
self.customer.id,
api_key=djstripe_settings.STRIPE_SECRET_KEY,
stripe_account=self.customer.djstripe_owner_account.id,
)
def test_can_charge(self):
with pytest.warns(DeprecationWarning) as record:
self.assertTrue(self.customer.can_charge())
# check that the message matches
assert "Customer.can_charge() is misleading" in record[0].message.args[0]
def test_has_valid_source(self):
assert self.customer.default_source
with pytest.warns(DeprecationWarning) as record:
self.assertTrue(self.customer.has_valid_source())
# check that the message matches
assert "Customer.has_valid_source() is deprecated" in record[0].message.args[0]
@patch(
"stripe.Customer.retrieve", return_value=deepcopy(FAKE_CUSTOMER), autospec=True
)
def test_add_card_set_default_true(self, customer_retrieve_mock):
self.customer.add_card(FAKE_CARD["id"])
self.customer.add_card(FAKE_CARD_III["id"])
self.assertEqual(2, Card.objects.count())
self.assertEqual(FAKE_CARD_III["id"], self.customer.default_source.id)
@patch(
"stripe.Customer.retrieve", return_value=deepcopy(FAKE_CUSTOMER), autospec=True
)
def test_add_card_set_default_false(self, customer_retrieve_mock):
# self.customer already has FAKE_CARD as its default payment method
self.customer.add_card(FAKE_CARD_III["id"], set_default=False)
self.assertEqual(2, Card.objects.count())
self.assertEqual(FAKE_CARD["id"], self.customer.default_source.id)
@patch(
"stripe.Customer.retrieve", return_value=deepcopy(FAKE_CUSTOMER), autospec=True
)
def test_add_card_set_default_false_with_single_card_still_becomes_default(
self, customer_retrieve_mock
):
# delete all already added cards to self.customer
Card.objects.all().delete()
# assert self.customer has no cards
self.assertEqual(0, self.customer.legacy_cards.count())
self.assertEqual(0, self.customer.sources.count())
self.customer.add_card(FAKE_CARD["id"], set_default=False)
# assert new card got added to self.customer
self.assertEqual(1, Card.objects.count())
# self.customer already has FAKE_CARD as its default payment method
self.assertEqual(FAKE_CARD["id"], self.customer.default_source.id)
@patch(
"stripe.Customer.retrieve", return_value=deepcopy(FAKE_CUSTOMER), autospec=True
)
@patch("stripe.PaymentMethod.attach", return_value=deepcopy(FAKE_PAYMENT_METHOD_I))
def test_add_payment_method_obj(self, attach_mock, customer_retrieve_mock):
self.assertEqual(
self.customer.payment_methods.filter(
id=FAKE_PAYMENT_METHOD_I["id"]
).count(),
0,
)
payment_method = PaymentMethod.sync_from_stripe_data(FAKE_PAYMENT_METHOD_I)
payment_method = self.customer.add_payment_method(payment_method)
self.assertEqual(payment_method.customer.id, self.customer.id)
self.assertEqual(
self.customer.payment_methods.filter(
id=FAKE_PAYMENT_METHOD_I["id"]
).count(),
1,
)
self.assertEqual(
self.customer.payment_methods.filter(
id=FAKE_PAYMENT_METHOD_I["id"]
).first(),
self.customer.default_payment_method,
)
self.assertEqual(
self.customer.default_payment_method.id,
self.customer.invoice_settings["default_payment_method"],
)
self.assert_fks(self.customer, expected_blank_fks={"djstripe.Customer.coupon"})
@patch("stripe.Customer.retrieve", autospec=True)
@patch("stripe.PaymentMethod.attach", return_value=deepcopy(FAKE_PAYMENT_METHOD_I))
def test_add_payment_method_set_default_true(
self, attach_mock, customer_retrieve_mock
):
# clear default source so we can check can_charge()
fake_customer = deepcopy(FAKE_CUSTOMER)
fake_customer["default_source"] = None
customer_retrieve_mock.return_value = fake_customer
self.customer.default_source = None
self.customer.save()
self.assertEqual(
self.customer.payment_methods.filter(
id=FAKE_PAYMENT_METHOD_I["id"]
).count(),
0,
)
payment_method = self.customer.add_payment_method(FAKE_PAYMENT_METHOD_I["id"])
self.assertEqual(payment_method.customer.id, self.customer.id)
self.assertEqual(
self.customer.payment_methods.filter(
id=FAKE_PAYMENT_METHOD_I["id"]
).count(),
1,
)
self.assertEqual(
self.customer.payment_methods.filter(
id=FAKE_PAYMENT_METHOD_I["id"]
).first(),
self.customer.default_payment_method,
)
self.assertEqual(
self.customer.default_payment_method.id,
self.customer.invoice_settings["default_payment_method"],
)
with pytest.warns(DeprecationWarning):
self.assertTrue(
self.customer.can_charge(),
"Expect to be able to charge since we've set a default_payment_method",
)
self.assert_fks(
self.customer,
expected_blank_fks={
"djstripe.Customer.coupon",
"djstripe.Customer.default_source",
},
)
@patch("stripe.Customer.retrieve", autospec=True)
@patch("stripe.PaymentMethod.attach", return_value=deepcopy(FAKE_PAYMENT_METHOD_I))
def test_add_payment_method_set_default_false(
self, attach_mock, customer_retrieve_mock
):
# clear default source so we can check can_charge()
fake_customer = deepcopy(FAKE_CUSTOMER)
fake_customer["default_source"] = None
customer_retrieve_mock.return_value = fake_customer
self.customer.default_source = None
self.customer.save()
self.assertEqual(
self.customer.payment_methods.filter(
id=FAKE_PAYMENT_METHOD_I["id"]
).count(),
0,
)
payment_method = self.customer.add_payment_method(
FAKE_PAYMENT_METHOD_I["id"], set_default=False
)
self.assertEqual(payment_method.customer.id, self.customer.id)
self.assertEqual(
self.customer.payment_methods.filter(
id=FAKE_PAYMENT_METHOD_I["id"]
).count(),
1,
)
with pytest.warns(DeprecationWarning):
self.assertFalse(
self.customer.can_charge(),
"Expect not to be able to charge since we've not set a "
"default_payment_method",
)
self.assert_fks(
self.customer,
expected_blank_fks={
"djstripe.Customer.coupon",
"djstripe.Customer.default_payment_method",
"djstripe.Customer.default_source",
},
)
@patch(
"stripe.Customer.retrieve", return_value=deepcopy(FAKE_CUSTOMER), autospec=True
)
def test_cannot_charge(self, customer_retrieve_fake):
self.customer.date_purged = timezone.now()
with pytest.warns(DeprecationWarning):
self.assertFalse(self.customer.can_charge())
def test_charge_accepts_only_decimals(self):
with self.assertRaises(ValueError):
self.customer.charge(10)
@patch("stripe.Coupon.retrieve", return_value=deepcopy(FAKE_COUPON), autospec=True)
@patch(
"stripe.Customer.retrieve", return_value=deepcopy(FAKE_CUSTOMER), autospec=True
)
def test_add_coupon_by_id(self, customer_retrieve_mock, coupon_retrieve_mock):
self.assertEqual(self.customer.coupon, None)
self.customer.add_coupon(FAKE_COUPON["id"])
customer_retrieve_mock.assert_called_once_with(
api_key=djstripe_settings.STRIPE_SECRET_KEY,
expand=ANY,
id=FAKE_CUSTOMER["id"],
stripe_account=self.customer.djstripe_owner_account.id,
)
@patch("stripe.Coupon.retrieve", return_value=deepcopy(FAKE_COUPON), autospec=True)
@patch(
"stripe.Customer.retrieve", return_value=deepcopy(FAKE_CUSTOMER), autospec=True
)
def test_add_coupon_by_object(self, customer_retrieve_mock, coupon_retrieve_mock):
self.assertEqual(self.customer.coupon, None)
coupon = Coupon.sync_from_stripe_data(FAKE_COUPON)
fake_discount = deepcopy(FAKE_DISCOUNT_CUSTOMER)
def fake_customer_save(self, *args, **kwargs):
# fake the api coupon update behaviour
coupon = self.pop("coupon", None)
if coupon:
self["discount"] = fake_discount
else:
self["discount"] = None
return self
with patch("tests.CustomerDict.save", new=fake_customer_save):
self.customer.add_coupon(coupon)
customer_retrieve_mock.assert_called_once_with(
api_key=djstripe_settings.STRIPE_SECRET_KEY,
expand=ANY,
id=FAKE_CUSTOMER["id"],
stripe_account=self.customer.djstripe_owner_account.id,
)
self.customer.refresh_from_db()
self.assert_fks(
self.customer,
expected_blank_fks={"djstripe.Customer.default_payment_method"},
)
@patch(
"djstripe.models.Account.get_default_account",
autospec=True,
)
@patch(
"stripe.BalanceTransaction.retrieve",
return_value=deepcopy(FAKE_BALANCE_TRANSACTION),
autospec=True,
)
@patch("stripe.Charge.retrieve", autospec=True)
@patch("stripe.PaymentIntent.retrieve", autospec=True)
@patch(
"stripe.PaymentMethod.retrieve",
return_value=deepcopy(FAKE_CARD_AS_PAYMENT_METHOD),
autospec=True,
)
def test_refund_charge(
self,
paymentmethod_card_retrieve_mock,
payment_intent_retrieve_mock,
charge_retrieve_mock,
balance_transaction_retrieve_mock,
default_account_mock,
):
default_account_mock.return_value = self.account
fake_charge_no_invoice = deepcopy(FAKE_CHARGE)
fake_charge_no_invoice.update({"invoice": None})
charge_retrieve_mock.return_value = fake_charge_no_invoice
fake_payment_intent = deepcopy(FAKE_PAYMENT_INTENT_I)
fake_payment_intent.update({"invoice": None})
payment_intent_retrieve_mock.return_value = fake_payment_intent
charge, created = Charge._get_or_create_from_stripe_object(
fake_charge_no_invoice
)
self.assertTrue(created)
self.assert_fks(
charge,
expected_blank_fks={
"djstripe.Account.branding_logo",
"djstripe.Account.branding_icon",
"djstripe.Charge.application_fee",
"djstripe.Charge.dispute",
"djstripe.Charge.latest_invoice (related name)",
"djstripe.Charge.latest_upcominginvoice (related name)",
"djstripe.Charge.invoice",
"djstripe.Charge.on_behalf_of",
"djstripe.Charge.source_transfer",
"djstripe.Charge.transfer",
"djstripe.Customer.coupon",
"djstripe.Customer.default_payment_method",
"djstripe.PaymentIntent.invoice (related name)",
"djstripe.PaymentIntent.on_behalf_of",
"djstripe.PaymentIntent.payment_method",
"djstripe.PaymentIntent.upcominginvoice (related name)",
},
)
charge.refund()
refunded_charge, created2 = Charge._get_or_create_from_stripe_object(
fake_charge_no_invoice
)
self.assertFalse(created2)
self.assertEqual(refunded_charge.refunded, True)
self.assertEqual(refunded_charge.amount_refunded, decimal.Decimal("20.00"))
self.assert_fks(
refunded_charge,
expected_blank_fks={
"djstripe.Account.branding_logo",
"djstripe.Account.branding_icon",
"djstripe.Charge.application_fee",
"djstripe.Charge.dispute",
"djstripe.Charge.latest_invoice (related name)",
"djstripe.Charge.latest_upcominginvoice (related name)",
"djstripe.Charge.invoice",
"djstripe.Charge.on_behalf_of",
"djstripe.Charge.source_transfer",
"djstripe.Charge.transfer",
"djstripe.Customer.coupon",
"djstripe.Customer.default_payment_method",
"djstripe.PaymentIntent.invoice (related name)",
"djstripe.PaymentIntent.on_behalf_of",
"djstripe.PaymentIntent.payment_method",
"djstripe.PaymentIntent.upcominginvoice (related name)",
},
)
@patch(
"djstripe.models.Account.get_default_account",
autospec=True,
)
@patch(
"stripe.BalanceTransaction.retrieve",
return_value=deepcopy(FAKE_BALANCE_TRANSACTION),
autospec=True,
)
@patch("stripe.Charge.retrieve", autospec=True)
@patch("stripe.PaymentIntent.retrieve", autospec=True)
@patch(
"stripe.PaymentMethod.retrieve",
return_value=deepcopy(FAKE_CARD_AS_PAYMENT_METHOD),
autospec=True,
)
def test_refund_charge_object_returned(
self,
paymentmethod_card_retrieve_mock,
payment_intent_retrieve_mock,
charge_retrieve_mock,
balance_transaction_retrieve_mock,
default_account_mock,
):
default_account_mock.return_value = self.account
fake_charge_no_invoice = deepcopy(FAKE_CHARGE)
fake_charge_no_invoice.update({"invoice": None})
charge_retrieve_mock.return_value = fake_charge_no_invoice
fake_payment_intent = deepcopy(FAKE_PAYMENT_INTENT_I)
fake_payment_intent.update({"invoice": None})
payment_intent_retrieve_mock.return_value = fake_payment_intent
charge, created = Charge._get_or_create_from_stripe_object(
fake_charge_no_invoice
)
self.assertTrue(created)
self.assert_fks(
charge,
expected_blank_fks={
"djstripe.Account.branding_logo",
"djstripe.Account.branding_icon",
"djstripe.Charge.application_fee",
"djstripe.Charge.dispute",
"djstripe.Charge.latest_invoice (related name)",
"djstripe.Charge.latest_upcominginvoice (related name)",
"djstripe.Charge.invoice",
"djstripe.Charge.on_behalf_of",
"djstripe.Charge.source_transfer",
"djstripe.Charge.transfer",
"djstripe.Customer.coupon",
"djstripe.Customer.default_payment_method",
"djstripe.PaymentIntent.invoice (related name)",
"djstripe.PaymentIntent.on_behalf_of",
"djstripe.PaymentIntent.payment_method",
"djstripe.PaymentIntent.upcominginvoice (related name)",
},
)
refunded_charge = charge.refund()
self.assertEqual(refunded_charge.refunded, True)
self.assertEqual(refunded_charge.amount_refunded, decimal.Decimal("20.00"))
self.assert_fks(
refunded_charge,
expected_blank_fks={
"djstripe.Account.branding_logo",
"djstripe.Account.branding_icon",
"djstripe.Charge.application_fee",
"djstripe.Charge.dispute",
"djstripe.Charge.latest_invoice (related name)",
"djstripe.Charge.latest_upcominginvoice (related name)",