Refactor recwarn to use warnings.catch_warnings instead of custom code

Since we dropped 2.5, we can now use warnings.catch_warnings to do the
"catch warnings" magic for us, simplifying the code a bit.
This commit is contained in:
Bruno Oliveira 2017-03-09 23:08:50 -03:00
parent d1ea7c8cc8
commit 22864b75ee
2 changed files with 9 additions and 37 deletions

View File

@ -6,11 +6,10 @@ import py
import sys
import warnings
import pytest
from collections import namedtuple
@pytest.yield_fixture
def recwarn(request):
def recwarn():
"""Return a WarningsRecorder instance that provides these methods:
* ``pop(category=None)``: return last warning matching the category.
@ -115,19 +114,14 @@ def warns(expected_warning, *args, **kwargs):
return func(*args[1:], **kwargs)
RecordedWarning = namedtuple('RecordedWarning', (
'message', 'category', 'filename', 'lineno', 'file', 'line',
))
class WarningsRecorder(object):
class WarningsRecorder(warnings.catch_warnings):
"""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
def __init__(self):
super(WarningsRecorder, self).__init__(record=True)
self._entered = False
self._list = []
@ -164,38 +158,20 @@ class WarningsRecorder(object):
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
self._showwarning(
message, category, filename, lineno, file=file, line=line)
self._module.showwarning = showwarning
# allow the same warning to be raised more than once
self._module.simplefilter('always')
self._list = super(WarningsRecorder, self).__enter__()
warnings.simplefilter('always')
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
super(WarningsRecorder, self).__exit__(*exc_info)
class WarningsChecker(WarningsRecorder):
def __init__(self, expected_warning=None, module=None):
super(WarningsChecker, self).__init__(module=module)
def __init__(self, expected_warning=None):
super(WarningsChecker, self).__init__()
msg = ("exceptions must be old-style classes or "
"derived from Warning, not %s")

View File

@ -217,7 +217,6 @@ class TestWarns(object):
excinfo.match(re.escape(message_template.format(warning_classes,
[each.message for each in warninfo])))
def test_record(self):
with pytest.warns(UserWarning) as record:
warnings.warn("user", UserWarning)
@ -225,9 +224,6 @@ class TestWarns(object):
assert len(record) == 1
assert str(record[0].message) == "user"
print(repr(record[0]))
assert str(record[0].message) in repr(record[0])
def test_record_only(self):
with pytest.warns(None) as record:
warnings.warn("user", UserWarning)