diff options
author | Serhiy Storchaka <storchaka@gmail.com> | 2015-05-21 17:15:40 (GMT) |
---|---|---|
committer | Serhiy Storchaka <storchaka@gmail.com> | 2015-05-21 17:15:40 (GMT) |
commit | 041dd8eef105f981693f7084b270481816dd9a7a (patch) | |
tree | 9fdcf84d365a2c2e6bcf318fab0649e8655b4b09 /Lib/unittest/case.py | |
parent | ff54223606d899c57912dc9f1c5d0d0f331f96b8 (diff) | |
download | cpython-041dd8eef105f981693f7084b270481816dd9a7a.zip cpython-041dd8eef105f981693f7084b270481816dd9a7a.tar.gz cpython-041dd8eef105f981693f7084b270481816dd9a7a.tar.bz2 |
Issue #15836: assertRaises(), assertRaisesRegex(), assertWarns() and
assertWarnsRegex() assertments now check the type of the first argument
to prevent possible user error. Based on patch by Daniel Wagner-Hall.
Diffstat (limited to 'Lib/unittest/case.py')
-rw-r--r-- | Lib/unittest/case.py | 13 |
1 files changed, 13 insertions, 0 deletions
diff --git a/Lib/unittest/case.py b/Lib/unittest/case.py index befad61..7701ad3 100644 --- a/Lib/unittest/case.py +++ b/Lib/unittest/case.py @@ -119,6 +119,10 @@ def expectedFailure(test_item): test_item.__unittest_expecting_failure__ = True return test_item +def _is_subtype(expected, basetype): + if isinstance(expected, tuple): + return all(_is_subtype(e, basetype) for e in expected) + return isinstance(expected, type) and issubclass(expected, basetype) class _BaseTestCaseContext: @@ -148,6 +152,9 @@ class _AssertRaisesBaseContext(_BaseTestCaseContext): If args is not empty, call a callable passing positional and keyword arguments. """ + if not _is_subtype(self.expected, self._base_type): + raise TypeError('%s() arg 1 must be %s' % + (name, self._base_type_str)) if args and args[0] is None: warnings.warn("callable is None", DeprecationWarning, 3) @@ -172,6 +179,9 @@ class _AssertRaisesBaseContext(_BaseTestCaseContext): class _AssertRaisesContext(_AssertRaisesBaseContext): """A context manager used to implement TestCase.assertRaises* methods.""" + _base_type = BaseException + _base_type_str = 'an exception type or tuple of exception types' + def __enter__(self): return self @@ -206,6 +216,9 @@ class _AssertRaisesContext(_AssertRaisesBaseContext): class _AssertWarnsContext(_AssertRaisesBaseContext): """A context manager used to implement TestCase.assertWarns* methods.""" + _base_type = Warning + _base_type_str = 'a warning type or tuple of warning types' + def __enter__(self): # The __warningregistry__'s need to be in a pristine state for tests # to work properly. |