Search code examples
pythontestingnosetests

Python nosetest ValueError exception


I have some function:

def reverse_number(num):
    try:
        return int(num)
    except ValueError:
        return "Please provide number"

and test for this:

assert_raises(ValueError, reverse.reverse_number, "error")

But when I call nosetests I got this error:

AssertionError: ValueError not raised

What am I doing wrong?


Solution

  • The function reverse_number catches the exception, preveting the exception to be raised; cause the assertion failure because assert_raises call expects the function call raises the ValueError exception.

    Simply not catching the exception, you can get what you want:

    def reverse_number(num):
        return int(num)
    

    Or, you can catch the exception, do something, and re-raise the exception using raise statement:

    def reverse_number(num):
        try:
            return int(num)
        except ValueError:
            # do something
            raise  # <--- re-raise the exception