test_exceptions.py revision 11986:c12e4625ab56
1import pytest
2
3
4def test_error_already_set(msg):
5    from pybind11_tests import throw_already_set
6
7    with pytest.raises(RuntimeError) as excinfo:
8        throw_already_set(False)
9    assert msg(excinfo.value) == "Unknown internal error occurred"
10
11    with pytest.raises(ValueError) as excinfo:
12        throw_already_set(True)
13    assert msg(excinfo.value) == "foo"
14
15
16def test_python_call_in_catch():
17    from pybind11_tests import python_call_in_destructor
18
19    d = {}
20    assert python_call_in_destructor(d) is True
21    assert d["good"] is True
22
23
24def test_custom(msg):
25    from pybind11_tests import (MyException, MyException5, MyException5_1,
26                                throws1, throws2, throws3, throws4, throws5, throws5_1,
27                                throws_logic_error)
28
29    # Can we catch a MyException?"
30    with pytest.raises(MyException) as excinfo:
31        throws1()
32    assert msg(excinfo.value) == "this error should go to a custom type"
33
34    # Can we translate to standard Python exceptions?
35    with pytest.raises(RuntimeError) as excinfo:
36        throws2()
37    assert msg(excinfo.value) == "this error should go to a standard Python exception"
38
39    # Can we handle unknown exceptions?
40    with pytest.raises(RuntimeError) as excinfo:
41        throws3()
42    assert msg(excinfo.value) == "Caught an unknown exception!"
43
44    # Can we delegate to another handler by rethrowing?
45    with pytest.raises(MyException) as excinfo:
46        throws4()
47    assert msg(excinfo.value) == "this error is rethrown"
48
49    # "Can we fall-through to the default handler?"
50    with pytest.raises(RuntimeError) as excinfo:
51        throws_logic_error()
52    assert msg(excinfo.value) == "this error should fall through to the standard handler"
53
54    # Can we handle a helper-declared exception?
55    with pytest.raises(MyException5) as excinfo:
56        throws5()
57    assert msg(excinfo.value) == "this is a helper-defined translated exception"
58
59    # Exception subclassing:
60    with pytest.raises(MyException5) as excinfo:
61        throws5_1()
62    assert msg(excinfo.value) == "MyException5 subclass"
63    assert isinstance(excinfo.value, MyException5_1)
64
65    with pytest.raises(MyException5_1) as excinfo:
66        throws5_1()
67    assert msg(excinfo.value) == "MyException5 subclass"
68
69    with pytest.raises(MyException5) as excinfo:
70        try:
71            throws5()
72        except MyException5_1:
73            raise RuntimeError("Exception error: caught child from parent")
74    assert msg(excinfo.value) == "this is a helper-defined translated exception"
75