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"
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 caseassertRaises
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:
Or you can work this way, if you need to resolve single expression (statements won't work in lambdas):
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 makevalue
single-element tuple, usefoo = (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 yourprint()
.