BartD BartD - 1 month ago 23
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"
try:
self.client.deleteUser('10000001-0000-0000-1000-100000000000')
# 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

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

from nose.tools import *

l = []
d = dict()

@raises(Exception)
def test_Exception1():
    '''this test should pass'''
    l.pop()

@raises(KeyError)
def test_Exception2():
    '''this test should pass'''
    d[1]

@raises(KeyError)
def test_Exception3():
    '''this test should fail (IndexError raised but KeyError was expected)'''
    l.pop()

def test_Exception4():
    '''this test should fail with KeyError'''
    d[1]

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!)