Python self.assertRaises

5.3k Views Asked by At

I have a small code as below, please help me how to write this in a correct way. I want to check if ID is present in the value and if not then it raises an exception.

value = ({'av' : '123', 'user' : 'abc', 'version' : 'xyz'})

with self.assertRaises(IndexError, value[0]["ID"]):
    print "not an error"
2

There are 2 best solutions below

4
On

Problem with your code is that value[0]["ID"] is just an arbitrary argument, and in Python arguments are evaluated before performing function call. So in your case assertRaises has no chance to intercept error, as it's not being called.

I guess you're looking for this snippet, if you wish to stick with context manager based approach, which is useful in case you need to evaluate statements or multiple expressions at once:

with self.assertRaises(IndexError):
    value[0]["ID"]

Or you can work this way, if you need to resolve single expression (statements won't work in lambdas):

self.assertRaises(IndexError, lambda: value[0]["ID"])

For additional information on this, take a look at this question, as it seemingly addresses your issue regarding how to properly use assertRaises.

Also please note in your case value is just dict, not tuple, despite parentheses — in order to make value single-element tuple, use foo = (bar, ) syntax — trailing coma is needed to distinguish from precedence override parentheses, like in (2 + 2) * 3.

Also in unit-testing you don't generally need to output anything related to status of your assertions — in case it passes or fails it's job of unit-testing framework to form appropriate report. But if you are willing to print it anyway, just include print() after your assertion — because if assertion fails, test stops running, and control won't reach your print().

0
On

In case you did not insist on the assertRaises method, I would rather choose assertIn:

value = ({'av' : '123', 'user' : 'abc', 'version' : 'xyz'})
self.assertIn('ID', value)