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