Skip to content

Commit 898f8f0

Browse files
committed
Add tests using warnings.warn() with Warnings
`warnings.warn()` expects that its first argument is a `str` or a `Warning`, but since 9454fc3 `pytest.warns()` no longer allows `Warning` instances unless the first argument the `Warning` was initialized with is a `str`. Furthermore, if the `Warning` was created without arguments then `pytest.warns()` raises an unexpected `IndexError`. The new tests reveal the problem.
1 parent 7690a0d commit 898f8f0

File tree

1 file changed

+17
-7
lines changed

1 file changed

+17
-7
lines changed

testing/test_recwarn.py

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -480,24 +480,34 @@ def test_catch_warning_within_raise(self) -> None:
480480
raise ValueError("some exception")
481481

482482

483-
def test_raise_type_error_on_non_string_warning() -> None:
484-
"""Check pytest.warns validates warning messages are strings (#10865)."""
483+
def test_raise_type_error_on_invalid_warning() -> None:
484+
"""Check pytest.warns validates warning messages are strings (#10865) or
485+
Warning instances (#11959)."""
485486
with pytest.raises(TypeError, match="Warning message must be str"):
486487
with pytest.warns(UserWarning):
487488
warnings.warn(1) # type: ignore
488489

489490

490-
def test_no_raise_type_error_on_string_warning() -> None:
491-
"""Check pytest.warns validates warning messages are strings (#10865)."""
492-
with pytest.warns(UserWarning):
493-
warnings.warn("Warning")
491+
@pytest.mark.parametrize(
492+
"message",
493+
[
494+
pytest.param("Warning", id="str"),
495+
pytest.param(UserWarning(), id="UserWarning"),
496+
pytest.param(Warning(), id="Warning"),
497+
],
498+
)
499+
def test_no_raise_type_error_on_valid_warning(message: str | Warning) -> None:
500+
"""Check pytest.warns validates warning messages are strings (#10865) or
501+
Warning instances (#11959)."""
502+
with pytest.warns(Warning):
503+
warnings.warn(message)
494504

495505

496506
@pytest.mark.skipif(
497507
hasattr(sys, "pypy_version_info"),
498508
reason="Not for pypy",
499509
)
500-
def test_raise_type_error_on_non_string_warning_cpython() -> None:
510+
def test_raise_type_error_on_invalid_warning_message_cpython() -> None:
501511
# Check that we get the same behavior with the stdlib, at least if filtering
502512
# (see https://github.com/python/cpython/issues/103577 for details)
503513
with pytest.raises(TypeError):

0 commit comments

Comments
 (0)