gh-76595: Add tests for PyCapsule_Import()#154588
Conversation
Add _testcapi helpers to create a capsule with an arbitrary name and to call PyCapsule_Import(), and Python tests covering the current behavior: only the first component of the dotted name is imported, the rest are attribute lookups. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
| @@ -0,0 +1,63 @@ | |||
| #include "parts.h" | |||
There was a problem hiding this comment.
It seems like the whole PyCapsule C API is part of the limited C API, so you can move this file to Modules/_testlimitedcapi/.
| return NULL; | ||
| } | ||
| char *name_copy = NULL; | ||
| if (name != NULL) { |
There was a problem hiding this comment.
In which case name can be NULL? I expect that with the current code, name is always non-NULL.
It means that name_copy is always non-NULL when pointer is initialized, and so that the &dummy code path is never taken.
If name can be NULL, calling capsule_destructor() on &dummy seems to be wrong to me.
There was a problem hiding this comment.
It can be NULL, the code supports this. Although it is not too useful. But the wrapper should not restrict what can be passed to the C API.
capsule_destructor() is a no-op if name is NULL. free() is not called on &dummy, it is called on PyCapsule_GetName(op).
| self.assertRaises(ImportError, | ||
| _testcapi.PyCapsule_Import, 'capsule_broken.capsule') |
There was a problem hiding this comment.
Hum, I would prefer to test also the exception message since this case is a little bit special.
| self.assertRaises(ImportError, | |
| _testcapi.PyCapsule_Import, 'capsule_broken.capsule') | |
| with self.assertRaises(ImportError) as cm: | |
| _testcapi.PyCapsule_Import('capsule_broken.capsule') | |
| self.assertEqual(str(cm.exception), | |
| 'PyCapsule_Import could not import ' | |
| 'module "capsule_broken"') |
Co-authored-by: Victor Stinner <vstinner@python.org>
The PyCapsule C API is part of the limited C API. Also assert the messages of the ImportError raised by PyCapsule_Import() and fix the check_import() helper after applying the review suggestion. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
PyCapsule_Import()was only exercised by the best-effort loop in thetest_capsuleC self-test.Add
_testcapihelpers to create a capsule with an arbitrary name and to callPyCapsule_Import()from Python, and tests covering the current behavior, including error cases and non-ASCII, non-UTF-8 and NULL names.🤖 Generated with Claude Code