Skip to content

Commit fbe18fc

Browse files
authored
Merge pull request #11991 from bluetech/warns-fix
recwarn: fix pytest.warns handling of Warnings with multiple arguments
2 parents 6ef0cf1 + 9b838f4 commit fbe18fc

File tree

3 files changed

+19
-4
lines changed

3 files changed

+19
-4
lines changed

changelog/11906.bugfix.rst

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix regression with :func:`pytest.warns` using custom warning subclasses which have more than one parameter in their `__init__`.

src/_pytest/recwarn.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -334,10 +334,10 @@ def found_str() -> str:
334334
for w in self:
335335
if not self.matches(w):
336336
warnings.warn_explicit(
337-
str(w.message),
338-
w.message.__class__, # type: ignore[arg-type]
339-
w.filename,
340-
w.lineno,
337+
message=w.message,
338+
category=w.category,
339+
filename=w.filename,
340+
lineno=w.lineno,
341341
module=w.__module__,
342342
source=w.source,
343343
)

testing/test_recwarn.py

+14
Original file line numberDiff line numberDiff line change
@@ -581,3 +581,17 @@ def test_raise_type_error_on_invalid_warning_message_cpython() -> None:
581581
with warnings.catch_warnings():
582582
warnings.filterwarnings("ignore", "test")
583583
warnings.warn(1) # type: ignore
584+
585+
586+
def test_multiple_arg_custom_warning() -> None:
587+
"""Test for issue #11906."""
588+
589+
class CustomWarning(UserWarning):
590+
def __init__(self, a, b):
591+
pass
592+
593+
with pytest.warns(CustomWarning):
594+
with pytest.raises(pytest.fail.Exception, match="DID NOT WARN"):
595+
with pytest.warns(CustomWarning, match="not gonna match"):
596+
a, b = 1, 2
597+
warnings.warn(CustomWarning(a, b))

0 commit comments

Comments
 (0)