| 1 | from pypy.module.cpyext.test.test_api import BaseApiTest, raises_w |
| 2 | from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase |
| 3 | from pypy.module.cpyext.pyobject import make_ref |
| 4 | from pypy.module.cpyext.exception import ( |
| 5 | PyExceptionInstance_Class, PyException_GetTraceback, |
| 6 | PyException_SetTraceback, PyException_GetContext, PyException_SetContext, |
| 7 | PyException_GetCause, PyException_SetCause) |
| 8 | |
| 9 | class TestExceptions(BaseApiTest): |
| 10 | |
| 11 | def test_ExceptionInstance_Class(self, space): |
| 12 | w_instance = space.call_function(space.w_ValueError) |
| 13 | assert PyExceptionInstance_Class( |
| 14 | space, w_instance) is space.w_ValueError |
| 15 | |
| 16 | def test_traceback(self, space): |
| 17 | w_exc = space.call_function(space.w_ValueError) |
| 18 | assert PyException_GetTraceback(space, w_exc) is None |
| 19 | with raises_w(space, TypeError): |
| 20 | PyException_SetTraceback(space, w_exc, space.wrap(1)) |
| 21 | |
| 22 | def test_context(self, space): |
| 23 | w_exc = space.call_function(space.w_ValueError) |
| 24 | assert PyException_GetContext(space, w_exc) is None |
| 25 | w_ctx = space.call_function(space.w_IndexError) |
| 26 | PyException_SetContext(space, w_exc, make_ref(space, w_ctx)) |
| 27 | assert space.is_w(PyException_GetContext(space, w_exc), w_ctx) |
| 28 | |
| 29 | def test_cause(self, space): |
| 30 | w_exc = space.call_function(space.w_ValueError) |
| 31 | assert PyException_GetCause(space, w_exc) is None |
| 32 | w_cause = space.call_function(space.w_IndexError) |
| 33 | PyException_SetCause(space, w_exc, make_ref(space, w_cause)) |
| 34 | assert space.is_w(PyException_GetCause(space, w_exc), w_cause) |
| 35 | |
| 36 | |
| 37 | class AppTestExceptions(AppTestCpythonExtensionBase): |
| 38 | |
| 39 | def test_OSError_aliases(self): |
| 40 | module = self.import_extension('foo', [ |
| 41 | ("get_aliases", "METH_NOARGS", |
| 42 | """ |
| 43 | return PyTuple_Pack(2, |
| 44 | PyExc_EnvironmentError, |
| 45 | PyExc_IOError); |
| 46 | """)]) |
| 47 | assert module.get_aliases() == (OSError, OSError) |
| 48 | |
| 49 | def test_implicit_chaining(self): |
| 50 | module = self.import_extension('foo', [ |
| 51 | ("raise_exc", "METH_NOARGS", |
| 52 | """ |
| 53 | PyObject *ev, *et, *tb; |
| 54 | PyObject *ev0, *et0, *tb0; |
| 55 | PyErr_GetExcInfo(&ev0, &et0, &tb0); |
| 56 | PyErr_SetString(PyExc_ValueError, "foo"); |
| 57 | |
| 58 | // simplified copy of __Pyx_GetException |
| 59 | PyErr_Fetch(&et, &ev, &tb); |
| 60 | PyErr_NormalizeException(&et, &ev, &tb); |
| 61 | if (tb) PyException_SetTraceback(ev, tb); |
| 62 | PyErr_SetExcInfo(et, ev, tb); |
| 63 | |
| 64 | PyErr_SetString(PyExc_TypeError, "bar"); |
| 65 | PyErr_SetExcInfo(ev0, et0, tb0); |
| 66 | return NULL; |
| 67 | """)]) |
| 68 | excinfo = raises(TypeError, module.raise_exc) |
| 69 | assert excinfo.value.__context__ |
| 70 |