Daryl Spitzer Daryl Spitzer - 1 year ago 107
Python Question

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

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

Moe Moe
Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download