How do you test that a Python function throws an exception?

Daryl Spitzer picture Daryl Spitzer · Sep 24, 2008 · Viewed 496k times · Source

How does one write a unittest that fails only if a function doesn't throw an expected exception?

Answer

Moe picture Moe · Sep 24, 2008

Use TestCase.assertRaises (or TestCase.failUnlessRaises) from the unittest module, for example:

import mymod

class MyTestCase(unittest.TestCase):
    def test1(self):
        self.assertRaises(SomeCoolException, mymod.myfunc)