Krzysztof Żuraw
Krzysztof Żuraw

Reputation: 107

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?

Upvotes: 2

Views: 554

Answers (1)

falsetru
falsetru

Reputation: 368914

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

Upvotes: 4

Related Questions