Improve pytest.raises examples

Fixes issue #586.
This commit is contained in:
Floris Bruynooghe 2014-09-08 14:26:31 +01:00
parent c692a0ee9c
commit d2f448ecee
1 changed files with 11 additions and 8 deletions

View File

@ -66,20 +66,23 @@ In order to write assertions about raised exceptions, you can use
``pytest.raises`` as a context manager like this:: ``pytest.raises`` as a context manager like this::
import pytest import pytest
with pytest.raises(ZeroDivisionError):
1 / 0 def test_zero_division():
with pytest.raises(ZeroDivisionError):
1 / 0
and if you need to have access to the actual exception info you may use:: and if you need to have access to the actual exception info you may use::
with pytest.raises(RuntimeError) as excinfo: def test_recursion_depth():
def f(): with pytest.raises(RuntimeError) as excinfo:
def f():
f()
f() f()
f() assert 'maximum recursion' in str(excinfo.value)
# do checks related to excinfo.type, excinfo.value, excinfo.traceback
``excinfo`` is a `py.code.ExceptionInfo`_ instance, which is a wrapper around ``excinfo`` is a `py.code.ExceptionInfo`_ instance, which is a wrapper around
the actual exception raised. the actual exception raised. The main attributes of interest are
``.type``, ``.value`` and ``.traceback``.
.. _py.code.ExceptionInfo: .. _py.code.ExceptionInfo:
http://pylib.readthedocs.org/en/latest/code.html#py-code-exceptioninfo http://pylib.readthedocs.org/en/latest/code.html#py-code-exceptioninfo