recwarn: minor style improvements

In preparation for next commit.
This commit is contained in:
Ran Benita 2024-02-16 13:38:55 +02:00
parent 8e56795b77
commit dcf9da92be
1 changed files with 16 additions and 11 deletions

View File

@ -314,7 +314,7 @@ class WarningsChecker(WarningsRecorder):
): ):
return return
def found_str(): def found_str() -> str:
return pformat([record.message for record in self], indent=2) return pformat([record.message for record in self], indent=2)
try: try:
@ -341,14 +341,19 @@ class WarningsChecker(WarningsRecorder):
module=w.__module__, module=w.__module__,
source=w.source, source=w.source,
) )
# Check warnings has valid argument type (#10865).
wrn: warnings.WarningMessage
for wrn in self:
self._validate_message(wrn)
@staticmethod # Currently in Python it is possible to pass other types than an
def _validate_message(wrn: Any) -> None: # `str` message when creating `Warning` instances, however this
if not isinstance(msg := wrn.message.args[0], str): # causes an exception when :func:`warnings.filterwarnings` is used
raise TypeError( # to filter those warnings. See
f"Warning message must be str, got {msg!r} (type {type(msg).__name__})" # https://github.com/python/cpython/issues/103577 for a discussion.
) # While this can be considered a bug in CPython, we put guards in
# pytest as the error message produced without this check in place
# is confusing (#10865).
for w in self:
msg = w.message.args[0] # type: ignore[union-attr]
if isinstance(msg, str):
continue
raise TypeError(
f"Warning message must be str, got {msg!r} (type {type(msg).__name__})"
)