views:

78

answers:

3

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..

A: 

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.

protobuf
A: 

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;
sza
+1  A: 

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.

nailxx