In python2, display previously warned warnings

This commit is contained in:
Anthony Sottile 2018-10-10 09:36:19 -07:00
parent aeb92accb2
commit e0f6fce9e9
3 changed files with 24 additions and 0 deletions

View File

@ -0,0 +1 @@
``pytest.warn`` will capture previously-warned warnings in python2. Previously they were never raised.

View File

@ -149,12 +149,25 @@ class WarningsRecorder(warnings.catch_warnings):
raise RuntimeError("Cannot enter %r twice" % self) raise RuntimeError("Cannot enter %r twice" % self)
self._list = super(WarningsRecorder, self).__enter__() self._list = super(WarningsRecorder, self).__enter__()
warnings.simplefilter("always") warnings.simplefilter("always")
# python3 keeps track of a "filter version", when the filters are
# updated previously seen warnings can be re-warned. python2 has no
# concept of this so we must reset the warnings registry manually.
# trivial patching of `warnings.warn` seems to be enough somehow?
if six.PY2:
def warn(*args, **kwargs):
return self._warn(*args, **kwargs)
warnings.warn, self._warn = warn, warnings.warn
return self return self
def __exit__(self, *exc_info): def __exit__(self, *exc_info):
if not self._entered: if not self._entered:
__tracebackhide__ = True __tracebackhide__ = True
raise RuntimeError("Cannot exit %r without entering first" % self) raise RuntimeError("Cannot exit %r without entering first" % self)
# see above where `self.mp` is assigned
if six.PY2:
warnings.warn = self._warn
super(WarningsRecorder, self).__exit__(*exc_info) super(WarningsRecorder, self).__exit__(*exc_info)

View File

@ -350,3 +350,13 @@ class TestWarns(object):
with pytest.warns(UserWarning, match=r"aaa"): with pytest.warns(UserWarning, match=r"aaa"):
warnings.warn("bbbbbbbbbb", UserWarning) warnings.warn("bbbbbbbbbb", UserWarning)
warnings.warn("cccccccccc", UserWarning) warnings.warn("cccccccccc", UserWarning)
@pytest.mark.filterwarnings("ignore")
def test_can_capture_previously_warned(self):
def f():
warnings.warn(UserWarning("ohai"))
return 10
assert f() == 10
assert pytest.warns(UserWarning, f) == 10
assert pytest.warns(UserWarning, f) == 10