Skip to content

Commit

Permalink
pytest.raises accpets custom message
Browse files Browse the repository at this point in the history
  • Loading branch information
palaviv committed Jun 16, 2016
1 parent 308396a commit d21886c
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
14 changes: 10 additions & 4 deletions _pytest/python.py
Original file line number Diff line number Diff line change
Expand Up @@ -1412,8 +1412,13 @@ def raises(expected_exception, *args, **kwargs):
elif not isclass(expected_exception):
raise TypeError(msg % type(expected_exception))

if "message" in kwargs:
message = kwargs.pop("message")
else:
message = "DID NOT RAISE {0}".format(expected_exception)

if not args:
return RaisesContext(expected_exception)
return RaisesContext(expected_exception, message)
elif isinstance(args[0], str):
code, = args
assert isinstance(code, str)
Expand All @@ -1434,11 +1439,12 @@ def raises(expected_exception, *args, **kwargs):
func(*args[1:], **kwargs)
except expected_exception:
return _pytest._code.ExceptionInfo()
pytest.fail("DID NOT RAISE {0}".format(expected_exception))
pytest.fail(message)

class RaisesContext(object):
def __init__(self, expected_exception):
def __init__(self, expected_exception, message):
self.expected_exception = expected_exception
self.message = message
self.excinfo = None

def __enter__(self):
Expand All @@ -1448,7 +1454,7 @@ def __enter__(self):
def __exit__(self, *tp):
__tracebackhide__ = True
if tp[0] is None:
pytest.fail("DID NOT RAISE")
pytest.fail(self.message)
if sys.version_info < (2, 7):
# py26: on __exit__() exc_value often does not contain the
# exception value.
Expand Down
17 changes: 17 additions & 0 deletions testing/python/raises.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,20 @@ def test_no_raise_message(self):
pytest.raises(ValueError, int, '0')
except pytest.raises.Exception as e:
assert e.msg == "DID NOT RAISE {0}".format(repr(ValueError))
try:
with pytest.raises(ValueError):
pass
except pytest.raises.Exception as e:
e.msg == "DID NOT RAISE {0}".format(repr(ValueError))

def test_costum_raise_message(self):
message = "TEST_MESSAGE"
try:
pytest.raises(ValueError, int, '0', message=message)
except pytest.raises.Exception as e:
assert e.msg == message
try:
with pytest.raises(ValueError, message=message):
pass
except pytest.raises.Exception as e:
e.msg == message

0 comments on commit d21886c

Please sign in to comment.