Skip to content

Commit

Permalink
Update Subscription.cancel for compatibility with 2018-08-23
Browse files Browse the repository at this point in the history
  • Loading branch information
imacek authored and jleclanche committed Sep 5, 2018
1 parent 4d4975d commit 8f1fa8b
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 15 deletions.
31 changes: 18 additions & 13 deletions djstripe/models/billing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1125,19 +1125,24 @@ def cancel(self, at_period_end=djstripe_settings.CANCELLATION_AT_PERIOD_END):
if self.trial_end and self.trial_end > timezone.now():
at_period_end = False

try:
stripe_subscription = self._api_delete(at_period_end=at_period_end)
except InvalidRequestError as exc:
if "No such subscription:" in str(exc):
# cancel() works by deleting the subscription. The object still
# exists in Stripe however, and can still be retrieved.
# If the subscription was already canceled (status=canceled),
# that api_retrieve() call will fail with "No such subscription".
# However, this may also happen if the subscription legitimately
# does not exist, in which case the following line will re-raise.
stripe_subscription = self.api_retrieve()
else:
raise
if at_period_end:
stripe_subscription = self.api_retrieve()
stripe_subscription.cancel_at_period_end = True
stripe_subscription.save()
else:
try:
stripe_subscription = self._api_delete()
except InvalidRequestError as exc:
if "No such subscription:" in str(exc):
# cancel() works by deleting the subscription. The object still
# exists in Stripe however, and can still be retrieved.
# If the subscription was already canceled (status=canceled),
# that api_retrieve() call will fail with "No such subscription".
# However, this may also happen if the subscription legitimately
# does not exist, in which case the following line will re-raise.
stripe_subscription = self.api_retrieve()
else:
raise

return Subscription.sync_from_stripe_data(stripe_subscription)

Expand Down
4 changes: 2 additions & 2 deletions tests/test_subscription.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ def test_cancel_already_canceled(self, subscription_retrieve_mock, subscription_
subscription = Subscription.sync_from_stripe_data(subscription_fake)

self.assertEqual(Subscription.objects.filter(status="canceled").count(), 0)
subscription.cancel()
subscription.cancel(at_period_end=False)
self.assertEqual(Subscription.objects.filter(status="canceled").count(), 1)

@patch("djstripe.models.Subscription._api_delete")
Expand All @@ -318,4 +318,4 @@ def test_cancel_error_in_cancel(self, subscription_delete_mock):
subscription = Subscription.sync_from_stripe_data(subscription_fake)

with self.assertRaises(InvalidRequestError):
subscription.cancel()
subscription.cancel(at_period_end=False)

0 comments on commit 8f1fa8b

Please sign in to comment.