Skip to content

Commit 15524f3

Browse files
CheuktingZac-HD
authored andcommitted
capture warning when exception is raised (fix #9036)
1 parent 679bd6f commit 15524f3

File tree

3 files changed

+13
-21
lines changed

3 files changed

+13
-21
lines changed

changelog/9036.bugfix.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
``pytest.warns`` and similar functions now capture warnings when an exception is raised inside a ``with`` block.

src/_pytest/recwarn.py

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -298,11 +298,6 @@ def __exit__(
298298
# nothing to do in this deprecated case, see WARNS_NONE_ARG above
299299
return
300300

301-
if not (exc_type is None and exc_val is None and exc_tb is None):
302-
# We currently ignore missing warnings if an exception is active.
303-
# TODO: fix this, because it means things are surprisingly order-sensitive.
304-
return
305-
306301
def found_str():
307302
return pformat([record.message for record in self], indent=2)
308303

testing/test_recwarn.py

Lines changed: 12 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -172,22 +172,6 @@ def f():
172172
with pytest.deprecated_call():
173173
assert f() == 10
174174

175-
@pytest.mark.parametrize("mode", ["context_manager", "call"])
176-
def test_deprecated_call_exception_is_raised(self, mode) -> None:
177-
"""If the block of the code being tested by deprecated_call() raises an exception,
178-
it must raise the exception undisturbed.
179-
"""
180-
181-
def f():
182-
raise ValueError("some exception")
183-
184-
with pytest.raises(ValueError, match="some exception"):
185-
if mode == "call":
186-
pytest.deprecated_call(f)
187-
else:
188-
with pytest.deprecated_call():
189-
f()
190-
191175
def test_deprecated_call_specificity(self) -> None:
192176
other_warnings = [
193177
Warning,
@@ -446,3 +430,15 @@ def test_re_emit_non_match_single(self) -> None:
446430
with pytest.warns(UserWarning, match="v1 warning"):
447431
warnings.warn("v1 warning", UserWarning)
448432
warnings.warn("non-matching v2 warning", UserWarning)
433+
434+
def test_catch_warning_within_raise(self) -> None:
435+
# warns-in-raises works since https://github.com/pytest-dev/pytest/pull/11129
436+
with pytest.raises(ValueError, match="some exception"):
437+
with pytest.warns(FutureWarning, match="some warning"):
438+
warnings.warn("some warning", category=FutureWarning)
439+
raise ValueError("some exception")
440+
# and raises-in-warns has always worked but we'll check for symmetry.
441+
with pytest.warns(FutureWarning, match="some warning"):
442+
with pytest.raises(ValueError, match="some exception"):
443+
warnings.warn("some warning", category=FutureWarning)
444+
raise ValueError("some exception")

0 commit comments

Comments
 (0)