2010-11-06 18:38:53 +08:00
|
|
|
""" recording warnings during test function execution. """
|
2009-06-18 23:26:40 +08:00
|
|
|
|
2015-07-29 07:01:11 +08:00
|
|
|
import inspect
|
2015-11-27 22:43:01 +08:00
|
|
|
|
|
|
|
import _pytest._code
|
2015-07-29 07:01:11 +08:00
|
|
|
import py
|
2013-10-02 20:32:40 +08:00
|
|
|
import sys
|
2014-08-01 06:13:40 +08:00
|
|
|
import warnings
|
2015-07-29 07:01:11 +08:00
|
|
|
import pytest
|
2014-08-01 06:13:40 +08:00
|
|
|
|
2009-05-06 03:24:47 +08:00
|
|
|
|
2015-07-29 07:01:11 +08:00
|
|
|
@pytest.yield_fixture
|
|
|
|
def recwarn(request):
|
2009-07-22 22:09:49 +08:00
|
|
|
"""Return a WarningsRecorder instance that provides these methods:
|
|
|
|
|
|
|
|
* ``pop(category=None)``: return last warning matching the category.
|
2010-07-27 03:15:15 +08:00
|
|
|
* ``clear()``: clear list of warnings
|
2013-10-02 20:32:40 +08:00
|
|
|
|
2011-03-04 06:40:38 +08:00
|
|
|
See http://docs.python.org/library/warnings.html for information
|
|
|
|
on warning categories.
|
2009-07-22 22:09:49 +08:00
|
|
|
"""
|
2010-07-05 04:13:12 +08:00
|
|
|
wrec = WarningsRecorder()
|
2015-07-29 07:01:11 +08:00
|
|
|
with wrec:
|
|
|
|
warnings.simplefilter('default')
|
|
|
|
yield wrec
|
|
|
|
|
2009-05-06 03:24:47 +08:00
|
|
|
|
2009-07-18 00:07:37 +08:00
|
|
|
def pytest_namespace():
|
2015-07-29 07:01:11 +08:00
|
|
|
return {'deprecated_call': deprecated_call,
|
|
|
|
'warns': warns}
|
|
|
|
|
2009-06-18 23:26:40 +08:00
|
|
|
|
2015-09-21 21:18:29 +08:00
|
|
|
def deprecated_call(func=None, *args, **kwargs):
|
2015-11-27 02:27:20 +08:00
|
|
|
""" assert that calling ``func(*args, **kwargs)`` triggers a
|
|
|
|
``DeprecationWarning`` or ``PendingDeprecationWarning``.
|
2015-09-21 21:18:29 +08:00
|
|
|
|
|
|
|
This function can be used as a context manager::
|
|
|
|
|
|
|
|
>>> with deprecated_call():
|
|
|
|
... myobject.deprecated_method()
|
2015-12-08 06:27:41 +08:00
|
|
|
|
2015-11-27 02:27:20 +08:00
|
|
|
Note: we cannot use WarningsRecorder here because it is still subject
|
|
|
|
to the mechanism that prevents warnings of the same type from being
|
|
|
|
triggered twice for the same module. See #1190.
|
2010-07-27 03:15:15 +08:00
|
|
|
"""
|
2015-09-21 21:18:29 +08:00
|
|
|
if not func:
|
|
|
|
return WarningsChecker(expected_warning=DeprecationWarning)
|
|
|
|
|
2015-11-27 02:27:20 +08:00
|
|
|
categories = []
|
2015-07-29 07:01:11 +08:00
|
|
|
|
2015-11-27 02:27:20 +08:00
|
|
|
def warn_explicit(message, category, *args, **kwargs):
|
|
|
|
categories.append(category)
|
|
|
|
old_warn_explicit(message, category, *args, **kwargs)
|
|
|
|
|
2015-12-09 08:40:05 +08:00
|
|
|
def warn(message, category=None, *args, **kwargs):
|
2015-11-27 02:27:20 +08:00
|
|
|
if isinstance(message, Warning):
|
|
|
|
categories.append(message.__class__)
|
|
|
|
else:
|
|
|
|
categories.append(category)
|
|
|
|
old_warn(message, category, *args, **kwargs)
|
2015-11-27 01:54:57 +08:00
|
|
|
|
2015-11-27 02:27:20 +08:00
|
|
|
old_warn = warnings.warn
|
|
|
|
old_warn_explicit = warnings.warn_explicit
|
2015-11-27 01:54:57 +08:00
|
|
|
warnings.warn_explicit = warn_explicit
|
|
|
|
warnings.warn = warn
|
|
|
|
try:
|
2009-06-18 23:26:40 +08:00
|
|
|
ret = func(*args, **kwargs)
|
2015-11-27 01:54:57 +08:00
|
|
|
finally:
|
2015-11-27 02:27:20 +08:00
|
|
|
warnings.warn_explicit = old_warn_explicit
|
|
|
|
warnings.warn = old_warn
|
|
|
|
deprecation_categories = (DeprecationWarning, PendingDeprecationWarning)
|
|
|
|
if not any(issubclass(c, deprecation_categories) for c in categories):
|
2009-12-30 19:13:38 +08:00
|
|
|
__tracebackhide__ = True
|
2015-07-29 07:01:11 +08:00
|
|
|
raise AssertionError("%r did not produce DeprecationWarning" % (func,))
|
2009-06-18 23:26:40 +08:00
|
|
|
return ret
|
|
|
|
|
|
|
|
|
2015-07-29 07:01:11 +08:00
|
|
|
def warns(expected_warning, *args, **kwargs):
|
|
|
|
"""Assert that code raises a particular class of warning.
|
|
|
|
|
|
|
|
Specifically, the input @expected_warning can be a warning class or
|
|
|
|
tuple of warning classes, and the code must return that warning
|
|
|
|
(if a single class) or one of those warnings (if a tuple).
|
|
|
|
|
|
|
|
This helper produces a list of ``warnings.WarningMessage`` objects,
|
|
|
|
one for each warning raised.
|
|
|
|
|
|
|
|
This function can be used as a context manager, or any of the other ways
|
|
|
|
``pytest.raises`` can be used::
|
|
|
|
|
|
|
|
>>> with warns(RuntimeWarning):
|
|
|
|
... warnings.warn("my warning", RuntimeWarning)
|
|
|
|
"""
|
|
|
|
wcheck = WarningsChecker(expected_warning)
|
|
|
|
if not args:
|
|
|
|
return wcheck
|
|
|
|
elif isinstance(args[0], str):
|
|
|
|
code, = args
|
|
|
|
assert isinstance(code, str)
|
|
|
|
frame = sys._getframe(1)
|
|
|
|
loc = frame.f_locals.copy()
|
|
|
|
loc.update(kwargs)
|
|
|
|
|
|
|
|
with wcheck:
|
2015-11-27 22:43:01 +08:00
|
|
|
code = _pytest._code.Source(code).compile()
|
2015-07-29 07:01:11 +08:00
|
|
|
py.builtin.exec_(code, frame.f_globals, loc)
|
|
|
|
else:
|
|
|
|
func = args[0]
|
|
|
|
with wcheck:
|
|
|
|
return func(*args[1:], **kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
class RecordedWarning(object):
|
|
|
|
def __init__(self, message, category, filename, lineno, file, line):
|
2009-05-06 03:24:47 +08:00
|
|
|
self.message = message
|
|
|
|
self.category = category
|
|
|
|
self.filename = filename
|
|
|
|
self.lineno = lineno
|
2015-07-29 07:01:11 +08:00
|
|
|
self.file = file
|
2009-05-06 03:24:47 +08:00
|
|
|
self.line = line
|
|
|
|
|
2015-07-29 07:01:11 +08:00
|
|
|
|
|
|
|
class WarningsRecorder(object):
|
|
|
|
"""A context manager to record raised warnings.
|
|
|
|
|
|
|
|
Adapted from `warnings.catch_warnings`.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, module=None):
|
|
|
|
self._module = sys.modules['warnings'] if module is None else module
|
|
|
|
self._entered = False
|
|
|
|
self._list = []
|
|
|
|
|
|
|
|
@property
|
|
|
|
def list(self):
|
|
|
|
"""The list of recorded warnings."""
|
|
|
|
return self._list
|
|
|
|
|
|
|
|
def __getitem__(self, i):
|
|
|
|
"""Get a recorded warning by index."""
|
|
|
|
return self._list[i]
|
|
|
|
|
|
|
|
def __iter__(self):
|
|
|
|
"""Iterate through the recorded warnings."""
|
|
|
|
return iter(self._list)
|
|
|
|
|
|
|
|
def __len__(self):
|
|
|
|
"""The number of recorded warnings."""
|
|
|
|
return len(self._list)
|
2009-05-06 03:24:47 +08:00
|
|
|
|
|
|
|
def pop(self, cls=Warning):
|
2015-07-29 07:01:11 +08:00
|
|
|
"""Pop the first recorded warning, raise exception if not exists."""
|
|
|
|
for i, w in enumerate(self._list):
|
2009-05-06 03:24:47 +08:00
|
|
|
if issubclass(w.category, cls):
|
2015-07-29 07:01:11 +08:00
|
|
|
return self._list.pop(i)
|
2009-05-06 04:31:18 +08:00
|
|
|
__tracebackhide__ = True
|
2015-07-29 07:01:11 +08:00
|
|
|
raise AssertionError("%r not found in warning list" % cls)
|
2009-05-06 03:24:47 +08:00
|
|
|
|
2010-07-27 03:15:15 +08:00
|
|
|
def clear(self):
|
2015-07-29 07:01:11 +08:00
|
|
|
"""Clear the list of recorded warnings."""
|
|
|
|
self._list[:] = []
|
|
|
|
|
|
|
|
def __enter__(self):
|
|
|
|
if self._entered:
|
|
|
|
__tracebackhide__ = True
|
|
|
|
raise RuntimeError("Cannot enter %r twice" % self)
|
|
|
|
self._entered = True
|
|
|
|
self._filters = self._module.filters
|
|
|
|
self._module.filters = self._filters[:]
|
|
|
|
self._showwarning = self._module.showwarning
|
|
|
|
|
|
|
|
def showwarning(message, category, filename, lineno,
|
|
|
|
file=None, line=None):
|
|
|
|
self._list.append(RecordedWarning(
|
|
|
|
message, category, filename, lineno, file, line))
|
|
|
|
|
|
|
|
# still perform old showwarning functionality
|
2015-08-07 03:05:01 +08:00
|
|
|
self._showwarning(
|
|
|
|
message, category, filename, lineno, file=file, line=line)
|
2015-07-29 07:01:11 +08:00
|
|
|
|
|
|
|
self._module.showwarning = showwarning
|
2015-08-07 03:05:01 +08:00
|
|
|
|
|
|
|
# allow the same warning to be raised more than once
|
|
|
|
|
2015-09-21 22:54:50 +08:00
|
|
|
self._module.simplefilter('always')
|
2015-07-29 07:01:11 +08:00
|
|
|
return self
|
|
|
|
|
|
|
|
def __exit__(self, *exc_info):
|
|
|
|
if not self._entered:
|
|
|
|
__tracebackhide__ = True
|
|
|
|
raise RuntimeError("Cannot exit %r without entering first" % self)
|
|
|
|
self._module.filters = self._filters
|
|
|
|
self._module.showwarning = self._showwarning
|
|
|
|
|
|
|
|
|
|
|
|
class WarningsChecker(WarningsRecorder):
|
|
|
|
def __init__(self, expected_warning=None, module=None):
|
|
|
|
super(WarningsChecker, self).__init__(module=module)
|
|
|
|
|
|
|
|
msg = ("exceptions must be old-style classes or "
|
|
|
|
"derived from Warning, not %s")
|
|
|
|
if isinstance(expected_warning, tuple):
|
|
|
|
for exc in expected_warning:
|
|
|
|
if not inspect.isclass(exc):
|
|
|
|
raise TypeError(msg % type(exc))
|
|
|
|
elif inspect.isclass(expected_warning):
|
|
|
|
expected_warning = (expected_warning,)
|
|
|
|
elif expected_warning is not None:
|
|
|
|
raise TypeError(msg % type(expected_warning))
|
|
|
|
|
|
|
|
self.expected_warning = expected_warning
|
|
|
|
|
|
|
|
def __exit__(self, *exc_info):
|
|
|
|
super(WarningsChecker, self).__exit__(*exc_info)
|
2009-05-06 03:24:47 +08:00
|
|
|
|
2015-07-29 07:01:11 +08:00
|
|
|
# only check if we're not currently handling an exception
|
|
|
|
if all(a is None for a in exc_info):
|
|
|
|
if self.expected_warning is not None:
|
|
|
|
if not any(r.category in self.expected_warning for r in self):
|
|
|
|
__tracebackhide__ = True
|
|
|
|
pytest.fail("DID NOT WARN")
|