pytest: raises regexp
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 😄 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!
About this issue
- Original URL
- State: closed
- Created 11 years ago
- Comments: 26 (26 by maintainers)
Commits related to this issue
- Make sure `async for` is not broken up to separate lines (#503) Fixes #372. — committed to fkohlgrueber/pytest by zsol 6 years ago
fixed in c578226d43e96d1cc86f14de0779acd96222f0e4