I am trying to assertRaise the exception inside a function where a condition raises a custom exception message .
Function:
if not Cart.objects.filter(member=member).count():
raise CartDoesNotExist("Cart Does Not Exist for Member: %s ( %id )." % (member.email,member.id))
Now , i am able to successfully produce the required condition to get to the raise statement.
So , my testcase looks like this :
def Order_CartDoesNotExist(self):
self.assertRaises(CartDoesNotExist,Order.objects.create_order(member=self.member2,member_slot=self.memslot,order_type="Normal"))
When i run the test , the output is an Error . It gives the same error CartDoesNotExist…..
So my question is , how to raise these kind of exceptions ? How to cover these situations in our unittest? I do not want to escape these conditions as they are important and increase code coverage?
Thank you all.
Your code is calling create_order directly, which raises the exception. You need to change how it is called. In Python 2.7, you can use this:
Here the context manager allows you to call your code directly, and the context manager will handle the exception for you.
If you are running with 2.6 or below:
Here you aren’t calling your function, you are passing it to assertRaises, along with the arguments it needs, and assertRaises will call the code and deal with the exception properly.