Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
add test for PyErr_SetObject
  • Loading branch information
iritkatriel committed Mar 7, 2023
commit 077747d86858ecf548d15177b5c63290e489dda3
19 changes: 19 additions & 0 deletions Lib/test/test_capi/test_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,25 @@ def test_err_restore(self):
self.assertEqual(1, v.args[0])
self.assertIs(tb, v.__traceback__.tb_next)

def test_set_object(self):

# new exception as obj is not an exception
with self.assertRaises(ValueError) as e:
_testcapi.exc_set_object(ValueError, 42)
self.assertEqual(e.exception.args, (42,))

# wraps the exception because unrelated types
with self.assertRaises(ValueError) as e:
_testcapi.exc_set_object(ValueError, TypeError(1,2,3))
wrapped = e.exception.args[0]
self.assertIsInstance(wrapped, TypeError)
self.assertEqual(wrapped.args, (1, 2, 3))

# is superclass, so does not wrap
with self.assertRaises(PermissionError) as e:
_testcapi.exc_set_object(OSError, PermissionError(24))
self.assertEqual(e.exception.args, (24,))


if __name__ == "__main__":
unittest.main()
15 changes: 15 additions & 0 deletions Modules/_testcapi/exceptions.c
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,20 @@ make_exception_with_doc(PyObject *self, PyObject *args, PyObject *kwargs)
return PyErr_NewExceptionWithDoc(name, doc, base, dict);
}

static PyObject *
exc_set_object(PyObject *self, PyObject *args)
{
PyObject *exc;
PyObject *obj;

if (!PyArg_ParseTuple(args, "OO:exc_set_object", &exc, &obj)) {
return NULL;
}

PyErr_SetObject(exc, obj);
return NULL;
}

static PyObject *
raise_exception(PyObject *self, PyObject *args)
{
Expand Down Expand Up @@ -247,6 +261,7 @@ static PyMethodDef test_methods[] = {
PyDoc_STR("fatal_error(message, release_gil=False): call Py_FatalError(message)")},
{"make_exception_with_doc", _PyCFunction_CAST(make_exception_with_doc),
METH_VARARGS | METH_KEYWORDS},
{"exc_set_object", exc_set_object, METH_VARARGS},
{"raise_exception", raise_exception, METH_VARARGS},
{"raise_memoryerror", raise_memoryerror, METH_NOARGS},
{"set_exc_info", test_set_exc_info, METH_VARARGS},
Expand Down