| 1 | import pytest |
| 2 | from .support import HPyTest, make_hpy_abi_fixture |
| 3 | from .test_capsule import CapsuleTemplate |
| 4 | |
| 5 | hpy_abi = make_hpy_abi_fixture('with hybrid') |
| 6 | |
| 7 | class TestHPyCapsuleLegacy(HPyTest): |
| 8 | |
| 9 | ExtensionTemplate = CapsuleTemplate |
| 10 | |
| 11 | def test_legacy_capsule_compat(self): |
| 12 | import pytest |
| 13 | mod = self.make_module(""" |
| 14 | @DEFINE_strdup |
| 15 | |
| 16 | #include <Python.h> |
| 17 | #include <string.h> |
| 18 | |
| 19 | static int dummy = 123; |
| 20 | |
| 21 | static void legacy_destructor(PyObject *capsule) |
| 22 | { |
| 23 | /* We need to use C lib 'free' because the string was |
| 24 | created with 'strdup0'. */ |
| 25 | free((void *) PyCapsule_GetName(capsule)); |
| 26 | } |
| 27 | |
| 28 | HPyDef_METH(Create_pycapsule, "create_pycapsule", HPyFunc_O) |
| 29 | static HPy Create_pycapsule_impl(HPyContext *ctx, HPy self, HPy arg) |
| 30 | { |
| 31 | HPy_ssize_t n; |
| 32 | const char *name = HPyUnicode_AsUTF8AndSize(ctx, arg, &n); |
| 33 | char *name_copy = strdup0(name); |
| 34 | if (name_copy == NULL) { |
| 35 | HPyErr_SetString(ctx, ctx->h_MemoryError, "out of memory"); |
| 36 | return HPy_NULL; |
| 37 | } |
| 38 | PyObject *legacy_caps = PyCapsule_New(&dummy, (const char *) name_copy, |
| 39 | legacy_destructor); |
| 40 | HPy res = HPy_FromPyObject(ctx, legacy_caps); |
| 41 | Py_DECREF(legacy_caps); |
| 42 | return res; |
| 43 | } |
| 44 | |
| 45 | HPyDef_METH(Capsule_get, "get", HPyFunc_O) |
| 46 | static HPy Capsule_get_impl(HPyContext *ctx, HPy self, HPy arg) |
| 47 | { |
| 48 | HPy res = HPy_NULL; |
| 49 | HPy h_value = HPy_NULL; |
| 50 | int *ptr = NULL; |
| 51 | |
| 52 | const char *name = HPyCapsule_GetName(ctx, arg); |
| 53 | if (name == NULL && HPyErr_Occurred(ctx)) { |
| 54 | return HPy_NULL; |
| 55 | } |
| 56 | HPy h_name = HPyUnicode_FromString(ctx, name); |
| 57 | if (HPy_IsNull(h_name)) { |
| 58 | goto finish; |
| 59 | } |
| 60 | |
| 61 | ptr = (int *) HPyCapsule_GetPointer(ctx, arg, name); |
| 62 | if (ptr == NULL && HPyErr_Occurred(ctx)) { |
| 63 | goto finish; |
| 64 | } |
| 65 | |
| 66 | h_value = HPyLong_FromLong(ctx, *ptr); |
| 67 | if (HPy_IsNull(h_value)) { |
| 68 | goto finish; |
| 69 | } |
| 70 | |
| 71 | res = HPyTuple_Pack(ctx, 2, h_name, h_value); |
| 72 | |
| 73 | finish: |
| 74 | HPy_Close(ctx, h_name); |
| 75 | HPy_Close(ctx, h_value); |
| 76 | return res; |
| 77 | } |
| 78 | |
| 79 | @EXPORT(Create_pycapsule) |
| 80 | @EXPORT(Capsule_get) |
| 81 | |
| 82 | @INIT |
| 83 | """) |
| 84 | name = "legacy_capsule" |
| 85 | p = mod.create_pycapsule(name) |
| 86 | assert mod.get(p) == (name, 123) |