Skip to content

raises regexp #372

@pytestbot

Description

@pytestbot

Originally reported by: György Kiss (BitBucket: kissgyorgy, GitHub: kissgyorgy)


I used assertRaisesRegexp in unittest and I miss it from pytest. As I don't want to use unittest anymore :D I wrote a context manager:

#!python

import pytest
import py

class raises_regexp(object):
    def __init__(self, exception, message):
        self.exception = exception
        self.message = message
        self.excinfo = None

    def __enter__(self):
        self.excinfo = object.__new__(py.code.ExceptionInfo)
        return self.excinfo

    def __exit__(self, exc_type, exc_val, exc_tb):
        __tracebackhide__ = True
        if exc_type is None:
            pytest.fail('DID NOT RAISE %s' % self.exception)

        self.excinfo.__init__((exc_type, exc_val, exc_tb))

        if not issubclass(self.excinfo.type, self.exception):
            pytest.fail('%s RAISED instead of %s' % (exc_type, self.exception))

        if self.message not in str(exc_val):
            pytest.fail('message "%s" not found in "%s"' % (self.message, str(exc_val)))

        return True

Usage:

#!python

def test_some_exception_thrown():
    with raises_regexp(ExpectedException, "message contained"):
       # code to test

I think others could benefit from something like this and would be nice to have it in pytest!


Metadata

Metadata

Assignees

No one assigned

    Labels

    good first issueeasy issue that is friendly to new contributortype: proposalproposal for a new feature, often to gather opinions or design the API around the new feature

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions