Skip to content

Commit

Permalink
MAINT: Refactor _AssertRaisesContextManager
Browse files Browse the repository at this point in the history
Rewrite _AssertRaisesContextManager with more
documentation and remove vestigial assertRaises.

Follow-up to pandas-devgh-16089.
  • Loading branch information
gfyoung committed Apr 22, 2017
1 parent c847884 commit fa17b1d
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 24 deletions.
5 changes: 3 additions & 2 deletions pandas/tests/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ class CheckImmutable(object):
mutable_regex = re.compile('does not support mutable operations')

def check_mutable_error(self, *args, **kwargs):
# pass whatever functions you normally would to assertRaises (after the
# Exception kind)
# Pass whatever function you normally would to assertRaisesRegexp
# (after the Exception kind).
tm.assertRaisesRegexp(TypeError, self.mutable_regex, *args, **kwargs)

def test_no_mutable_funcs(self):
Expand All @@ -70,6 +70,7 @@ def delslice():

self.check_mutable_error(delslice)
mutable_methods = getattr(self, "mutable_methods", [])

for meth in mutable_methods:
self.check_mutable_error(getattr(self.container, meth))

Expand Down
83 changes: 61 additions & 22 deletions pandas/util/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2500,40 +2500,79 @@ def assertRaisesRegexp(_exception, _regexp, _callable=None, *args, **kwargs):

class _AssertRaisesContextmanager(object):
"""
Handles the behind the scenes work
for assertRaises and assertRaisesRegexp
Context manager behind assertRaisesRegexp.
"""

def __init__(self, exception, regexp=None, *args, **kwargs):
def __init__(self, exception, regexp=None):
"""
Initialize an _AssertRaisesContextManager instance.
Parameters
----------
exception : class
The expected Exception class.
regexp : str, default None
The regex to compare against the Exception message.
"""

self.exception = exception

if regexp is not None and not hasattr(regexp, "search"):
regexp = re.compile(regexp, re.DOTALL)

self.regexp = regexp

def __enter__(self):
return self

def __exit__(self, exc_type, exc_value, traceback):
def __exit__(self, exc_type, exc_value, trace_back):
expected = self.exception
if not exc_type:
name = getattr(expected, "__name__", str(expected))
raise AssertionError("{0} not raised.".format(name))
if issubclass(exc_type, expected):
return self.handle_success(exc_type, exc_value, traceback)
return self.handle_failure(exc_type, exc_value, traceback)

def handle_failure(*args, **kwargs):
# Failed, so allow Exception to bubble up
return False

def handle_success(self, exc_type, exc_value, traceback):
if self.regexp is not None:
val = str(exc_value)
if not self.regexp.search(val):
e = AssertionError('"%s" does not match "%s"' %
(self.regexp.pattern, str(val)))
raise_with_traceback(e, traceback)
return True
if not exc_type:
exp_name = getattr(expected, "__name__", str(expected))
raise AssertionError("{0} not raised.".format(exp_name))

return self.exception_matches(exc_type, exc_value, trace_back)

def exception_matches(self, exc_type, exc_value, trace_back):
"""
Check that the Exception raised matches the expected Exception
and expected error message regular expression.
Parameters
----------
exc_type : class
The type of Exception raised.
exc_value : Exception
The instance of `exc_type` raised.
trace_back : stack trace object
The traceback object associated with `exc_value`.
Returns
-------
is_matched : bool
Whether or not the Exception raised matches the expected
Exception class and expected error message regular expression.
Raises
------
AssertionError : The error message provided does not match
the expected error message regular expression.
"""

if issubclass(exc_type, self.exception):
if self.regexp is not None:
val = str(exc_value)

if not self.regexp.search(val):
e = AssertionError('"%s" does not match "%s"' %
(self.regexp.pattern, str(val)))
raise_with_traceback(e, trace_back)

return True
else:
# Failed, so allow Exception to bubble up.
return False


@contextmanager
Expand Down

0 comments on commit fa17b1d

Please sign in to comment.