I have written a unit test for a function but i cant seem to get what the error means.
Here's the app class
class ShoppingList(object):
cart = {} # A dictionary to hold item_name:price as key:value
balance = 0
budget_amount = 0 # one wouldn't want to shop for more than is available
def __init__(self, budget_amount):
self.budget_amount = budget_amount
# a method to add items to the cart dictionary
def addItem(self, item_name, price, quantity):
# declare argument types and check they are use correctly
number_types = ( int, float, complex)
if isinstance(price, number_types) and isinstance(quantity, number_types) and isinstance(item_name, str):
self.cart[item_name] = price
total_cost = self.calculatePrice(price, quantity)
self.balance = self.budget_amount - total_cost
else:
raise ValueError
# a method to calculate total cost
def calculatePrice(self, price, quantity):
total_amount = price * quantity
#check total doesnt exceed balance we have
if total_amount > self.balance:
return("That amount is more than what we have")
return total_amount
And the unit tests that i put down are described below.
import unittest
from app.shoppinglist import ShoppingList
# a class to contain test cases for the shopping list
class ShoppingListTest( unittest.TestCase ):
def setUp(self):
budget_amount = 500
self.shoppingList = ShoppingList(budget_amount)
# method to test value types in addItem
def test_addItem_method_returns_error_for_nonInt(self):
self.assertRaises(ValueError, self.shoppingList.addItem, 1, "one", "thirty")
# method to check if quantity arg is not a number
def test_addItem_method_returns_error_for_quantityArg_string(self):
self.assertRaises( ValueError, self.shoppingList.addItem, "rice", "four", 400)
# method to check if price arg is not a number
def test_addItem_method_returns_error_for_priceArg_string(self):
self.assertRaises( ValueError, self.shoppingList.addItem, "Water", 4, "hundred")
# check if calculatePrice raises an error if total cost exceeds budget cost
def test_calculatePrice_returns_err_for_exceedingBudget(self):
result = self.shoppingList.calculatePrice( 2, 150)
self.assertGreaterEqual(self.shoppingList.balance, result)
When i run the tests calculatePrice
always returns and error that type error '>=' not supported between instance of int and str
. What i want to achieve is make sure that the total_price in calculatePrice doesnt exceed the balance. If it does raise an error to notify user
I will appreciate any help from anyone. Thank you
Here's the problem, if you cannot buy it, the total_amount should be 0, not a string. Due to calculatePrice should always return number
def calculatePrice(self, price, quantity):
total_amount = price * quantity
#check total doesnt exceed balance we have
if total_amount > self.balance:
print("That amount is more than what we have")
return 0
return total_amount