Dictionary KeyError with assertRaises¶
Have you ever wanted to write a unit test that verifies a key doesn't exist in a dictionary? If so, you've probably done it several ways:
self.assertIn('mykey', mydict.keys())
try:
tmp = mydict[mykey]
except KeyError:
pass
else:
self.fail()
self.assertEqual(mydict.get(mykey), None)
self.assertIsNone(mydict.get(mykey))
You can probably come up with various other ways using self.assertListEqual(), etc. However, none of these test the actual statement mydict[mykey], except the long try/except code above. I know that essentially using dict.get() does the same thing, etc. I still don't think it's as good.
Fortunately there is a special assert statement in the unittest module just for an occasion like this. However, it only takes a callable so that rules out something like this:
Lambda to the rescue!
Using lambda turns our dictionary lookup into a callable which allows us to pass a single statement anywhere a function or a callable object is required.
This is a great testing use-case for this nice little anonymous function. It allows us to test the statement exactly as it would appear in code with the assertRaises() method.