aboutsummaryrefslogtreecommitdiffstats
path: root/pyblackbird_cc/payments
diff options
context:
space:
mode:
Diffstat (limited to 'pyblackbird_cc/payments')
-rw-r--r--pyblackbird_cc/payments/models.py3
-rw-r--r--pyblackbird_cc/payments/tests/test_models.py26
2 files changed, 29 insertions, 0 deletions
diff --git a/pyblackbird_cc/payments/models.py b/pyblackbird_cc/payments/models.py
index 81bb1c8..b947a22 100644
--- a/pyblackbird_cc/payments/models.py
+++ b/pyblackbird_cc/payments/models.py
@@ -1,4 +1,5 @@
from django.conf import settings
+from django.core.exceptions import ValidationError
from django.db import models
from pyblackbird_cc.resources.models import Resource
@@ -27,6 +28,8 @@ class ShoppingCart(models.Model):
return f"Shopping Cart for {self.user.username}"
def add_resource(self, resource: Resource):
+ if CartItem.objects.filter(cart=self, resource=resource).exists():
+ raise ValidationError(f"{resource.name} is already in your shopping cart.")
item, created = CartItem.objects.get_or_create(
cart=self,
resource=resource,
diff --git a/pyblackbird_cc/payments/tests/test_models.py b/pyblackbird_cc/payments/tests/test_models.py
index fd26fea..4dab6e3 100644
--- a/pyblackbird_cc/payments/tests/test_models.py
+++ b/pyblackbird_cc/payments/tests/test_models.py
@@ -1,3 +1,4 @@
+from django.core.exceptions import ValidationError
import pytest
from allauth.account.signals import user_signed_up
from django.contrib.auth import get_user_model
@@ -86,3 +87,28 @@ def test_cart_item_is_created_when_resource_is_added_to_cart(user_data, resource
users_cart = ShoppingCart.objects.get(user=user)
users_cart.add_resource(resource)
assert users_cart.items.count() == 1 # type: ignore
+
+
+@pytest.mark.django_db
+def test_cannot_add_the_same_resource_to_cart_twice(user_data, resource):
+ user = User.objects.create_user(**user_data) # type: ignore
+ request = RequestFactory().get("/")
+ user_signed_up.send(sender=user.__class__, request=request, user=user)
+ users_cart = ShoppingCart.objects.get(user=user)
+ users_cart.add_resource(resource)
+ assert users_cart.items.count() == 1 # type: ignore
+ with pytest.raises(ValidationError):
+ users_cart.add_resource(resource)
+
+
+@pytest.mark.django_db
+def test_can_add_multiple_different_items_to_cart(user_data, resources):
+ user = User.objects.create_user(**user_data) # type: ignore
+ request = RequestFactory().get("/")
+ user_signed_up.send(sender=user.__class__, request=request, user=user)
+ users_cart = ShoppingCart.objects.get(user=user)
+ users_cart.add_resource(resources[0])
+ users_cart.add_resource(resources[1])
+ users_cart.add_resource(resources[2])
+ users_cart.add_resource(resources[3])
+ assert users_cart.items.count() == 4 # type: ignore