Skip to content

Commit

Permalink
changes + test
Browse files Browse the repository at this point in the history
  • Loading branch information
reaganjlee committed Oct 23, 2024
1 parent d0999eb commit ccd67e3
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 3 deletions.
9 changes: 6 additions & 3 deletions src/_pytest/recwarn.py
Original file line number Diff line number Diff line change
Expand Up @@ -329,9 +329,12 @@ def found_str() -> str:
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
(
k
for k, v in sys.modules.items()
if getattr(v, "__file__", None) == w.filename
),
None,
)
warnings.warn_explicit(
message=w.message,
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:
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

0 comments on commit ccd67e3

Please sign in to comment.