BartD BartD - 1 year ago 99
Python Question

How should we test exceptions with nose?

I'm testing exceptions with nose. Here's an example:

def testDeleteUserUserNotFound(self):
"Test exception is raised when trying to delete non-existent users"
# make nose fail here
except UserNotFoundException:
assert True

The assert is executed if the exception is raised, but if no exception is raised, it won't be executed.

Is there anything I can put on the commented line above so that if no exception is raised nose will report a failure?

Answer Source

nose provides tools for testing exceptions (like unittest does). Try this example (and read about the other tools at Nose Testing Tools

from import *

l = []
d = dict()

def test_Exception1():
    '''this test should pass'''

def test_Exception2():
    '''this test should pass'''

def test_Exception3():
    '''this test should fail (IndexError raised but KeyError was expected)'''

def test_Exception4():
    '''this test should fail with KeyError'''

I would think that this is the proper way that you were looking for because it lets you be specific about the exceptions that you expect or want. So you actually provoke the error to see that it raises the right exception. And then you let nose evaluate the result. (Put as little logic into the unit tests as possible!)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download