| 1 |
""" recording warnings during test function execution. """ |
| 2 |
|
| 3 |
import inspect |
| 4 |
|
| 5 |
import _pytest._code |
| 6 |
import py |
| 7 |
import sys |
| 8 |
import warnings |
| 9 |
import pytest |
| 10 |
|
| 11 |
|
| 12 |
@pytest.yield_fixture |
| 13 |
def recwarn(request): |
| 14 |
"""Return a WarningsRecorder instance that provides these methods: |
| 15 |
|
| 16 |
* ``pop(category=None)``: return last warning matching the category. |
| 17 |
* ``clear()``: clear list of warnings |
| 18 |
|
| 19 |
See http://docs.python.org/library/warnings.html for information |
| 20 |
on warning categories. |
| 21 |
""" |
| 22 |
wrec = WarningsRecorder() |
| 23 |
with wrec: |
| 24 |
warnings.simplefilter('default') |
| 25 |
yield wrec |
| 26 |
|
| 27 |
|
| 28 |
def pytest_namespace(): |
| 29 |
return {'deprecated_call': deprecated_call, |
| 30 |
'warns': warns} |
| 31 |
|
| 32 |
|
| 33 |
def deprecated_call(func=None, *args, **kwargs): |
| 34 |
""" assert that calling ``func(*args, **kwargs)`` triggers a |
| 35 |
``DeprecationWarning`` or ``PendingDeprecationWarning``. |
| 36 |
|
| 37 |
This function can be used as a context manager:: |
| 38 |
|
| 39 |
>>> with deprecated_call(): |
| 40 |
... myobject.deprecated_method() |
| 41 |
|
| 42 |
Note: we cannot use WarningsRecorder here because it is still subject |
| 43 |
to the mechanism that prevents warnings of the same type from being |
| 44 |
triggered twice for the same module. See #1190. |
| 45 |
""" |
| 46 |
if not func: |
| 47 |
return WarningsChecker(expected_warning=DeprecationWarning) |
| 48 |
|
| 49 |
categories = [] |
| 50 |
|
| 51 |
def warn_explicit(message, category, *args, **kwargs): |
| 52 |
categories.append(category) |
| 53 |
old_warn_explicit(message, category, *args, **kwargs) |
| 54 |
|
| 55 |
def warn(message, category=None, *args, **kwargs): |
| 56 |
if isinstance(message, Warning): |
| 57 |
categories.append(message.__class__) |
| 58 |
else: |
| 59 |
categories.append(category) |
| 60 |
old_warn(message, category, *args, **kwargs) |
| 61 |
|
| 62 |
old_warn = warnings.warn |
| 63 |
old_warn_explicit = warnings.warn_explicit |
| 64 |
warnings.warn_explicit = warn_explicit |
| 65 |
warnings.warn = warn |
| 66 |
try: |
| 67 |
ret = func(*args, **kwargs) |
| 68 |
finally: |
| 69 |
warnings.warn_explicit = old_warn_explicit |
| 70 |
warnings.warn = old_warn |
| 71 |
deprecation_categories = (DeprecationWarning, PendingDeprecationWarning) |
| 72 |
if not any(issubclass(c, deprecation_categories) for c in categories): |
| 73 |
__tracebackhide__ = True |
| 74 |
raise AssertionError("%r did not produce DeprecationWarning" % (func,)) |
| 75 |
return ret |
| 76 |
|
| 77 |
|
| 78 |
def warns(expected_warning, *args, **kwargs): |
| 79 |
"""Assert that code raises a particular class of warning. |
| 80 |
|
| 81 |
Specifically, the input @expected_warning can be a warning class or |
| 82 |
tuple of warning classes, and the code must return that warning |
| 83 |
(if a single class) or one of those warnings (if a tuple). |
| 84 |
|
| 85 |
This helper produces a list of ``warnings.WarningMessage`` objects, |
| 86 |
one for each warning raised. |
| 87 |
|
| 88 |
This function can be used as a context manager, or any of the other ways |
| 89 |
``pytest.raises`` can be used:: |
| 90 |
|
| 91 |
>>> with warns(RuntimeWarning): |
| 92 |
... warnings.warn("my warning", RuntimeWarning) |
| 93 |
""" |
| 94 |
wcheck = WarningsChecker(expected_warning) |
| 95 |
if not args: |
| 96 |
return wcheck |
| 97 |
elif isinstance(args[0], str): |
| 98 |
code, = args |
| 99 |
assert isinstance(code, str) |
| 100 |
frame = sys._getframe(1) |
| 101 |
loc = frame.f_locals.copy() |
| 102 |
loc.update(kwargs) |
| 103 |
|
| 104 |
with wcheck: |
| 105 |
code = _pytest._code.Source(code).compile() |
| 106 |
py.builtin.exec_(code, frame.f_globals, loc) |
| 107 |
else: |
| 108 |
func = args[0] |
| 109 |
with wcheck: |
| 110 |
return func(*args[1:], **kwargs) |
| 111 |
|
| 112 |
|
| 113 |
class RecordedWarning(object): |
| 114 |
def __init__(self, message, category, filename, lineno, file, line): |
| 115 |
self.message = message |
| 116 |
self.category = category |
| 117 |
self.filename = filename |
| 118 |
self.lineno = lineno |
| 119 |
self.file = file |
| 120 |
self.line = line |
| 121 |
|
| 122 |
|
| 123 |
class WarningsRecorder(object): |
| 124 |
"""A context manager to record raised warnings. |
| 125 |
|
| 126 |
Adapted from `warnings.catch_warnings`. |
| 127 |
""" |
| 128 |
|
| 129 |
def __init__(self, module=None): |
| 130 |
self._module = sys.modules['warnings'] if module is None else module |
| 131 |
self._entered = False |
| 132 |
self._list = [] |
| 133 |
|
| 134 |
@property |
| 135 |
def list(self): |
| 136 |
"""The list of recorded warnings.""" |
| 137 |
return self._list |
| 138 |
|
| 139 |
def __getitem__(self, i): |
| 140 |
"""Get a recorded warning by index.""" |
| 141 |
return self._list[i] |
| 142 |
|
| 143 |
def __iter__(self): |
| 144 |
"""Iterate through the recorded warnings.""" |
| 145 |
return iter(self._list) |
| 146 |
|
| 147 |
def __len__(self): |
| 148 |
"""The number of recorded warnings.""" |
| 149 |
return len(self._list) |
| 150 |
|
| 151 |
def pop(self, cls=Warning): |
| 152 |
"""Pop the first recorded warning, raise exception if not exists.""" |
| 153 |
for i, w in enumerate(self._list): |
| 154 |
if issubclass(w.category, cls): |
| 155 |
return self._list.pop(i) |
| 156 |
__tracebackhide__ = True |
| 157 |
raise AssertionError("%r not found in warning list" % cls) |
| 158 |
|
| 159 |
def clear(self): |
| 160 |
"""Clear the list of recorded warnings.""" |
| 161 |
self._list[:] = [] |
| 162 |
|
| 163 |
def __enter__(self): |
| 164 |
if self._entered: |
| 165 |
__tracebackhide__ = True |
| 166 |
raise RuntimeError("Cannot enter %r twice" % self) |
| 167 |
self._entered = True |
| 168 |
self._filters = self._module.filters |
| 169 |
self._module.filters = self._filters[:] |
| 170 |
self._showwarning = self._module.showwarning |
| 171 |
|
| 172 |
def showwarning(message, category, filename, lineno, |
| 173 |
file=None, line=None): |
| 174 |
self._list.append(RecordedWarning( |
| 175 |
message, category, filename, lineno, file, line)) |
| 176 |
|
| 177 |
|
| 178 |
self._showwarning( |
| 179 |
message, category, filename, lineno, file=file, line=line) |
| 180 |
|
| 181 |
self._module.showwarning = showwarning |
| 182 |
|
| 183 |
|
| 184 |
|
| 185 |
self._module.simplefilter('always') |
| 186 |
return self |
| 187 |
|
| 188 |
def __exit__(self, *exc_info): |
| 189 |
if not self._entered: |
| 190 |
__tracebackhide__ = True |
| 191 |
raise RuntimeError("Cannot exit %r without entering first" % self) |
| 192 |
self._module.filters = self._filters |
| 193 |
self._module.showwarning = self._showwarning |
| 194 |
|
| 195 |
|
| 196 |
class WarningsChecker(WarningsRecorder): |
| 197 |
def __init__(self, expected_warning=None, module=None): |
| 198 |
super(WarningsChecker, self).__init__(module=module) |
| 199 |
|
| 200 |
msg = ("exceptions must be old-style classes or " |
| 201 |
"derived from Warning, not %s") |
| 202 |
if isinstance(expected_warning, tuple): |
| 203 |
for exc in expected_warning: |
| 204 |
if not inspect.isclass(exc): |
| 205 |
raise TypeError(msg % type(exc)) |
| 206 |
elif inspect.isclass(expected_warning): |
| 207 |
expected_warning = (expected_warning,) |
| 208 |
elif expected_warning is not None: |
| 209 |
raise TypeError(msg % type(expected_warning)) |
| 210 |
|
| 211 |
self.expected_warning = expected_warning |
| 212 |
|
| 213 |
def __exit__(self, *exc_info): |
| 214 |
super(WarningsChecker, self).__exit__(*exc_info) |
| 215 |
|
| 216 |
|
| 217 |
if all(a is None for a in exc_info): |
| 218 |
if self.expected_warning is not None: |
| 219 |
if not any(r.category in self.expected_warning for r in self): |
| 220 |
__tracebackhide__ = True |
| 221 |
pytest.fail("DID NOT WARN") |