From e2a77980b630dfcfdd2c934534c4a8847b93b927 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kristj=C3=A1n=20Valur=20J=C3=B3nsson?= Date: Thu, 27 Aug 2009 22:20:21 +0000 Subject: issue 6275 Add an "exc_value" attribute to the _AssertRaisesContext context manager in the unittest package. This allows further tests on the exception that was raised after the context manager exits. --- Doc/library/unittest.rst | 4 ++++ Lib/test/test_unittest.py | 15 +++++++++++++++ Lib/unittest/case.py | 1 + 3 files changed, 20 insertions(+) diff --git a/Doc/library/unittest.rst b/Doc/library/unittest.rst index 25d792d..a2d4478 100644 --- a/Doc/library/unittest.rst +++ b/Doc/library/unittest.rst @@ -888,6 +888,10 @@ Test cases with self.failUnlessRaises(some_error_class): do_something() + The context manager will store the caught exception object in its + :attr:`exc_value` attribute. This can be useful if the intention + is to perform additional checks on the exception raised. + .. versionchanged:: 2.7 Added the ability to use :meth:`assertRaises` as a context manager. diff --git a/Lib/test/test_unittest.py b/Lib/test/test_unittest.py index cca1836..5c3921d 100644 --- a/Lib/test/test_unittest.py +++ b/Lib/test/test_unittest.py @@ -2821,6 +2821,21 @@ test case self.assertRaisesRegexp, Exception, re.compile('^Expected$'), Stub) + def testAssertRaisesExcValue(self): + class ExceptionMock(Exception): + pass + + def Stub(foo): + raise ExceptionMock(foo) + v = "particular value" + + 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. diff --git a/Lib/unittest/case.py b/Lib/unittest/case.py index 6ffdacb..d52bc8d 100644 --- a/Lib/unittest/case.py +++ b/Lib/unittest/case.py @@ -104,6 +104,7 @@ class _AssertRaisesContext(object): 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 -- cgit v0.12