Skip to content

Commit

Permalink
Added tests for new modelformset code. Fixed some PEP8 errors. Fixed …
Browse files Browse the repository at this point in the history
…some failing tests.
  • Loading branch information
mbrochh committed Nov 18, 2011
1 parent 9bf5d7c commit f5a65d5
Show file tree
Hide file tree
Showing 5 changed files with 116 additions and 56 deletions.
4 changes: 3 additions & 1 deletion shop/forms.py
Expand Up @@ -40,7 +40,9 @@ def save(self, *args, **kwargs):
items from the cart when the quantity is set to 0.
"""
quantity = self.cleaned_data['quantity']
self.instance.cart.update_quantity(self.instance.id, quantity)
instance = self.instance.cart.update_quantity(self.instance.id,
quantity)
return instance


def get_cart_item_formset(cart_items=None, data=None):
Expand Down
90 changes: 47 additions & 43 deletions shop/models/defaults/bases.py
Expand Up @@ -23,34 +23,34 @@ class BaseProduct(PolymorphicModel):
Most of the already existing fields here should be generic enough to reside
on the "base model" and not on an added property
"""

name = models.CharField(max_length=255, verbose_name=_('Name'))
slug = models.SlugField(verbose_name=_('Slug'), unique=True)
active = models.BooleanField(default=False, verbose_name=_('Active'))

date_added = models.DateTimeField(auto_now_add=True, verbose_name=_('Date added'))
last_modified = models.DateTimeField(auto_now=True, verbose_name=_('Last modified'))

unit_price = CurrencyField(verbose_name=_('Unit price'))

class Meta(object):
abstract = True
app_label = 'shop'
verbose_name = _('Product')
verbose_name_plural = _('Products')

def __unicode__(self):
return self.name

def get_absolute_url(self):
return reverse('product_detail', args=[self.slug])

def get_price(self):
"""
Return the price for this item (provided for extensibility)
"""
return self.unit_price

def get_name(self):
"""
Return the name of this Product (provided for extensibility)
Expand Down Expand Up @@ -81,12 +81,13 @@ class Meta(object):
verbose_name_plural = _('Carts')

def __init__(self, *args, **kwargs):
super(BaseCart, self).__init__(*args,**kwargs)
super(BaseCart, self).__init__(*args, **kwargs)
# That will hold things like tax totals or total discount
self.subtotal_price = Decimal('0.0')
self.total_price = Decimal('0.0')
self.current_total = Decimal('0.0') # used by cart modifiers
self.extra_price_fields = [] # List of tuples (label, value)
self._updated_cart_items = None

def add_product(self, product, quantity=1, merge=True, queryset=None):
"""
Expand Down Expand Up @@ -153,6 +154,7 @@ def update_quantity(self, cart_item_id, quantity):
cart_item.quantity = quantity
cart_item.save()
self.save()
return cart_item

def delete_item(self, cart_item_id):
"""
Expand All @@ -169,8 +171,8 @@ def get_updated_cart_items(self):
Returns updated cart items after update() has been called and
cart modifiers have been processed for all cart items.
"""
assert hasattr(self, '_updated_cart_items'),\
"Cart needs to be updated before calling get_updated_cart_items."
assert self._updated_cart_items is not None, ('Cart needs to be'
'updated before calling get_updated_cart_items.')
return self._updated_cart_items

def update(self, state=None):
Expand All @@ -189,21 +191,21 @@ def update(self, state=None):
"purchase" button was pressed)
"""
from shop.models import CartItem, Product

# This is a ghetto "select_related" for polymorphic models.
items = CartItem.objects.filter(cart=self)
product_ids = [item.product_id for item in items]
products = Product.objects.filter(id__in=product_ids)
products_dict = dict([(p.id, p) for p in products])

self.extra_price_fields = [] # Reset the price fields
self.subtotal_price = Decimal('0.0') # Reset the subtotal

# This will hold extra information that cart modifiers might want to pass
# to each other
if state == None:
state = {}
state = {}

# This calls all the pre_process_cart methods (if any), before the cart
# is processed. This allows for data collection on the cart for example)
for modifier in cart_modifiers_pool.get_modifiers_list():
Expand All @@ -212,15 +214,15 @@ def update(self, state=None):
for item in items: # For each CartItem (order line)...
item.product = products_dict[item.product_id] #This is still the ghetto select_related
self.subtotal_price = self.subtotal_price + item.update(state)

self.current_total = self.subtotal_price
# Now we have to iterate over the registered modifiers again (unfortunately)
# to pass them the whole Order this time
for modifier in cart_modifiers_pool.get_modifiers_list():
modifier.process_cart(self, state)

self.total_price = self.current_total

# This calls the post_process_cart method from cart modifiers, if any.
# It allows for a last bit of processing on the "finished" cart, before
# it is displayed
Expand Down Expand Up @@ -265,7 +267,7 @@ class Meta(object):
def __init__(self, *args, **kwargs):
# That will hold extra fields to display to the user
# (ex. taxes, discount)
super(BaseCartItem, self).__init__(*args,**kwargs)
super(BaseCartItem, self).__init__(*args, **kwargs)
self.extra_price_fields = [] # list of tuples (label, value)
# These must not be stored, since their components can be changed between
# sessions / logins etc...
Expand All @@ -282,7 +284,7 @@ def update(self, state):
# We now loop over every registered price modifier,
# most of them will simply add a field to extra_payment_fields
modifier.process_cart_item(self, state)

self.line_total = self.current_total
return self.line_total

Expand All @@ -292,17 +294,17 @@ def update(self, state):
#==============================================================================



class BaseOrder(models.Model):
"""
A model representing an Order.
An order is the "in process" counterpart of the shopping cart, which holds
stuff like the shipping and billing addresses (copied from the User profile)
when the Order is first created), list of items, and holds stuff like the
status, shipping costs, taxes, etc...
"""

PROCESSING = 1 # New order, no shipping/payment backend chosen yet
PAYMENT = 2 # The user is filling in payment information
CONFIRMED = 3 # Chosen shipping/payment backend, processing payment
Expand All @@ -318,17 +320,17 @@ class BaseOrder(models.Model):
(SHIPPED, _('Shipped')),
(CANCELLED, _('Cancelled')),
)

# If the user is null, the order was created with a session
user = models.ForeignKey(User, blank=True, null=True,
verbose_name=_('User'))

status = models.IntegerField(choices=STATUS_CODES, default=PROCESSING,
verbose_name=_('Status'))

order_subtotal = CurrencyField(verbose_name=_('Order subtotal'))
order_total = CurrencyField(verbose_name='Order total')

shipping_address_text = models.TextField(_('Shipping address'), blank=True, null=True)
billing_address_text = models.TextField(_('Billing address'), blank=True, null=True)

Expand All @@ -337,7 +339,7 @@ class BaseOrder(models.Model):
verbose_name=_('Created'))
modified = models.DateTimeField(auto_now=True,
verbose_name=_('Updated'))

class Meta(object):
abstract = True
app_label = 'shop'
Expand All @@ -349,34 +351,36 @@ def __unicode__(self):

def get_absolute_url(self):
return reverse('order_detail', kwargs={'pk': self.pk })

def is_payed(self):
"""Has this order been integrally payed for?"""
return self.amount_payed == self.order_total

def is_completed(self):
return self.status == self.COMPLETED

@property
def amount_payed(self):
"""
The amount payed is the sum of related orderpayments
"""
from shop.models import OrderPayment
sum = OrderPayment.objects.filter(order=self).aggregate(sum=Sum('amount'))
result = sum.get('sum')
sum_ = OrderPayment.objects.filter(order=self).aggregate(
sum=Sum('amount'))
result = sum_.get('sum')
if not result:
result = Decimal('-1')
return result

@property
def shipping_costs(self):
from shop.models import ExtraOrderPriceField
sum = Decimal('0.0')
cost_list = ExtraOrderPriceField.objects.filter(order=self).filter(is_shipping=True)
sum_ = Decimal('0.0')
cost_list = ExtraOrderPriceField.objects.filter(order=self).filter(
is_shipping=True)
for cost in cost_list:
sum = sum + cost.value
return sum
sum_ += cost.value
return sum_

def set_billing_address(self, billing_address):
"""
Expand All @@ -388,7 +392,7 @@ def set_billing_address(self, billing_address):
if hasattr(billing_address, 'as_text'):
self.billing_address_text = billing_address.as_text()
self.save()

def set_shipping_address(self, shipping_address):
"""
Process shipping_address trying to get as_text method from address
Expand All @@ -411,21 +415,21 @@ class BaseOrderItem(models.Model):
"""
A line Item for an order.
"""

order = models.ForeignKey(get_model_string('Order'), related_name='items',
verbose_name=_('Order'))

product_reference = models.CharField(max_length=255,
verbose_name=_('Product reference'))
product_name = models.CharField(max_length=255, null=True, blank=True,
verbose_name=_('Product name'))
product = models.ForeignKey(get_model_string('Product'), verbose_name=_('Product'), null=True, blank=True, **f_kwargs)
unit_price = CurrencyField(verbose_name=_('Unit price'))
quantity = models.IntegerField(verbose_name=_('Quantity'))

line_subtotal = CurrencyField(verbose_name=_('Line subtotal'))
line_total = CurrencyField(verbose_name=_('Line total'))

class Meta(object):
abstract = True
app_label = 'shop'
Expand Down
26 changes: 15 additions & 11 deletions shop/tests/__init__.py
@@ -1,34 +1,38 @@
from api import ShopApiTestCase
from cart import CartTestCase
from cart_modifiers import (
from cart_modifiers import (
CartModifiersTestCase,
TenPercentPerItemTaxModifierTestCase,
)
from order import (
OrderConversionTestCase,
from order import (
OrderConversionTestCase,
OrderPaymentTestCase,
OrderTestCase,
OrderTestCase,
OrderUtilTestCase,
)
from forms import (
CartItemModelFormTestCase,
GetCartItemFormsetTestCase,
)
from payment import PayOnDeliveryTestCase, GeneralPaymentBackendTestCase
from product import ProductTestCase, ProductStatisticsTestCase
from shipping import (
FlatRateShippingTestCase,
GeneralShippingBackendTestCase,
ShippingApiTestCase,
GeneralShippingBackendTestCase,
ShippingApiTestCase,
)
from templatetags import ProductsTestCase
from util import (
AddressUtilTestCase,
CartUtilsTestCase,
CurrencyFieldTestCase,
CartUtilsTestCase,
CurrencyFieldTestCase,
LoaderTestCase,
)
from views import (
from views import (
CartDetailsViewTestCase,
CartViewTestCase,
CartViewTestCase,
OrderListViewTestCase,
ProductDetailViewTestCase,
ProductDetailViewTestCase,
)
from views_checkout import (
CheckoutCartToOrderTestCase,
Expand Down
51 changes: 51 additions & 0 deletions shop/tests/forms.py
@@ -0,0 +1,51 @@
# -*- coding: utf-8 -*-
"""Tests for the forms of the django-shop app."""
from django.contrib.auth.models import User
from django.test import TestCase

from shop.forms import CartItemModelForm, get_cart_item_formset
from shop.models.cartmodel import Cart, CartItem
from shop.models.productmodel import Product


class BaseCartItemFormsTestCase(TestCase):
"""Base class for tests related to ``CartItem`` forms and formsets."""

def setUp(self):
self.user = User.objects.create(username="test",
email="test@example.com",
first_name="Test",
last_name = "Tester")
self.cart = Cart.objects.create()
self.product = Product.objects.create(unit_price=123)
self.item = CartItem.objects.create(cart=self.cart, quantity=2,
product=self.product)



class CartItemModelFormTestCase(BaseCartItemFormsTestCase):
"""Tests for the ``CartItemModelForm`` form class."""

def test_setting_quantity_to_0_removes_cart_item(self):
data = {
'quantity': '0',
}
form = CartItemModelForm(instance=self.item, data=data)
self.assertEqual(len(form.errors), 0)
form.save()
self.assertEqual(0, CartItem.objects.all().count())


class GetCartItemFormsetTestCase(BaseCartItemFormsTestCase):
"""Tests for the ``get_cart_item_formset()`` method."""

def test_should_return_formset(self):
items = CartItem.objects.all()
formset = get_cart_item_formset(cart_items=items)
self.assertTrue('quantity' in formset.forms[0].fields)

def test_cart_items_should_have_updated_values(self):
self.cart.update()
items = self.cart.get_updated_cart_items()
formset = get_cart_item_formset(cart_items=items)
self.assertEqual(formset.forms[0].instance.line_subtotal, 246)
1 change: 0 additions & 1 deletion shop/views/cart.py
Expand Up @@ -108,7 +108,6 @@ def get_context_data(self, **kwargs):
cart_object.update(state)
ctx.update({'cart': cart_object})
ctx.update({'cart_items': cart_object.get_updated_cart_items()})

return ctx

def get(self, request, *args, **kwargs):
Expand Down

0 comments on commit f5a65d5

Please sign in to comment.