diff --git a/changelog/9036.bugfix.rst b/changelog/9036.bugfix.rst new file mode 100644 index 00000000000..4f25f82e292 --- /dev/null +++ b/changelog/9036.bugfix.rst @@ -0,0 +1 @@ +``pytest.warns`` and similar functions now capture warnings when an exception is raised inside a ``with`` block. diff --git a/src/_pytest/recwarn.py b/src/_pytest/recwarn.py index 9c6e7e91daf..0569e0b48aa 100644 --- a/src/_pytest/recwarn.py +++ b/src/_pytest/recwarn.py @@ -280,24 +280,22 @@ def __exit__( 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()}""" - ) + ) diff --git a/testing/test_recwarn.py b/testing/test_recwarn.py index 7e0f836a634..5dfd8942253 100644 --- a/testing/test_recwarn.py +++ b/testing/test_recwarn.py @@ -179,6 +179,7 @@ def test_deprecated_call_exception_is_raised(self, mode) -> None: """ def f(): + warnings.warn(DeprecationWarning("hi")) raise ValueError("some exception") with pytest.raises(ValueError, match="some exception"):