Commit 1cd0247a authored by Brett Cannon's avatar Brett Cannon

Merged revisions 66321 via svnmerge from

svn+ssh://pythondev@svn.python.org/python/trunk

........
  r66321 | brett.cannon | 2008-09-08 17:49:16 -0700 (Mon, 08 Sep 2008) | 7 lines

  warnings.catch_warnings() now returns a list or None instead of the custom
  WarningsRecorder object. This makes the API simpler to use as no special object
  must be learned.

  Closes issue 3781.
  Review by Benjamin Peterson.
........
parent 4c19e6e0
......@@ -160,6 +160,67 @@ ImportWarning can also be enabled explicitly in Python code using::
warnings.simplefilter('default', ImportWarning)
.. _warning-suppress:
Temporarily Suppressing Warnings
--------------------------------
If you are using code that you know will raise a warning, such some deprecated
function, but do not want to see the warning, then suppress the warning using
the :class:`catch_warnings` context manager::
import warnings
def fxn():
warnings.warn("deprecated", DeprecationWarning)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
fxn()
While within the context manager all warnings will simply be ignored. This
allows you to use known-deprecated code without having to see the warning while
not suppressing the warning for other code that might not be aware of its use
of deprecated code.
.. _warning-testing:
Testing Warnings
----------------
To test warnings raised by code, use the :class:`catch_warnings` context
manager. With it you can temporarily mutate the warnings filter to facilitate
your testing. For instance, do the following to capture all raised warnings to
check::
import warnings
def fxn():
warnings.warn("deprecated", DeprecationWarning)
with warnings.catch_warnings(record=True) as w:
# Cause all warnings to always be triggered.
warnings.simplefilter("always")
# Trigger a warning.
fxn()
# Verify some things
assert len(w) == 1
assert isinstance(w[-1].category, DeprecationWarning)
assert "deprecated" in str(w[-1].message)
One can also cause all warnings to be exceptions by using ``error`` instead of
``always``. One thing to be aware of is that if a warning has already been
raised because of a ``once``/``default`` rule, then no matter what filters are
set the warning will not be seen again unless the warnings registry related to
the warning has been cleared.
Once the context manager exits, the warnings filter is restored to its state
when the context was entered. This prevents tests from changing the warnings
filter in unexpected ways between tests and leading to indeterminate test
results.
.. _warning-functions:
Available Functions
......@@ -248,31 +309,22 @@ Available Functions
and calls to :func:`simplefilter`.
Available Classes
-----------------
Available Context Managers
--------------------------
.. class:: catch_warnings([\*, record=False, module=None])
A context manager that guards the warnings filter from being permanently
mutated. The manager returns an instance of :class:`WarningsRecorder`. The
*record* argument specifies whether warnings that would typically be
handled by :func:`showwarning` should instead be recorded by the
:class:`WarningsRecorder` instance. This argument is typically set when
testing for expected warnings behavior. The *module* argument may be a
module object that is to be used instead of the :mod:`warnings` module.
This argument should only be set when testing the :mod:`warnings` module
or some similar use-case.
Typical usage of the context manager is like so::
def fxn():
warn("fxn is deprecated", DeprecationWarning)
return "spam spam bacon spam"
A context manager that copies and, upon exit, restores the warnings filter.
If the *record* argument is False (the default) the context manager returns
:class:`None`. If *record* is true, a list is returned that is populated
with objects as seen by a custom :func:`showwarning` function (which also
suppresses output to ``sys.stdout``). Each object has attributes with the
same names as the arguments to :func:`showwarning`.
# The function 'fxn' is known to raise a DeprecationWarning.
with catch_warnings() as w:
warnings.filterwarning('ignore', 'fxn is deprecated', DeprecationWarning)
fxn() # DeprecationWarning is temporarily suppressed.
The *module* argument takes a module that will be used instead of the
module returned when you import :mod:`warnings` whose filter will be
protected. This arguments exists primarily for testing the :mod:`warnings`
module itself.
.. versionadded:: 2.6
......@@ -280,19 +332,3 @@ Available Classes
Constructor arguments turned into keyword-only arguments.
.. class:: WarningsRecorder()
A subclass of :class:`list` that stores all warnings passed to
:func:`showwarning` when returned by a :class:`catch_warnings` context
manager created with its *record* argument set to ``True``. Each recorded
warning is represented by an object whose attributes correspond to the
arguments to :func:`showwarning`. As a convenience, a
:class:`WarningsRecorder` instance has the attributes of the last
recorded warning set on the :class:`WarningsRecorder` instance as well.
.. method:: reset()
Delete all recorded warnings.
.. versionadded:: 2.6
import unittest
from test.support import run_unittest, catch_warning
from test.support import run_unittest
import sys
import warnings
......@@ -8,7 +8,7 @@ class AllTest(unittest.TestCase):
def check_all(self, modname):
names = {}
with catch_warning():
with warnings.catch_warnings():
warnings.filterwarnings("ignore", ".* (module|package)",
DeprecationWarning)
try:
......
......@@ -211,7 +211,7 @@ class TestVectorsTestCase(unittest.TestCase):
def digest(self):
return self._x.digest()
with support.catch_warning():
with warnings.catch_warnings():
warnings.simplefilter('error', RuntimeWarning)
try:
hmac.HMAC(b'a', b'b', digestmod=MockCrazyHash)
......
......@@ -6,7 +6,7 @@ import sys
import py_compile
import warnings
import imp
from test.support import unlink, TESTFN, unload, run_unittest, catch_warning
from test.support import unlink, TESTFN, unload, run_unittest
def remove_files(name):
......@@ -153,7 +153,7 @@ class ImportTest(unittest.TestCase):
self.assert_(y is test.support, y.__name__)
def test_import_initless_directory_warning(self):
with catch_warning():
with warnings.catch_warnings():
# Just a random non-package directory we always expect to be
# somewhere in sys.path...
warnings.simplefilter('error', ImportWarning)
......
import sys
sys.path = ['.'] + sys.path
from test.support import verbose, run_unittest, catch_warning
from test.support import verbose, run_unittest
import re
from re import Scanner
import sys, os, traceback
......
......@@ -4,7 +4,7 @@ import struct
import warnings
from functools import wraps
from test.support import TestFailed, verbose, run_unittest, catch_warning
from test.support import TestFailed, verbose, run_unittest
import sys
ISBIGENDIAN = sys.byteorder == "big"
......@@ -34,7 +34,7 @@ def bigendian_to_native(value):
def with_warning_restore(func):
@wraps(func)
def decorator(*args, **kw):
with catch_warning():
with warnings.catch_warnings():
# We need this function to warn every time, so stick an
# unqualifed 'always' at the head of the filter list
warnings.simplefilter("always")
......
......@@ -66,35 +66,35 @@ class ReadWriteTests(unittest.TestCase):
class TestWarnings(unittest.TestCase):
def has_warned(self, w):
self.assertEqual(w.category, RuntimeWarning)
self.assertEqual(w[-1].category, RuntimeWarning)
def test_byte_max(self):
with support.catch_warning() as w:
with warnings.catch_warnings(record=True) as w:
ts.T_BYTE = CHAR_MAX+1
self.has_warned(w)
def test_byte_min(self):
with support.catch_warning() as w:
with warnings.catch_warnings(record=True) as w:
ts.T_BYTE = CHAR_MIN-1
self.has_warned(w)
def test_ubyte_max(self):
with support.catch_warning() as w:
with warnings.catch_warnings(record=True) as w:
ts.T_UBYTE = UCHAR_MAX+1
self.has_warned(w)
def test_short_max(self):
with support.catch_warning() as w:
with warnings.catch_warnings(record=True) as w:
ts.T_SHORT = SHRT_MAX+1
self.has_warned(w)
def test_short_min(self):
with support.catch_warning() as w:
with warnings.catch_warnings(record=True) as w:
ts.T_SHORT = SHRT_MIN-1
self.has_warned(w)
def test_ushort_max(self):
with support.catch_warning() as w:
with warnings.catch_warnings(record=True) as w:
ts.T_USHORT = USHRT_MAX+1
self.has_warned(w)
......
......@@ -7,7 +7,7 @@ import warnings
class TestUntestedModules(unittest.TestCase):
def test_at_least_import_untested_modules(self):
with support.catch_warning():
with warnings.catch_warnings(record=True):
import aifc
import bdb
import cgitb
......
This diff is collapsed.
......@@ -7,7 +7,7 @@ import linecache
import sys
__all__ = ["warn", "showwarning", "formatwarning", "filterwarnings",
"resetwarnings"]
"resetwarnings", "catch_warnings"]
def showwarning(message, category, filename, lineno, file=None, line=None):
......@@ -274,28 +274,20 @@ class WarningMessage(object):
self.filename, self.lineno, self.line))
class WarningsRecorder(list):
"""Record the result of various showwarning() calls."""
def showwarning(self, *args, **kwargs):
self.append(WarningMessage(*args, **kwargs))
def __getattr__(self, attr):
return getattr(self[-1], attr)
def reset(self):
del self[:]
class catch_warnings(object):
"""Guard the warnings filter from being permanently changed and optionally
record the details of any warnings that are issued.
"""A context manager that copies and restores the warnings filter upon
exiting the context.
The 'record' argument specifies whether warnings should be captured by a
custom implementation of warnings.showwarning() and be appended to a list
returned by the context manager. Otherwise None is returned by the context
manager. The objects appended to the list are arguments whose attributes
mirror the arguments to showwarning().
Context manager returns an instance of warnings.WarningRecorder which is a
list of WarningMessage instances. Attributes on WarningRecorder are
redirected to the last created WarningMessage instance.
The 'module' argument is to specify an alternative module to the module
named 'warnings' and imported under that name. This argument is only useful
when testing the warnings module itself.
"""
......@@ -307,17 +299,21 @@ class catch_warnings(object):
keyword-only.
"""
self._recorder = WarningsRecorder() if record else None
self._record = record
self._module = sys.modules['warnings'] if module is None else module
def __enter__(self):
self._filters = self._module.filters
self._module.filters = self._filters[:]
self._showwarning = self._module.showwarning
if self._recorder is not None:
self._recorder.reset() # In case the instance is being reused.
self._module.showwarning = self._recorder.showwarning
return self._recorder
if self._record:
log = []
def showwarning(*args, **kwargs):
log.append(WarningMessage(*args, **kwargs))
self._module.showwarning = showwarning
return log
else:
return None
def __exit__(self, *exc_info):
self._module.filters = self._filters
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment