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()
.