do_something()
The context manager will store the caught exception object in its
- :attr:`exc_value` attribute. This can be useful if the intention
+ :attr:`exception` attribute. This can be useful if the intention
is to perform additional checks on the exception raised::
with self.assertRaises(SomeException) as cm:
do_something()
- the_exception = cm.exc_value
+ the_exception = cm.exception
self.assertEqual(the_exception.error_code, 3)
- .. versionchanged:: 3.1
+ .. versionchanged:: 3.1
Added the ability to use :meth:`assertRaises` as a context manager.
+ .. versionchanged:: 3.2
+ Added the :attr:`exception` attribute.
+
.. deprecated:: 3.1
:meth:`failUnlessRaises`.
- .. versionchanged:: 3.2
- Added the :attr:`exc_value` attribute.
-
.. method:: assertRaisesRegexp(exception, regexp[, callable, ...])
# a good chance that it won't be imported when this test is run
module_name = 'audioop'
- import sys
if module_name in sys.modules:
del sys.modules[module_name]
# a good chance that it won't be imported when this test is run
module_name = 'audioop'
- import sys
if module_name in sys.modules:
del sys.modules[module_name]
# methods. Contains formatted tracebacks instead
# of sys.exc_info() results."
def test_addFailure(self):
- import sys
-
class Foo(unittest.TestCase):
def test_1(self):
pass
# methods. Contains formatted tracebacks instead
# of sys.exc_info() results."
def test_addError(self):
- import sys
-
class Foo(unittest.TestCase):
def test_1(self):
pass
ctx = self.assertRaises(ExceptionMock)
with ctx:
Stub(v)
- e = ctx.exc_value
+ e = ctx.exception
self.assertIsInstance(e, ExceptionMock)
self.assertEqual(e.args[0], v)
pass
else:
self.fail("assertRaises() didn't let exception pass through")
- with self.assertRaises(KeyError):
- raise KeyError
+ with self.assertRaises(KeyError) as cm:
+ try:
+ raise KeyError
+ except Exception as e:
+ exc = e
+ raise
+ self.assertIs(cm.exception, exc)
+
with self.assertRaises(KeyError):
raise KeyError("key")
try:
self.expected_regex = expected_regexp
def __enter__(self):
- pass
+ return self
def __exit__(self, exc_type, exc_value, tb):
if exc_type is None:
if not issubclass(exc_type, self.expected):
# let unexpected exceptions pass through
return False
- #store exception, without traceback, for later retrieval
- self.exc_value = exc_value.with_traceback(None)
+ # store exception, without traceback, for later retrieval
+ self.exception = exc_value.with_traceback(None)
if self.expected_regex is None:
return True
do_something()
The context manager keeps a reference to the exception as
- the exc_value attribute. This allows you to inspect the
+ the 'exception' attribute. This allows you to inspect the
exception after the assertion::
with self.assertRaises(SomeException) as cm:
do_something()
- the_exception = cm.exc_value
+ the_exception = cm.exception
self.assertEqual(the_exception.error_code, 3)
"""
context = _AssertRaisesContext(excClass, self, callableObj)