views:

202

answers:

3

I know about unittest Python module.

I know about assertRaises() method of TestCase class.

I would like to write a test that succeeds when an exception is not raised.

Any hints please?

+6  A: 
def runTest(self):
    try:
        doStuff()
    except:
        self.fail("Encountered an unexpected exception.")

UPDATE: As liw.fi mentions, the default result is a success, so the example above is something of an antipattern. You should probably only use it if you want to do something special before failing. You should also catch the most specific exceptions possible.

Hank Gay
Not to be pedantic, but Python uses try...except, not try...catch
Joe Holloway
Thanks - the 'answer before coffee' gotcha strikes again.
Hank Gay
A: 

I’m not very familiar with Python, but maybe the sys.exc_info() method can help you with something like:

sys.exc_info() == (None, None, None)
Gumbo
+7  A: 

The test runner will catch all exceptions you didn't assert would be raised. Thus:

doStuff()
self.assert_(True)

This should work fine. You can leave out the self.assert_ call, since it doesn't really do anything. I like to put it there to document that I didn't forget an assertion.

Lars Wirzenius