Search code examples
pythonnosetests

How to use nose's assert_raises?


I've searched for documentation, but couldn't find any. There were a couple that didn't explain much.

Can someone explain to me Nose's

assert_raises(what should I put here?)

function and how to use it?


Solution

  • The assert_raises() function tests to make sure a function call raises a specified exception when presented with certain parameters.

    For example, if you had a function add that adds two numbers, it should probably raise a TypeError when you pass it, say, an integer and a string. So:

    from nose.tools import assert_raises
    
    def add(x, y):
        return x + y
    
    assert_raises(TypeError, add, 2, "0")
    

    The first argument is the exception type you expect. The second is the function to call. The rest of the arguments will be passed to the function (in this case, they will become x and y inside the function).

    If the expected exception is raised by the function, the assertion passes.