Luke Lee

Software Engineer

Web + Desktop + Science

Fork me on Github

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:

self.assertRaises(KeyError, mydict[mykey])

Lambda to the rescue!

self.assertRaises(KeyError, lambda: mydict[mykey])

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.

Published: 06-13-2012 19:01:00

lukelee.net