diff options
author | Matthew Lemon <y@yulqen.org> | 2024-09-09 17:24:53 +0100 |
---|---|---|
committer | Matthew Lemon <y@yulqen.org> | 2024-09-09 17:24:53 +0100 |
commit | 7550f31f604fa45f9030a32b9b8fbc2d0739bed7 (patch) | |
tree | 0ca1863f5ecaeaefba1e448e9e356a0e5c282ed8 | |
parent | 0bef50c8097ab52df424c94176e913dcb1d8f7f5 (diff) |
subscription and user is now uniquely constrained
-rw-r--r-- | pyblackbird_cc/payments/models.py | 3 | ||||
-rw-r--r-- | pyblackbird_cc/payments/tests/test_models.py | 25 |
2 files changed, 28 insertions, 0 deletions
diff --git a/pyblackbird_cc/payments/models.py b/pyblackbird_cc/payments/models.py index cbf462c..174e3fe 100644 --- a/pyblackbird_cc/payments/models.py +++ b/pyblackbird_cc/payments/models.py @@ -57,5 +57,8 @@ class Subscription(models.Model): start_date = models.DateTimeField(null=True, blank=True) end_date = models.DateTimeField(null=True, blank=True) + class Meta: + constraints = [models.UniqueConstraint(fields=["user", "plan"], name="unique_user_plan")] + def __str__(self): return f"Subscription for {self.user.username}" diff --git a/pyblackbird_cc/payments/tests/test_models.py b/pyblackbird_cc/payments/tests/test_models.py index 132d025..467d6e4 100644 --- a/pyblackbird_cc/payments/tests/test_models.py +++ b/pyblackbird_cc/payments/tests/test_models.py @@ -1,6 +1,7 @@ import pytest from allauth.account.signals import user_signed_up from django.contrib.auth import get_user_model +from django.db import IntegrityError from django.test import RequestFactory from pyblackbird_cc.payments.models import Subscription @@ -15,6 +16,30 @@ def user_data(): @pytest.mark.django_db +def test_subscription_user_unique(): + # Ensure the free plan exists + free_plan, _ = SubscriptionPlan.objects.get_or_create( + name="Free Plan", + defaults={ + "price": 0, + "description": "Free plan description", + "allowed_downloads": 10, + }, + ) + + # Create a new user + user_data = {"email": "testuser@example.com", "password": "testpassword123"} + user = User.objects.create_user(**user_data) + + # Create a subscription for the user + subscription = Subscription.objects.create(user=user, plan=free_plan) + + # Try to create another subscription for the same user + with pytest.raises(IntegrityError): + Subscription.objects.create(user=user, plan=free_plan) + + +@pytest.mark.django_db def test_user_signup_assigns_free_subscription(user_data): # Ensure the free plan exists free_plan, _ = SubscriptionPlan.objects.get_or_create( |