Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Recwarn: Fix module when re-emitting unmatched warnings #12898

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog/11933.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix regression with :func:`pytest.warns` using wrong module when re-emitting unmatched warnings.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice! 👍

11 changes: 10 additions & 1 deletion src/_pytest/recwarn.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

from pprint import pformat
import re
import sys
from types import TracebackType
from typing import Any
from typing import Callable
Expand Down Expand Up @@ -327,12 +328,20 @@ def found_str() -> str:
# Whether or not any warnings matched, we want to re-emit all unmatched warnings.
for w in self:
if not self.matches(w):
module = next(
(
k
for k, v in sys.modules.items()
if getattr(v, "__file__", None) == w.filename
),
None,
)
warnings.warn_explicit(
message=w.message,
category=w.category,
filename=w.filename,
lineno=w.lineno,
module=w.__module__,
module=module,
source=w.source,
)

Expand Down
32 changes: 32 additions & 0 deletions testing/test_recwarn.py
Original file line number Diff line number Diff line change
Expand Up @@ -545,6 +545,38 @@ def test_it():
result.assert_outcomes()


def test_re_emit_uses_correct_module(pytester: Pytester) -> None:
warning_module_code = """
import warnings

def trigger_warning(msg):
warnings.warn(msg, UserWarning)
"""
pytester.makepyfile(module_a=warning_module_code)
pytester.makepyfile(module_b=warning_module_code)

test_code = """
import pytest
import warnings
from module_a import trigger_warning as trigger_warning_a
from module_b import trigger_warning as trigger_warning_b

def test_ignore_warning_from_module_a():
with pytest.raises(pytest.fail.Exception, match="DID NOT WARN"):
with pytest.warns(UserWarning, match="module A.") as outer:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test is not really veryfing the new module attribute... if I go in the code and set module = None in warnings.warn_explicit, the test still passes, which makes it unsuitable for a regression test... can you improve the test to check the actual module attribute of the warnings?

warnings.filterwarnings("ignore", category=UserWarning, module="module_a")
with pytest.warns(UserWarning, match="module B.") as inner: # re-emit the module A warning
trigger_warning_a("module A.")
trigger_warning_b("module B.")
"""
# Write the test to a new file called 'test_re_emit.py'
pytester.makepyfile(test_re_emit=test_code)

# Run the test and assert that it passed
result = pytester.runpytest()
result.assert_outcomes(passed=1)


def test_raise_type_error_on_invalid_warning() -> None:
"""Check pytest.warns validates warning messages are strings (#10865) or
Warning instances (#11959)."""
Expand Down
Loading