diff --git a/_pytest/python.py b/_pytest/python.py index 4262d6fa7..b2cf99efb 100644 --- a/_pytest/python.py +++ b/_pytest/python.py @@ -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) @@ -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): @@ -1448,7 +1454,7 @@ class RaisesContext(object): 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. diff --git a/testing/python/raises.py b/testing/python/raises.py index 0ea7f9bee..b42f4f54d 100644 --- a/testing/python/raises.py +++ b/testing/python/raises.py @@ -76,3 +76,20 @@ class TestRaises: 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