Unittest in Django. How do I get the exception message from assertRaises ()?

I used assertRaises () to check that an exception will be thrown and there is no problem with that.

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

+2


a source to share


3 answers


I am using the following decorator, inspired by one of 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()

      

@decorator

is from decorator . You can write the decorator by hand if for some reason you don't want to inject a dependency.

+2


a source


If different exception messages constitute a different checkable condition, they should probably be two different exceptions. However, they can easily inherit from the same base exception class, so your other exception handling code doesn't have to change.



0


a source


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

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

      

0


a source







All Articles