Fix checking expected warnings when an exception is raised

pytest.warn and similar functions should capture warnings when an exception is raised inside a with block
This commit is contained in:
eltio 2022-08-07 02:13:16 +03:00
parent 58cf20edf0
commit 6a8946718d
3 changed files with 17 additions and 17 deletions

View File

@ -0,0 +1 @@
``pytest.warns`` and similar functions now capture warnings when an exception is raised inside a ``with`` block.

View File

@ -280,24 +280,22 @@ class WarningsChecker(WarningsRecorder):
def found_str():
return pformat([record.message for record in self], indent=2)
# only check if we're not currently handling an exception
if exc_type is None and exc_val is None and exc_tb is None:
if self.expected_warning is not None:
if not any(issubclass(r.category, self.expected_warning) for r in self):
__tracebackhide__ = True
if self.expected_warning is not None:
if not any(issubclass(r.category, self.expected_warning) for r in self):
__tracebackhide__ = True
fail(
f"DID NOT WARN. No warnings of type {self.expected_warning} were emitted.\n"
f"The list of emitted warnings is: {found_str()}."
)
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:
fail(
f"DID NOT WARN. No warnings of type {self.expected_warning} were emitted.\n"
f"The list of emitted warnings is: {found_str()}."
)
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:
fail(
f"""\
f"""\
DID NOT WARN. No warnings of type {self.expected_warning} matching the regex were emitted.
Regex: {self.match_expr}
Emitted warnings: {found_str()}"""
)
)

View File

@ -179,6 +179,7 @@ class TestDeprecatedCall:
"""
def f():
warnings.warn(DeprecationWarning("hi"))
raise ValueError("some exception")
with pytest.raises(ValueError, match="some exception"):