Skip to content

Commit 04fe383

Browse files
authored
[3.13] gh-146480: Add tests on _PyErr_SetKeyError() (#146486) (#146512)
gh-146480: Add tests on _PyErr_SetKeyError() (#146486) (cherry picked from commit d4153a9)
1 parent 9ee6b67 commit 04fe383

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

Lib/test/test_capi/test_exceptions.py

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,9 @@
1313

1414
from .test_misc import decode_stderr
1515

16-
# Skip this test if the _testcapi module isn't available.
16+
# Skip this test if the _testcapi or _testinternalcapi module isn't available.
1717
_testcapi = import_helper.import_module('_testcapi')
18+
_testinternalcapi = import_helper.import_module('_testinternalcapi')
1819

1920
NULL = None
2021

@@ -108,6 +109,26 @@ def __del__(self):
108109
b'<string>:7: RuntimeWarning: Testing PyErr_WarnEx',
109110
])
110111

112+
def test__pyerr_setkeyerror(self):
113+
# Test _PyErr_SetKeyError()
114+
_pyerr_setkeyerror = _testinternalcapi._pyerr_setkeyerror
115+
for arg in (
116+
"key",
117+
# check that a tuple argument is not unpacked
118+
(1, 2, 3),
119+
# PyErr_SetObject(exc_type, exc_value) uses exc_value if it's
120+
# already an exception, but _PyErr_SetKeyError() always creates a
121+
# new KeyError.
122+
KeyError('arg'),
123+
):
124+
with self.subTest(arg=arg):
125+
with self.assertRaises(KeyError) as cm:
126+
# Test calling _PyErr_SetKeyError() with an exception set
127+
# to check that the function overrides the current
128+
# exception.
129+
_pyerr_setkeyerror(arg)
130+
self.assertEqual(cm.exception.args, (arg,))
131+
111132

112133
class Test_FatalError(unittest.TestCase):
113134

Modules/_testinternalcapi.c

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1986,6 +1986,20 @@ gh_119213_getargs_impl(PyObject *module, PyObject *spam)
19861986
}
19871987

19881988

1989+
static PyObject *
1990+
_pyerr_setkeyerror(PyObject *self, PyObject *arg)
1991+
{
1992+
// Test that _PyErr_SetKeyError() overrides the current exception
1993+
// if an exception is set
1994+
PyErr_NoMemory();
1995+
1996+
_PyErr_SetKeyError(arg);
1997+
1998+
assert(PyErr_Occurred());
1999+
return NULL;
2000+
}
2001+
2002+
19892003
static PyMethodDef module_functions[] = {
19902004
{"get_configs", get_configs, METH_NOARGS},
19912005
{"get_recursion_depth", get_recursion_depth, METH_NOARGS},
@@ -2076,6 +2090,7 @@ static PyMethodDef module_functions[] = {
20762090
{"uop_symbols_test", _Py_uop_symbols_test, METH_NOARGS},
20772091
#endif
20782092
GH_119213_GETARGS_METHODDEF
2093+
{"_pyerr_setkeyerror", _pyerr_setkeyerror, METH_O},
20792094
{NULL, NULL} /* sentinel */
20802095
};
20812096

0 commit comments

Comments
 (0)