A beginner level question.. trying to understand how I can best use the built-in unittest. In the trivial example below, the method consume_food picks a food item and then I am calling food.cut() method.
In future, this method may return instance of Drink object. The #commented code indicates one possible future implementation. In this case, self.milk will not have the cut method defined.
I want to add a unit test for consume_food and pick_food methods. I would like to do this for the original implementation first and then change it after adding self.milk functionality.
EDIT: The intention is to write a unit test for an existing api, so that I can capture any such changes ( i.e. absence of Drink.cut method) forcing me to update the methods and unit tests.
Can someone please help showing me how to write a unit test for this example?
class Fruit:
def cut(self):
print("cut the fruit")
class Drink:
def pour(self):
print("pour the drink")
class A:
def __init__(self):
self.apple = Fruit()
self.banana=Fruit()
#self.milk = Drink()
#self.liquid_diet = True
def consume_food(self):
food = pick_food()
food.cut()
print("consuming the food")
def pick_food(self):
return self.apple
#if self.liquid_diet: return self.milk
#return self.apple
consume_foodassumes that all foods can be cut. If you write a unittest that relies on being able to callfood.cut(), then it will fail if you add foods that do not have.cut(). That is unavoidable; you can't write a test that will always keep working no matter how you change the API. So I don't really understand what your question is.consume_foodat all will do that.Drink.cutmethod)... yes, I can add some hasattr/ assertion or isinstance condition, but the thing I wanted to learn is , 'can I use unittest' here? if so how to write one? can someone please show me for this example please? I understand that it will need to be changed in future.