1

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"
toriningen
  • 7,196
  • 3
  • 46
  • 68
user2511126
  • 620
  • 1
  • 14
  • 31

2 Answers2

5

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

Community
  • 1
  • 1
toriningen
  • 7,196
  • 3
  • 46
  • 68
  • alright thanks for your response. I will try it and respond you. – user2511126 Feb 27 '14 at 00:57
  • I tried using this: and its still not working, its throwing an error. self.assertRaises(IndexError, lambda: value[0]["ID"]) – user2511126 Feb 27 '14 at 05:41
  • "value" contains an array and I am not worried about the print at the end. I just want to use self.assertRaises function to evaluate if the array contains ID. – user2511126 Feb 27 '14 at 05:58
  • 1
    Well, that's because accessing missing key on dicts raises `KeyError`, not `IndexError`, which is raised on missing indices. So you're basically asserting for wrong exception — try `assertRaises(KeyError, lambda: value[0]["ID"])` instead. – toriningen Feb 28 '14 at 01:44
1

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)
radekholy24
  • 418
  • 2
  • 12