我已经为一个函数写了一个单元测试,但是我似乎不能理解这个错误意味着什么。
下面是app类
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 arguement 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下面描述了我写下的单元测试。
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)当我运行测试时,calculatePrice总是返回并错误那个type error '>=' not supported between instance of int and str。我想要实现的是确保calculatePrice中的total_price不会超出平衡。如果它确实引发错误来通知用户
我将感谢任何人的帮助。谢谢
发布于 2017-08-27 16:55:59
这就是问题所在,如果你买不到它,total_amount应该是0,而不是字符串。由于calculatePrice应始终返回数字
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_amounthttps://stackoverflow.com/questions/45903174
复制相似问题