Skip to content

Commit 4f2db6c

Browse files
authored
Merge pull request #1616 from palaviv/pytest.raises-message
Pytest.raises custom error message
2 parents f3aead8 + f8d4cad commit 4f2db6c

File tree

4 files changed

+52
-5
lines changed

4 files changed

+52
-5
lines changed

CHANGELOG.rst

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,9 @@
7070
* Add ``build/`` and ``dist/`` to the default ``--norecursedirs`` list. Thanks
7171
`@mikofski`_ for the report and `@tomviner`_ for the PR (`#1544`_).
7272

73-
*
73+
* pytest.raises in the context manager form accepts a custom
74+
message to raise when no exception occurred.
75+
Thanks `@palaviv`_ for the complete PR (`#1616`_).
7476

7577
.. _@milliams: https://github.com/milliams
7678
.. _@csaftoiu: https://github.com/csaftoiu
@@ -95,6 +97,7 @@
9597
.. _#1520: https://github.com/pytest-dev/pytest/pull/1520
9698
.. _#372: https://github.com/pytest-dev/pytest/issues/372
9799
.. _#1544: https://github.com/pytest-dev/pytest/issues/1544
100+
.. _#1616: https://github.com/pytest-dev/pytest/pull/1616
98101

99102

100103
**Bug Fixes**

_pytest/python.py

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1337,6 +1337,16 @@ def raises(expected_exception, *args, **kwargs):
13371337
>>> with raises(ZeroDivisionError):
13381338
... 1/0
13391339
1340+
.. versionchanged:: 2.10
1341+
1342+
In the context manager form you may use the keyword argument
1343+
``message`` to specify a custom failure message::
1344+
1345+
>>> with raises(ZeroDivisionError, message="Expecting ZeroDivisionError"):
1346+
... pass
1347+
... Failed: Expecting ZeroDivisionError
1348+
1349+
13401350
.. note::
13411351
13421352
When using ``pytest.raises`` as a context manager, it's worthwhile to
@@ -1412,8 +1422,12 @@ def raises(expected_exception, *args, **kwargs):
14121422
elif not isclass(expected_exception):
14131423
raise TypeError(msg % type(expected_exception))
14141424

1425+
message = "DID NOT RAISE {0}".format(expected_exception)
1426+
14151427
if not args:
1416-
return RaisesContext(expected_exception)
1428+
if "message" in kwargs:
1429+
message = kwargs.pop("message")
1430+
return RaisesContext(expected_exception, message)
14171431
elif isinstance(args[0], str):
14181432
code, = args
14191433
assert isinstance(code, str)
@@ -1434,11 +1448,12 @@ def raises(expected_exception, *args, **kwargs):
14341448
func(*args[1:], **kwargs)
14351449
except expected_exception:
14361450
return _pytest._code.ExceptionInfo()
1437-
pytest.fail("DID NOT RAISE {0}".format(expected_exception))
1451+
pytest.fail(message)
14381452

14391453
class RaisesContext(object):
1440-
def __init__(self, expected_exception):
1454+
def __init__(self, expected_exception, message):
14411455
self.expected_exception = expected_exception
1456+
self.message = message
14421457
self.excinfo = None
14431458

14441459
def __enter__(self):
@@ -1448,7 +1463,7 @@ def __enter__(self):
14481463
def __exit__(self, *tp):
14491464
__tracebackhide__ = True
14501465
if tp[0] is None:
1451-
pytest.fail("DID NOT RAISE")
1466+
pytest.fail(self.message)
14521467
if sys.version_info < (2, 7):
14531468
# py26: on __exit__() exc_value often does not contain the
14541469
# exception value.

doc/en/assert.rst

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,15 @@ and if you need to have access to the actual exception info you may use::
8585
the actual exception raised. The main attributes of interest are
8686
``.type``, ``.value`` and ``.traceback``.
8787

88+
.. versionchanged:: 2.10
89+
90+
In the context manager form you may use the keyword argument
91+
``message`` to specify a custom failure message::
92+
93+
>>> with raises(ZeroDivisionError, message="Expecting ZeroDivisionError"):
94+
... pass
95+
... Failed: Expecting ZeroDivisionError
96+
8897
If you want to write test code that works on Python 2.4 as well,
8998
you may also use two other ways to test for an expected exception::
9099

testing/python/raises.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,3 +76,23 @@ def test_no_raise_message(self):
7676
pytest.raises(ValueError, int, '0')
7777
except pytest.raises.Exception as e:
7878
assert e.msg == "DID NOT RAISE {0}".format(repr(ValueError))
79+
else:
80+
assert False, "Expected pytest.raises.Exception"
81+
82+
try:
83+
with pytest.raises(ValueError):
84+
pass
85+
except pytest.raises.Exception as e:
86+
assert e.msg == "DID NOT RAISE {0}".format(repr(ValueError))
87+
else:
88+
assert False, "Expected pytest.raises.Exception"
89+
90+
def test_costum_raise_message(self):
91+
message = "TEST_MESSAGE"
92+
try:
93+
with pytest.raises(ValueError, message=message):
94+
pass
95+
except pytest.raises.Exception as e:
96+
assert e.msg == message
97+
else:
98+
assert False, "Expected pytest.raises.Exception"

0 commit comments

Comments
 (0)