Skip to content

Commit

Permalink
fix doctest and improve unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
aaronzo committed Oct 30, 2024
1 parent ff4206c commit 74ca5ee
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
10 changes: 6 additions & 4 deletions src/_pytest/recwarn.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,15 +145,15 @@ def warns(
You may also set the keyword argument ``keep_ignores`` to avoid catching warnings
which were filtered out, in pytest configuration or otherwise::
>>> warnings.simplefilter("ignore", category=FutureWarning)
>>> warnings.simplefilter("ignore", category=UserWarning)
>>> with pytest.warns(UserWarning, keep_ignores=True):
... warnings.warn("ignore this warning", UserWarning)
Traceback (most recent call last):
...
Failed: DID NOT WARN. No warnings of type ...UserWarning... were emitted...
>>> with pytest.warns(RuntimeWarning):
>>> warnings.simplefilter("ignore", category=FutureWarning)
>>> warnings.simplefilter("ignore", category=UserWarning)
>>> with pytest.warns(UserWarning, keep_ignores=True):
... warnings.warn("ignore this warning", UserWarning)
warnings.warn("keep this warning", RuntimeWarning)
Expand Down Expand Up @@ -260,13 +260,15 @@ def __enter__(self) -> Self:

if self._keep_ignores:
for action, message, category, module, lineno in reversed(warnings.filters):
if isinstance(message, re.Pattern):
module = getattr(module, "pattern", None) # type: ignore[unreachable]
if isinstance(module, re.Pattern):
module = getattr(module, "pattern", None) # type: ignore[unreachable]
warnings.filterwarnings(
action="always" if action != "ignore" else "ignore",
message=message if isinstance(message, str) else "",
message=message or "",
category=category,
module=module if isinstance(module, str) else "",
module=module or "",
lineno=lineno,
)
else:
Expand Down
6 changes: 6 additions & 0 deletions testing/test_recwarn.py
Original file line number Diff line number Diff line change
Expand Up @@ -416,6 +416,12 @@ def test_keep_ignores(self) -> None:
with pytest.warns(UserWarning, keep_ignores=True):
warnings.warn("ignore this warning", FutureWarning)

with pytest.raises(pytest.fail.Exception, match="DID NOT WARN"):
with warnings.catch_warnings():
warnings.filterwarnings("ignore", message="ignore this")
with pytest.warns(UserWarning, keep_ignores=True):
warnings.warn("ignore this warning", UserWarning)

def test_one_from_multiple_warns(self) -> None:
with pytest.warns():
with pytest.raises(pytest.fail.Exception, match="DID NOT WARN"):
Expand Down

0 comments on commit 74ca5ee

Please sign in to comment.