Skip to content

recwarn: fix pytest.warns handling of Warnings with multiple arguments #11991

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

Merged
merged 1 commit into from
Feb 16, 2024
Merged
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/11906.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix regression with :func:`pytest.warns` using custom warning subclasses which have more than one parameter in their `__init__`.
8 changes: 4 additions & 4 deletions src/_pytest/recwarn.py
Original file line number Diff line number Diff line change
Expand Up @@ -334,10 +334,10 @@ def found_str() -> str:
for w in self:
if not self.matches(w):
warnings.warn_explicit(
str(w.message),
w.message.__class__, # type: ignore[arg-type]
w.filename,
w.lineno,
message=w.message,
category=w.category,
filename=w.filename,
lineno=w.lineno,
module=w.__module__,
source=w.source,
)
Expand Down
14 changes: 14 additions & 0 deletions testing/test_recwarn.py
Original file line number Diff line number Diff line change
Expand Up @@ -581,3 +581,17 @@ def test_raise_type_error_on_invalid_warning_message_cpython() -> None:
with warnings.catch_warnings():
warnings.filterwarnings("ignore", "test")
warnings.warn(1) # type: ignore


def test_multiple_arg_custom_warning() -> None:
"""Test for issue #11906."""

class CustomWarning(UserWarning):
def __init__(self, a, b):
pass

with pytest.warns(CustomWarning):
with pytest.raises(pytest.fail.Exception, match="DID NOT WARN"):
with pytest.warns(CustomWarning, match="not gonna match"):
a, b = 1, 2
warnings.warn(CustomWarning(a, b))