diff options
| author | Ezio Melotti <ezio.melotti@gmail.com> | 2010-08-02 18:10:09 (GMT) |
|---|---|---|
| committer | Ezio Melotti <ezio.melotti@gmail.com> | 2010-08-02 18:10:09 (GMT) |
| commit | f613f352d05cafbec6c4524c67f3eed00a0c4857 (patch) | |
| tree | fe0e22ba0c4a6de17a04580c26cf19c8cc136528 /Lib/test/test_support.py | |
| parent | 800a354fa946d777b8df92e5b0bd07e92f6f9a3b (diff) | |
| download | cpython-f613f352d05cafbec6c4524c67f3eed00a0c4857.zip cpython-f613f352d05cafbec6c4524c67f3eed00a0c4857.tar.gz cpython-f613f352d05cafbec6c4524c67f3eed00a0c4857.tar.bz2 | |
Merged revisions 78758 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r78758 | florent.xicluna | 2010-03-07 14:18:33 +0200 (Sun, 07 Mar 2010) | 4 lines
Issue #7849: Now the utility ``check_warnings`` verifies if the warnings are
effectively raised. A new utility ``check_py3k_warnings`` deals with py3k warnings.
........
Diffstat (limited to 'Lib/test/test_support.py')
| -rw-r--r-- | Lib/test/test_support.py | 99 |
1 files changed, 90 insertions, 9 deletions
diff --git a/Lib/test/test_support.py b/Lib/test/test_support.py index d4b891e..7400b0d 100644 --- a/Lib/test/test_support.py +++ b/Lib/test/test_support.py @@ -11,6 +11,7 @@ import os import shutil import warnings import unittest +import re __all__ = ["Error", "TestFailed", "TestSkipped", "ResourceDenied", "import_module", "verbose", "use_resources", "max_memuse", "record_original_stdout", @@ -18,8 +19,8 @@ __all__ = ["Error", "TestFailed", "TestSkipped", "ResourceDenied", "import_modul "is_resource_enabled", "requires", "find_unused_port", "bind_port", "fcmp", "have_unicode", "is_jython", "TESTFN", "HOST", "FUZZ", "findfile", "verify", "vereq", "sortdict", "check_syntax_error", - "open_urlresource", "check_warnings", "CleanImport", - "EnvironmentVarGuard", "captured_output", + "open_urlresource", "check_warnings", "_check_py3k_warnings", + "CleanImport", "EnvironmentVarGuard", "captured_output", "captured_stdout", "TransientResource", "transient_internet", "run_with_locale", "set_memlimit", "bigmemtest", "bigaddrspacetest", "BasicTestRunner", "run_unittest", "run_doctest", "threading_setup", @@ -406,22 +407,103 @@ class WarningsRecorder(object): entry to the warnings.catch_warnings() context manager. """ def __init__(self, warnings_list): - self.warnings = warnings_list + self._warnings = warnings_list + self._last = 0 def __getattr__(self, attr): - if self.warnings: - return getattr(self.warnings[-1], attr) + if len(self._warnings) > self._last: + return getattr(self._warnings[-1], attr) elif attr in warnings.WarningMessage._WARNING_DETAILS: return None raise AttributeError("%r has no attribute %r" % (self, attr)) + @property + def warnings(self): + return self._warnings[self._last:] + def reset(self): - del self.warnings[:] + self._last = len(self._warnings) -@contextlib.contextmanager -def check_warnings(): + +def _filterwarnings(filters, quiet=False): + """Catch the warnings, then check if all the expected + warnings have been raised and re-raise unexpected warnings. + If 'quiet' is True, only re-raise the unexpected warnings. + """ + # Clear the warning registry of the calling module + # in order to re-raise the warnings. + frame = sys._getframe(2) + registry = frame.f_globals.get('__warningregistry__') + if registry: + registry.clear() with warnings.catch_warnings(record=True) as w: + # Disable filters, to record all warnings. Because + # test_warnings swap the module, we need to look up + # in the sys.modules dictionary. + sys.modules['warnings'].resetwarnings() yield WarningsRecorder(w) + # Filter the recorded warnings + reraise = [warning.message for warning in w] + missing = [] + for msg, cat in filters: + seen = False + for exc in reraise[:]: + message = str(exc) + # Filter out the matching messages + if (re.match(msg, message, re.I) and + issubclass(exc.__class__, cat)): + seen = True + reraise.remove(exc) + if not seen and not quiet: + # This filter caught nothing + missing.append((msg, cat.__name__)) + for exc in reraise: + raise AssertionError("unhandled warning %r" % exc) + for filter in missing: + raise AssertionError("filter (%r, %s) did not caught any warning" % + filter) + + +@contextlib.contextmanager +def check_warnings(*filters, **kwargs): + """Context manager to silence warnings. + + Accept 2-tuples as positional arguments: + ("message regexp", WarningCategory) + + Optional argument: + - if 'quiet' is True, it does not fail if a filter catches nothing + (default False) + + Without argument, it defaults to: + check_warnings(("", Warning), quiet=False) + """ + if not filters: + filters = (("", Warning),) + return _filterwarnings(filters, kwargs.get('quiet')) + + +@contextlib.contextmanager +def _check_py3k_warnings(*filters, **kwargs): + """Context manager to silence py3k warnings. + + Accept 2-tuples as positional arguments: + ("message regexp", WarningCategory) + + Optional argument: + - if 'quiet' is True, it does not fail if a filter catches nothing + (default False) + + Without argument, it defaults to: + _check_py3k_warnings(("", DeprecationWarning), quiet=False) + """ + if sys.py3kwarning: + if not filters: + filters = (("", DeprecationWarning),) + else: + # It should not raise any py3k warning + filters = () + return _filterwarnings(filters, kwargs.get('quiet')) class CleanImport(object): @@ -595,7 +677,6 @@ _4G = 4 * _1G MAX_Py_ssize_t = sys.maxsize def set_memlimit(limit): - import re global max_memuse global real_max_memuse sizes = { |
