2010-11-06 18:38:53 +08:00
|
|
|
""" recording warnings during test function execution. """
|
2017-03-17 09:21:30 +08:00
|
|
|
from __future__ import absolute_import, division, print_function
|
|
|
|
|
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
|
2009-05-06 03:24:47 +08:00
|
|
|
|
2017-09-06 07:13:08 +08:00
|
|
|
import re
|
|
|
|
|
2015-09-19 07:03:05 +08:00
|
|
|
from _pytest.fixtures import yield_fixture
|
|
|
|
from _pytest.outcomes import fail
|
2017-03-16 01:00:59 +08:00
|
|
|
|
2017-07-29 00:27:59 +08:00
|
|
|
|
2017-03-16 01:00:59 +08:00
|
|
|
@yield_fixture
|
2017-03-10 10:08:50 +08:00
|
|
|
def recwarn():
|
2018-02-28 05:26:40 +08:00
|
|
|
"""Return a :class:`WarningsRecorder` instance that records all warnings emitted by test functions.
|
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
|
|
|
|
2015-09-21 21:18:29 +08:00
|
|
|
def deprecated_call(func=None, *args, **kwargs):
|
2017-06-07 09:25:15 +08:00
|
|
|
"""context manager that can be used to ensure a block of code triggers a
|
|
|
|
``DeprecationWarning`` or ``PendingDeprecationWarning``::
|
2015-09-21 21:18:29 +08:00
|
|
|
|
2016-10-21 09:39:28 +08:00
|
|
|
>>> import warnings
|
|
|
|
>>> def api_call_v2():
|
|
|
|
... warnings.warn('use v3 of this api', DeprecationWarning)
|
|
|
|
... return 200
|
|
|
|
|
2015-09-21 21:18:29 +08:00
|
|
|
>>> with deprecated_call():
|
2016-10-21 09:39:28 +08:00
|
|
|
... assert api_call_v2() == 200
|
2015-12-08 06:27:41 +08:00
|
|
|
|
2017-06-07 09:25:15 +08:00
|
|
|
``deprecated_call`` can also be used by passing a function and ``*args`` and ``*kwargs``,
|
|
|
|
in which case it will ensure calling ``func(*args, **kwargs)`` produces one of the warnings
|
|
|
|
types above.
|
2010-07-27 03:15:15 +08:00
|
|
|
"""
|
2015-09-21 21:18:29 +08:00
|
|
|
if not func:
|
2017-06-07 09:25:15 +08:00
|
|
|
return _DeprecatedCallContext()
|
|
|
|
else:
|
2017-06-22 19:54:39 +08:00
|
|
|
__tracebackhide__ = True
|
2017-06-07 09:25:15 +08:00
|
|
|
with _DeprecatedCallContext():
|
|
|
|
return func(*args, **kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
class _DeprecatedCallContext(object):
|
|
|
|
"""Implements the logic to capture deprecation warnings as a context manager."""
|
2015-09-21 21:18:29 +08:00
|
|
|
|
2017-06-07 09:25:15 +08:00
|
|
|
def __enter__(self):
|
|
|
|
self._captured_categories = []
|
|
|
|
self._old_warn = warnings.warn
|
|
|
|
self._old_warn_explicit = warnings.warn_explicit
|
|
|
|
warnings.warn_explicit = self._warn_explicit
|
|
|
|
warnings.warn = self._warn
|
2015-07-29 07:01:11 +08:00
|
|
|
|
2017-06-07 09:25:15 +08:00
|
|
|
def _warn_explicit(self, message, category, *args, **kwargs):
|
|
|
|
self._captured_categories.append(category)
|
2015-11-27 02:27:20 +08:00
|
|
|
|
2017-06-07 09:25:15 +08:00
|
|
|
def _warn(self, message, category=None, *args, **kwargs):
|
2015-11-27 02:27:20 +08:00
|
|
|
if isinstance(message, Warning):
|
2017-06-07 09:25:15 +08:00
|
|
|
self._captured_categories.append(message.__class__)
|
2015-11-27 02:27:20 +08:00
|
|
|
else:
|
2017-06-07 09:25:15 +08:00
|
|
|
self._captured_categories.append(category)
|
|
|
|
|
|
|
|
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
|
|
warnings.warn_explicit = self._old_warn_explicit
|
|
|
|
warnings.warn = self._old_warn
|
2017-06-22 19:54:39 +08:00
|
|
|
|
2017-06-07 09:25:15 +08:00
|
|
|
if exc_type is None:
|
|
|
|
deprecation_categories = (DeprecationWarning, PendingDeprecationWarning)
|
|
|
|
if not any(issubclass(c, deprecation_categories) for c in self._captured_categories):
|
|
|
|
__tracebackhide__ = True
|
|
|
|
msg = "Did not produce DeprecationWarning or PendingDeprecationWarning"
|
|
|
|
raise AssertionError(msg)
|
2009-06-18 23:26:40 +08:00
|
|
|
|
|
|
|
|
2015-07-29 07:01:11 +08:00
|
|
|
def warns(expected_warning, *args, **kwargs):
|
|
|
|
"""Assert that code raises a particular class of warning.
|
|
|
|
|
2018-02-28 05:26:40 +08:00
|
|
|
Specifically, the parameter ``expected_warning`` can be a warning class or
|
|
|
|
sequence of warning classes, and the inside the ``with`` block must issue a warning of that class or
|
|
|
|
classes.
|
2015-07-29 07:01:11 +08:00
|
|
|
|
2018-02-28 05:26:40 +08:00
|
|
|
This helper produces a list of :class:`warnings.WarningMessage` objects,
|
2015-07-29 07:01:11 +08:00
|
|
|
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)
|
2017-09-07 16:28:52 +08:00
|
|
|
|
|
|
|
In the context manager form you may use the keyword argument ``match`` to assert
|
|
|
|
that the exception matches a text or regex::
|
|
|
|
|
|
|
|
>>> with warns(UserWarning, match='must be 0 or None'):
|
|
|
|
... warnings.warn("value must be 0 or None", UserWarning)
|
|
|
|
|
|
|
|
>>> with warns(UserWarning, match=r'must be \d+$'):
|
|
|
|
... warnings.warn("value must be 42", UserWarning)
|
|
|
|
|
|
|
|
>>> with warns(UserWarning, match=r'must be \d+$'):
|
|
|
|
... warnings.warn("this is not here", UserWarning)
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
|
|
|
Failed: DID NOT WARN. No warnings of type ...UserWarning... was emitted...
|
|
|
|
|
2015-07-29 07:01:11 +08:00
|
|
|
"""
|
2017-09-06 07:13:08 +08:00
|
|
|
match_expr = None
|
2015-07-29 07:01:11 +08:00
|
|
|
if not args:
|
2017-09-06 07:13:08 +08:00
|
|
|
if "match" in kwargs:
|
|
|
|
match_expr = kwargs.pop("match")
|
|
|
|
return WarningsChecker(expected_warning, match_expr=match_expr)
|
2015-07-29 07:01:11 +08:00
|
|
|
elif isinstance(args[0], str):
|
|
|
|
code, = args
|
|
|
|
assert isinstance(code, str)
|
|
|
|
frame = sys._getframe(1)
|
|
|
|
loc = frame.f_locals.copy()
|
|
|
|
loc.update(kwargs)
|
|
|
|
|
2017-09-06 07:13:08 +08:00
|
|
|
with WarningsChecker(expected_warning, match_expr=match_expr):
|
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]
|
2017-09-06 07:13:08 +08:00
|
|
|
with WarningsChecker(expected_warning, match_expr=match_expr):
|
2015-07-29 07:01:11 +08:00
|
|
|
return func(*args[1:], **kwargs)
|
|
|
|
|
|
|
|
|
2017-03-10 10:08:50 +08:00
|
|
|
class WarningsRecorder(warnings.catch_warnings):
|
2015-07-29 07:01:11 +08:00
|
|
|
"""A context manager to record raised warnings.
|
|
|
|
|
|
|
|
Adapted from `warnings.catch_warnings`.
|
|
|
|
"""
|
|
|
|
|
2017-03-10 10:08:50 +08:00
|
|
|
def __init__(self):
|
|
|
|
super(WarningsRecorder, self).__init__(record=True)
|
2015-07-29 07:01:11 +08:00
|
|
|
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)
|
2017-03-10 10:08:50 +08:00
|
|
|
self._list = super(WarningsRecorder, self).__enter__()
|
|
|
|
warnings.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)
|
2017-03-10 10:08:50 +08:00
|
|
|
super(WarningsRecorder, self).__exit__(*exc_info)
|
2015-07-29 07:01:11 +08:00
|
|
|
|
|
|
|
|
|
|
|
class WarningsChecker(WarningsRecorder):
|
2017-09-06 07:13:08 +08:00
|
|
|
def __init__(self, expected_warning=None, match_expr=None):
|
2017-03-10 10:08:50 +08:00
|
|
|
super(WarningsChecker, self).__init__()
|
2015-07-29 07:01:11 +08:00
|
|
|
|
|
|
|
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
|
2017-09-06 07:13:08 +08:00
|
|
|
self.match_expr = match_expr
|
2015-07-29 07:01:11 +08:00
|
|
|
|
|
|
|
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:
|
2017-01-03 19:03:26 +08:00
|
|
|
if not any(issubclass(r.category, self.expected_warning)
|
|
|
|
for r in self):
|
2015-07-29 07:01:11 +08:00
|
|
|
__tracebackhide__ = True
|
2018-05-18 05:31:16 +08:00
|
|
|
fail("DID NOT WARN. No warnings of type {} was emitted. "
|
|
|
|
"The list of emitted warnings is: {}.".format(
|
2017-07-17 07:25:07 +08:00
|
|
|
self.expected_warning,
|
2017-07-17 07:25:07 +08:00
|
|
|
[each.message for each in self]))
|
2017-09-06 07:13:08 +08:00
|
|
|
elif self.match_expr is not None:
|
|
|
|
for r in self:
|
|
|
|
if issubclass(r.category, self.expected_warning):
|
|
|
|
if re.compile(self.match_expr).search(str(r.message)):
|
|
|
|
break
|
|
|
|
else:
|
2018-05-18 16:48:44 +08:00
|
|
|
fail(
|
|
|
|
"DID NOT WARN. No warnings of type {} matching"
|
|
|
|
" ('{}') was emitted. The list of emitted warnings"
|
|
|
|
" is: {}.".format(
|
|
|
|
self.expected_warning, self.match_expr,
|
|
|
|
[each.message for each in self]))
|