--- unittest.py.orig 2008-11-26 20:29:55.000000000 -0700 +++ unittest.py 2008-11-26 20:57:08.000000000 -0700 @@ -149,6 +149,21 @@ (_strclass(self.__class__), self.testsRun, len(self.errors), len(self.failures)) +class AssertRaisesContext: + def __init__(self, exc, test_case): + self.exc = exc + self.test_case = test_case + def __enter__(self): + pass + def __exit__(self, exc_type, exc_value, traceback): + if exc_type is None: + raise self.test_case.failureException( + "{exc!s} not raised".format(exc=self.exc)) + if not issubclass(exc_type, self.exc): + raise self.test_case.failureException( + "{exc!s} not raised".format(exc=self.exc)) from exc_value + return True + class TestCase: """A class whose instances are single test cases. @@ -299,14 +314,22 @@ """Fail the test unless the expression is true.""" if not expr: raise self.failureException(msg) - def failUnlessRaises(self, excClass, callableObj, *args, **kwargs): + def failUnlessRaises(self, excClass, callableObj=None, *args, **kwargs): """Fail unless an exception of class excClass is thrown by callableObj when invoked with arguments args and keyword arguments kwargs. If a different type of exception is thrown, it will not be caught, and the test case will be deemed to have suffered an error, exactly as for an unexpected exception. + + If called with callableObj omitted or None, will return a + context object used like this:: + + with self.failUnlessRaises(some_error_class): + do_something() """ + if callableObj is None: + return AssertRaisesContext(excClass, self) try: callableObj(*args, **kwargs) except excClass: