nosetests 断言GreaterEqual

nosetests assertGreaterEqual

我已经为一个函数编写了单元测试,但我似乎无法理解错误的含义。

这是应用 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

下面描述了我写下的单元测试。

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 总是 returns 并且错误 type error '>=' not supported between instance of int and str。我想要实现的是确保 calculatePrice 中的 total_price 不超过余额。如果确实引发错误以通知用户

我将不胜感激任何人的帮助。谢谢

问题来了,如果买不到,total_amount应该是0,不是字符串。由于 calculatePrice 应该总是 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