2

I used the assertRaises() to validation there will be an exception thrown and there is no problem of this.

My question is, is there any way to get the exception message from assertRaises()? I would like to assert for different types of exceptiosn as well by parsing the exception message..

3 Answers 3

2

I use following decorator inspired by one in nose:

def raises(exception, message):
    @decorator
    def decorate(func, *args, **kwargs):
        name = func.__name__
        try:
            func(*args, **kwargs)
        except exception, e:
            if message is not None:
                assert_equal(str(e), message)
        except:
            raise
        else:
            msg = "%s() did not raise %s" % (name, exception.__name__)
            raise AssertionError(msg)
    return decorate

So I can do something like:

class TestMyThing(TestCase):
    @raises(ValueError, "T should not exceed 100, but has value 120")
    def test(self):
        some_code_that_provoke_exception()

The @decorator is from decorator package. You can write decorator by hands if you don't want to introduce a dependency for some reason.

0

If the different exception messages amount to a different testable condition, they should probably be two different exceptions. They can easily inherit from the same base exception class, however, so your other exception handling code would not necessarily need to change.

0

I just figured out the solution, just create a wrapper class, and use this to assert the exception.

@staticmethod
def assertRaises(exception, apicall, *args, **kwargs):
    try:
        apicall(*args, **kwargs)
    except exception as e:
        return e
    finally:
        pass;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.