Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Middleware #9

Open
wants to merge 17 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ django-cart is a very simple application that just let you add and remove items
## Prerequisites

- Django 1.1+
- django content type framework in your INSTALLED_APPS
- django content type framework in your INSTALLED\_APPS
- south for migrations (optional)

## Installation
Expand Down
87 changes: 0 additions & 87 deletions cart/cart.py

This file was deleted.

16 changes: 16 additions & 0 deletions cart/middleware.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from django.utils import timezone

import models

CART_ID = 'CART-ID'


class CartMiddleware(object):

def process_request(self, request):
try:
cart_id = request.session[CART_ID]
request.cart = models.Cart.objects.get(pk=cart_id)
except (KeyError, models.Cart.DoesNotExist):
request.cart = models.Cart.objects.create(creation_date=timezone.now())
request.session[CART_ID] = request.cart.pk
64 changes: 51 additions & 13 deletions cart/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,6 @@
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

class Cart(models.Model):
creation_date = models.DateTimeField(verbose_name=_('creation date'))
checked_out = models.BooleanField(default=False, verbose_name=_('checked out'))

class Meta:
verbose_name = _('cart')
verbose_name_plural = _('carts')
ordering = ('-creation_date',)

def __unicode__(self):
return unicode(self.creation_date)

class ItemManager(models.Manager):
def get(self, *args, **kwargs):
Expand All @@ -23,8 +12,9 @@ def get(self, *args, **kwargs):
del(kwargs['product'])
return super(ItemManager, self).get(*args, **kwargs)


class Item(models.Model):
cart = models.ForeignKey(Cart, verbose_name=_('cart'))
cart = models.ForeignKey('Cart', verbose_name=_('cart'))
quantity = models.PositiveIntegerField(verbose_name=_('quantity'))
unit_price = models.DecimalField(max_digits=18, decimal_places=2, verbose_name=_('unit price'))
# product as generic relation
Expand All @@ -47,11 +37,59 @@ def total_price(self):

# product
def get_product(self):
return self.content_type.get_object_for_this_type(id=self.object_id)
return self.content_type.get_object_for_this_type(pk=self.object_id)

def set_product(self, product):
self.content_type = ContentType.objects.get_for_model(type(product))
self.object_id = product.pk

product = property(get_product, set_product)


class ProductDoesNotExist(Exception):

def __init__(self, product):
self.product = product


class Cart(models.Model):
creation_date = models.DateTimeField(verbose_name=_('creation date'))
checked_out = models.BooleanField(default=False, verbose_name=_('checked out'))

def is_empty(self):
return self.item_count() == 0

def empty(self):
for item in self.items():
item.delete()

def items(self):
return list(self.item_set.all())

def item_count(self):
return len(self.items())

def add_item(self, item, unit_price=0, quantity=1):
try:
item = Item.objects.get(cart=self, product=item, unit_price=unit_price)
item.quantity += quantity
item.save()
except Item.DoesNotExist:
item = Item.objects.create(cart=self, product=item, unit_price=unit_price, quantity=quantity)

def remove_item(self, item):
try:
Item.objects.get(cart=self, product=item).delete()
except Item.DoesNotExist:
raise ProductDoesNotExist(item)

def summary(self):
return sum(item.total_price for item in self.items())

class Meta:
verbose_name = _('cart')
verbose_name_plural = _('carts')
ordering = ('-creation_date',)

def __unicode__(self):
return unicode(self.creation_date)
160 changes: 157 additions & 3 deletions cart/tests.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
from django.core.exceptions import ImproperlyConfigured
from django.test import TestCase
from models import Cart, Item
from django.test.client import RequestFactory
from django.utils import timezone
from models import Cart, Item, ProductDoesNotExist
from django.contrib.auth.models import User
import datetime
from decimal import Decimal

import middleware


class CartAndItemModelsTestCase(TestCase):

def _create_cart_in_database(self, creation_date=datetime.datetime.now(),
def _create_cart_in_database(self, creation_date=timezone.now(),
checked_out=False):
"""
Helper function so I don't repeat myself
Expand Down Expand Up @@ -41,7 +47,7 @@ def _create_user_in_database(self):
return user

def test_cart_creation(self):
creation_date = datetime.datetime.now()
creation_date = timezone.now()
cart = self._create_cart_in_database(creation_date)
id = cart.id

Expand Down Expand Up @@ -108,3 +114,151 @@ def test_item_unicode(self):
item = self._create_item_in_database(cart, product=user, quantity=3, unit_price=Decimal("100"))

self.assertEquals(item.__unicode__(), "3 units of User")


class CartAddItemTests(TestCase):

def setUp(self):
self.cart = Cart.objects.create(creation_date=timezone.now())
self.item = User.objects.create_user(username='test-user', password='')

def test_with_nonexistent_item(self):
self.assertEqual(Item.objects.count(), 0)

self.cart.add_item(self.item)

self.assertEqual(self.cart.item_set.count(), 1)

def test_with_existing_item_adds_to_quantity(self):
self.assertEqual(Item.objects.count(), 0)

self.cart.add_item(self.item, quantity=1)
self.cart.add_item(self.item, quantity=1)

self.assertEqual(self.cart.item_set.count(), 1)
self.assertEqual(self.cart.item_set.all()[0].quantity, 2)


class CartRemoveItemTests(TestCase):

def setUp(self):
self.cart = Cart.objects.create(creation_date=timezone.now())
self.item = User.objects.create_user(username='test-user', password='')

def test_remove_item_that_exists(self):
self.cart.add_item(self.item)
self.assertEqual(Item.objects.count(), 1)

self.cart.remove_item(self.item)
self.assertEqual(self.cart.item_set.count(), 0)
self.assertEqual(Item.objects.count(), 0)

def test_remove_item_that_does_not_exist_raises_ProductDoesNotExist(self):
self.assertEqual(Item.objects.count(), 0)

self.assertRaises(ProductDoesNotExist, self.cart.remove_item, self.item)


class CartItemsTests(TestCase):

def setUp(self):
self.cart = Cart.objects.create(creation_date=timezone.now())

def test_empty_items(self):
self.assertEqual(self.cart.items(), [])

def test_items(self):
item = User.objects.create_user(username='test-user', password='')
self.cart.add_item(item)

self.assertEqual(self.cart.items(), list(Item.objects.all()))


class CartSummaryTests(TestCase):

def setUp(self):
self.cart = Cart.objects.create(creation_date=timezone.now())
self.item = User.objects.create_user(username='test-user', password='')

def test_zero(self):
self.assertEqual(self.cart.summary(), 0)

def test_summary(self):
self.cart.add_item(self.item, unit_price=100)

self.assertEqual(self.cart.summary(), 100)

def test_summary_with_quantity(self):
self.cart.add_item(self.item, unit_price=100, quantity=3)

self.assertEqual(self.cart.summary(), 300)


class CartEmptyTests(TestCase):

def setUp(self):
self.cart = Cart.objects.create(creation_date=timezone.now())

def test_already_empty(self):
self.cart.empty()
self.assertTrue(self.cart.is_empty())

def test_empty(self):
item = User.objects.create_user(username='test-user', password='')

self.cart.add_item(item)
self.assertFalse(self.cart.is_empty())

self.cart.empty()
self.assertTrue(self.cart.is_empty())


class CartItemCountTests(TestCase):

def setUp(self):
self.cart = Cart.objects.create(creation_date=timezone.now())

def test_zero(self):
self.assertEqual(self.cart.item_count(), 0)

def test_item_count(self):
item1 = User.objects.create_user(username='test-user1', password='')
item2 = User.objects.create_user(username='test-user2', password='')
self.cart.add_item(item1)
self.cart.add_item(item2)

self.assertEqual(self.cart.item_count(), 2)


class CartMiddlewareTests(TestCase):
SESSION_CART_ID = 'CART-ID'

def setUp(self):
self.request = RequestFactory().get('')
self.request.session = {}

self.cart_middleware = middleware.CartMiddleware()

def test_no_cart_in_session(self):
self.cart_middleware.process_request(self.request)

assert hasattr(self.request, 'cart')
self.assertEqual(self.request.cart, Cart.objects.get(id=1))
self.assertEqual(self.request.session[CartMiddlewareTests.SESSION_CART_ID], 1)

def test_cart_in_session(self):
Cart.objects.create(creation_date=timezone.now())
self.request.session[CartMiddlewareTests.SESSION_CART_ID] = 1

self.cart_middleware.process_request(self.request)

self.assertEqual(self.request.cart.id, 1)
self.assertEqual(self.request.session[CartMiddlewareTests.SESSION_CART_ID], 1)

def test_invalid_cart_in_session(self):
self.request.session[CartMiddlewareTests.SESSION_CART_ID] = 2

self.cart_middleware.process_request(self.request)

self.assertEqual(self.request.cart.id, 1)
self.assertEqual(self.request.session[CartMiddlewareTests.SESSION_CART_ID], 1)
10 changes: 10 additions & 0 deletions manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#!/usr/bin/env python
import os
import sys

if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")

from django.core.management import execute_from_command_line

execute_from_command_line(sys.argv)
Empty file added project/__init__.py
Empty file.
Loading