Careful with your assertRaises() and inheritance of exceptions
10 April 2013
This took me by surprise today!
If you run this unit test, it actually passes with flying colors:
import unittest class BadAssError(TypeError): pass def foo(): raise BadAssError("d'oh") class Test(unittest.TestCase): def test(self): self.assertRaises(BadAssError, foo) self.assertRaises(TypeError, foo) self.assertRaises(Exception, foo) if __name__ == '__main__': unittest.main()
assertRaises doesn't just take the exception that is being raised and accepts it, it also takes any of the raised exceptions' parents.
I've only tested it with Python 2.6 and 2.7. And the same works equally with unittest2.
I don't really know how I feel about this. It did surprise me when I was changing one of the exceptions and expected the old tests to break but they didn't. I mean, if I want to write a test that really makes sure the exception really is
BadAssError it means I can't use