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 to share