Skip to content

Commit

Permalink
Add AssertRaisesContext.exc_val
Browse files Browse the repository at this point in the history
  • Loading branch information
srittau committed Oct 19, 2019
1 parent c19c27a commit fed14cb
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 1 deletion.
9 changes: 9 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,15 @@ with assert_raises(KeyError) as context:
...
```

* Add `AssertRaisesContext.exc_val` property to access the caught
exception after leaving the context manager:

```python
with assert_raises(KeyError) as context:
...
assert_equal("expected message", str(context.exc_val))
```

News in asserts 0.9.1
=====================

Expand Down
10 changes: 9 additions & 1 deletion asserts/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -880,16 +880,18 @@ def __init__(self, exception, msg_fmt="{msg}"):
self.exception = exception
self.msg_fmt = msg_fmt
self._exc_type = exception
self._exc_val = None
self._exception_name = getattr(exception, "__name__", str(exception))
self._tests = []

def __enter__(self):
return self

def __exit__(self, exc_type, exc_val, exc_tb):
if not exc_type:
if not exc_type or not exc_val:
msg = "{} not raised".format(self._exception_name)
fail(self.format_message(msg))
self._exc_val = exc_val
if not issubclass(exc_type, self.exception):
return False
for test in self._tests:
Expand All @@ -913,6 +915,12 @@ class was raised. The callback will get the raised exception as only
"""
self._tests.append(cb)

@property
def exc_val(self):
if self._exc_val is None:
raise RuntimeError("must be called after leaving the context")
return self._exc_val


class AssertRaisesRegexContext(AssertRaisesContext):

Expand Down
2 changes: 2 additions & 0 deletions asserts/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ class AssertRaisesContext(Generic[_E]):
) -> bool: ...
def format_message(self, default_msg: Text) -> Text: ...
def add_test(self, cb: Callable[[_E], Any]) -> None: ...
@property
def exc_val(self) -> _E: ...

class AssertRaisesErrnoContext(AssertRaisesContext[_E]):
expected_errno: int
Expand Down
11 changes: 11 additions & 0 deletions test_asserts.py
Original file line number Diff line number Diff line change
Expand Up @@ -936,6 +936,17 @@ def test_assert_raises__raises_right_exception(self):
with assert_raises(KeyError):
raise KeyError()

def test_assert_raises__exc_val(self):
exc = KeyError()
with assert_raises(KeyError) as context:
raise exc
assert_is(exc, context.exc_val)

def test_assert_raises__exc_val_within_context(self):
with assert_raises(RuntimeError):
with assert_raises(KeyError) as context:
context.exc_val

def test_assert_raises__raises_subclass(self):
class MyError(IndexError):
pass
Expand Down

0 comments on commit fed14cb

Please sign in to comment.