Skip to content

Commit

Permalink
capture warning when exception is raised (fix pytest-dev#9036)
Browse files Browse the repository at this point in the history
  • Loading branch information
Cheukting authored and Zac-HD committed Jun 30, 2023
1 parent 679bd6f commit 15524f3
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 21 deletions.
1 change: 1 addition & 0 deletions changelog/9036.bugfix.rst
@@ -0,0 +1 @@
``pytest.warns`` and similar functions now capture warnings when an exception is raised inside a ``with`` block.
5 changes: 0 additions & 5 deletions src/_pytest/recwarn.py
Expand Up @@ -298,11 +298,6 @@ def __exit__(
# nothing to do in this deprecated case, see WARNS_NONE_ARG above
return

if not (exc_type is None and exc_val is None and exc_tb is None):
# We currently ignore missing warnings if an exception is active.
# TODO: fix this, because it means things are surprisingly order-sensitive.
return

def found_str():
return pformat([record.message for record in self], indent=2)

Expand Down
28 changes: 12 additions & 16 deletions testing/test_recwarn.py
Expand Up @@ -172,22 +172,6 @@ def f():
with pytest.deprecated_call():
assert f() == 10

@pytest.mark.parametrize("mode", ["context_manager", "call"])
def test_deprecated_call_exception_is_raised(self, mode) -> None:
"""If the block of the code being tested by deprecated_call() raises an exception,
it must raise the exception undisturbed.
"""

def f():
raise ValueError("some exception")

with pytest.raises(ValueError, match="some exception"):
if mode == "call":
pytest.deprecated_call(f)
else:
with pytest.deprecated_call():
f()

def test_deprecated_call_specificity(self) -> None:
other_warnings = [
Warning,
Expand Down Expand Up @@ -446,3 +430,15 @@ def test_re_emit_non_match_single(self) -> None:
with pytest.warns(UserWarning, match="v1 warning"):
warnings.warn("v1 warning", UserWarning)
warnings.warn("non-matching v2 warning", UserWarning)

def test_catch_warning_within_raise(self) -> None:
# warns-in-raises works since https://github.com/pytest-dev/pytest/pull/11129
with pytest.raises(ValueError, match="some exception"):
with pytest.warns(FutureWarning, match="some warning"):
warnings.warn("some warning", category=FutureWarning)
raise ValueError("some exception")
# and raises-in-warns has always worked but we'll check for symmetry.
with pytest.warns(FutureWarning, match="some warning"):
with pytest.raises(ValueError, match="some exception"):
warnings.warn("some warning", category=FutureWarning)
raise ValueError("some exception")

0 comments on commit 15524f3

Please sign in to comment.