From a232abd56cd7ddc0d6dbeefd851c538ec547ab06 Mon Sep 17 00:00:00 2001 From: Ran Benita Date: Fri, 16 Feb 2024 14:29:19 +0200 Subject: [PATCH] [8.0.x] recwarn: fix pytest.warns handling of Warnings with multiple arguments (cherry picked from commit fbe18fc7a9a44982bedc81c1d25f63e6d20fffab) --- changelog/11906.bugfix.rst | 1 + src/_pytest/recwarn.py | 8 ++++---- testing/test_recwarn.py | 14 ++++++++++++++ 3 files changed, 19 insertions(+), 4 deletions(-) create mode 100644 changelog/11906.bugfix.rst diff --git a/changelog/11906.bugfix.rst b/changelog/11906.bugfix.rst new file mode 100644 index 00000000000..68bede540a8 --- /dev/null +++ b/changelog/11906.bugfix.rst @@ -0,0 +1 @@ +Fix regression with :func:`pytest.warns` using custom warning subclasses which have more than one parameter in their `__init__`. diff --git a/src/_pytest/recwarn.py b/src/_pytest/recwarn.py index 52b2b11cf0c..634eff2597a 100644 --- a/src/_pytest/recwarn.py +++ b/src/_pytest/recwarn.py @@ -344,10 +344,10 @@ def found_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, ) diff --git a/testing/test_recwarn.py b/testing/test_recwarn.py index 1db2fe0a12d..a0e70d72aea 100644 --- a/testing/test_recwarn.py +++ b/testing/test_recwarn.py @@ -550,3 +550,17 @@ def test_it(): result = pytester.runpytest_subprocess() assert result.ret == ExitCode.INTERRUPTED result.assert_outcomes() + + +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))