Index: Doc/library/unittest.rst =================================================================== --- Doc/library/unittest.rst (revision 73271) +++ Doc/library/unittest.rst (working copy) @@ -881,6 +881,7 @@ error if another exception is raised, or fails if no exception is raised. To catch any of a group of exceptions, a tuple containing the exception classes may be passed as *exception*. + Returns the exception object caught so that it can be futher validated. If *callable* is omitted or None, returns a context manager so that the code under test can be written inline rather than as a function:: @@ -888,8 +889,12 @@ with self.failUnlessRaises(some_error_class): do_something() + The context manager will store the caught exception object in its + :attr:`exc_value` attribute. + .. versionchanged:: 2.7 Added the ability to use :meth:`assertRaises` as a context manager. + Made the method return the caught exception object .. deprecated:: 2.7 :meth:`failUnlessRaises`. Index: Lib/test/test_unittest.py =================================================================== --- Lib/test/test_unittest.py (revision 73271) +++ Lib/test/test_unittest.py (working copy) @@ -2820,6 +2820,29 @@ self.assertRaisesRegexp, Exception, re.compile('^Expected$'), Stub) + def testAssertRaisesReturn(self): + class ExceptionMock(Exception): + pass + + def Stub(foo): + raise ExceptionMock(foo) + v = "particular value" + + e = self.assertRaises(ExceptionMock, Stub, v) + self.assertTrue(isinstance(e, ExceptionMock)) + self.assertEqual(e.args[0], v) + + e = self.assertRaisesRegexp(ExceptionMock, re.compile(v), Stub, v) + self.assertTrue(isinstance(e, ExceptionMock)) + self.assertEqual(e.args[0], v) + + ctx = self.assertRaises(ExceptionMock) + with ctx: + Stub(v) + e = ctx.exc_value + self.assertTrue(isinstance(e, ExceptionMock)) + self.assertEqual(e.args[0], v) + def testSynonymAssertMethodNames(self): """Test undocumented method name synonyms. Index: Lib/unittest.py =================================================================== --- Lib/unittest.py (revision 73271) +++ Lib/unittest.py (working copy) @@ -291,6 +291,9 @@ if not issubclass(exc_type, self.expected): # let unexpected exceptions pass through return False + + self.exc_value = exc_value #store for later retrieval + if self.expected_regex is None: return True @@ -589,6 +592,7 @@ return context with context: callableObj(*args, **kwargs) + return context.exc_value def _getAssertEqualityFunc(self, first, second): """Get a detailed comparison function for the types of the two args. @@ -1009,6 +1013,7 @@ return context with context: callable_obj(*args, **kwargs) + return context.exc_value def assertRegexpMatches(self, text, expected_regex, msg=None): if isinstance(expected_regex, basestring):