Skip to content

RFC: provide warns with a behavior similar to raises  #2708

Closed
@massich

Description

@massich

When dealing with the messages thrown by warnings (IMHO) it would great if we could use the same calls as for the raises case. As example, this would allow for:

    with warns(RuntimeWarning, message='my runtime warning'):
        warnings.warn("my runtime warning", RuntimeWarning)

    with warns(UserWarning, match=r'must be \d+$'):
        warnings.warn("value must be 42", UserWarning)

I have implemented such behavior by wrapping pytest.warns here in the following manner:

from pytest import warns as _warns
from contextlib import contextmanager
from re import compile

@contextmanager
def warns(expected_warning, message=None, match=None):
    with _warns(expected_warning) as record:
        yield

    wrn_msg = str(record[0].message)
    if message is not None:
        assert_msg = '"{}" is different from "{}"'.format(wrn_msg, message)
        assert wrn_msg == message, assert_msg
    elif match is not None:
        regex = compile(match)
        assert_msg = '"{}" pattern not found in "{}"'.format(match, wrn_msg)
        assert regex.search(wrn_msg) is not None, assert_msg
    else:
        pass

Do you think is a valuable feature? Do you think that a PR implementing such behavior is useful to anyone? I'm sure I'm not the first one to wander why warns has different signature than raises. Therefore I can only guess that is not that easy to integrate it to pytest. But If you think that PR is in order I'll be happy to do it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    plugin: warningsrelated to the warnings builtin plugintype: enhancementnew feature or API change, should be merged into features branch

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions