Permalink
Browse files

Added unit tests for accounts.

Raise ValueError if sum to withdraw or deposit is less than zero.
Raise ValueError if sum to withdraw is larger than balance.
Fixed bugs in models.
  • Loading branch information...
1 parent 2771c27 commit 0ea01981993198921307b7e1545bfc91a06417d7 @jautero committed Jun 30, 2011
Showing with 34 additions and 10 deletions.
  1. +7 −3 limuweb/tilit/models.py
  2. +27 −7 limuweb/tilit/tests.py
View
10 limuweb/tilit/models.py
@@ -9,9 +9,13 @@ class Account(models.Model):
def __unicode__(self):
return self.name
def deposit(self,sum):
- balance += sum
+ if sum<0:
+ raise ValueError(sum)
+ self.balance += sum
def withdraw(self,sum):
- balance -= sum
+ if sum<0 or sum>self.balance:
+ raise ValueError(sum)
+ self.balance -= sum
class AccountCode(models.Model):
account = models.ForeignKey(Account, related_name='account_codes')
@@ -21,7 +25,7 @@ def __unicode__(self):
return u'%s - %s' % (self.product, self.code)
class Meta:
- ordering = ["product"]
+ ordering = ["account"]
@classmethod
def get_or_code(self, code):
View
34 limuweb/tilit/tests.py
@@ -6,11 +6,31 @@
"""
from django.test import TestCase
+from tilit.models import Account
-
-class SimpleTest(TestCase):
- def test_basic_addition(self):
- """
- Tests that 1 + 1 always equals 2.
- """
- self.assertEqual(1 + 1, 2)
+class AccountTest(TestCase):
+ def setUp(self):
+ "Create two accounts: one with balance of 20 and one with balance of 0."
+ self.account1=Account.objects.create(name="Account 1",balance=20)
+ self.account2=Account.objects.create(name="Account 2",balance=0)
+ def test_deposit(self):
+ "Deposit 10 euros on both accounts and check balance."
+ self.account1.deposit(10)
+ self.account2.deposit(10)
+ self.assertEqual(self.account1.balance, 30)
+ self.assertEqual(self.account2.balance, 10)
+ def test_withdraw(self):
+ "Withdraw 10 euros from both accounts and check balance."
+ self.account1.withdraw(10)
+ with self.assertRaises(ValueError):
+ self.account2.withdraw(10)
+ self.assertEqual(self.account1.balance, 10)
+ self.assertEqual(self.account2.balance, 0)
+ def test_negatives(self):
+ "Test that trying to withdraw or deposit negative sums don't work."
+ with self.assertRaises(ValueError):
+ self.account1.deposit(-10)
+ with self.assertRaises(ValueError):
+ self.account2.withdraw(-10)
+ self.assertEqual(self.account1.balance,20)
+ self.assertEqual(self.account2.balance,0)

0 comments on commit 0ea0198

Please sign in to comment.