Debian Codegraph @

pypy/module/cpyext/test/test_memoryobject.py

raw symbols SCIP
1 import pytest
2
3 from rpython.rtyper.lltypesystem import rffi
4 from rpython.rlib.buffer import StringBuffer
5
6 from pypy.module.cpyext.test.test_api import BaseApiTest
7 from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase
8 from pypy.interpreter.buffer import SimpleView
9 from pypy.module.cpyext.pyobject import make_ref, from_ref, decref
10 from pypy.module.cpyext.memoryobject import PyMemoryViewObject
11
12 only_pypy ="config.option.runappdirect and '__pypy__' not in sys.builtin_module_names"
13
14 class TestMemoryViewObject(BaseApiTest):
15 def test_frombuffer(self, space, api):
16 w_view = SimpleView(StringBuffer("hello"), w_obj=self).wrap(space)
17 w_memoryview = api.PyMemoryView_FromObject(w_view)
18 c_memoryview = rffi.cast(
19 PyMemoryViewObject, make_ref(space, w_memoryview))
20 view = c_memoryview.c_view
21 assert view.c_ndim == 1
22 f = rffi.charp2str(view.c_format)
23 assert f == 'B'
24 assert view.c_shape[0] == 5
25 assert view.c_strides[0] == 1
26 assert view.c_len == 5
27 o = rffi.charp2str(view.c_buf)
28 assert o == 'hello'
29 ref = api.PyMemoryView_FromBuffer(view)
30 w_mv = from_ref(space, ref)
31 for f in ('format', 'itemsize', 'ndim', 'readonly',
32 'shape', 'strides', 'suboffsets'):
33 w_f = space.wrap(f)
34 assert space.eq_w(space.getattr(w_mv, w_f),
35 space.getattr(w_memoryview, w_f))
36 decref(space, ref)
37 decref(space, c_memoryview)
38
39 def test_class_with___buffer__(self, space, api):
40 w_obj = space.appexec([], """():
41 from __pypy__.bufferable import bufferable
42 class B(bufferable):
43 def __init__(self):
44 self.buf = bytearray(10)
45
46 def __buffer__(self, flags):
47 return memoryview(self.buf)
48 return B()""")
49 py_obj = make_ref(space, w_obj)
50 assert py_obj.c_ob_type.c_tp_as_buffer
51 assert py_obj.c_ob_type.c_tp_as_buffer.c_bf_getbuffer
52 assert not py_obj.c_ob_type.c_tp_as_buffer.c_bf_releasebuffer
53
54
55 class AppTestPyBuffer(AppTestCpythonExtensionBase):
56 def test_fillWithObject(self):
57 module = self.import_extension('foo', [
58 ("fillinfo", "METH_VARARGS",
59 """
60 Py_buffer buf;
61 PyObject * ret = NULL;
62 PyObject *str = PyBytes_FromString("hello, world.");
63 if (PyBuffer_FillInfo(&buf, str, PyBytes_AsString(str), 13,
64 0, 0)) {
65 return NULL;
66 }
67
68 /* Get rid of our own reference to the object, but
69 * the Py_buffer should still have a reference.
70 */
71 Py_DECREF(str);
72
73 ret = PyMemoryView_FromBuffer(&buf);
74 if (((PyMemoryViewObject*)ret)->view.obj != NULL)
75 {
76 PyErr_SetString(PyExc_ValueError, "leaked ref");
77 Py_DECREF(ret);
78 return NULL;
79 }
80 return ret;
81 """)])
82 result = module.fillinfo()
83 assert b"hello, world." == result
84
85 @pytest.mark.skip(reason="segfaults on linux buildslave")
86 def test_0d(self):
87 module = self.import_extension('foo', [
88 ("create_view", "METH_VARARGS",
89 """
90 /* Create an approximation of the buffer for a 0d ndarray */
91 Py_buffer buf;
92 PyObject *ret, *str = PyBytes_FromString("hello, world.");
93 buf.buf = PyBytes_AsString(str);
94 buf.obj = str;
95 buf.readonly = 1;
96 buf.len = 13;
97 buf.itemsize = 13;
98 buf.ndim = 0;
99 buf.shape = NULL;
100 ret = PyMemoryView_FromBuffer(&buf);
101 return ret;
102 """)])
103 result = module.create_view()
104 assert result.shape == ()
105 assert result.itemsize == 13
106 assert result.tobytes() == b'hello, world.'
107
108 def test_fromobject(self):
109 foo = self.import_extension('foo', [
110 ("make_view", "METH_O",
111 """
112 if (!PyObject_CheckBuffer(args))
113 return Py_None;
114 return PyMemoryView_FromObject(args);
115 """)])
116 hello = b'hello'
117 mview = foo.make_view(hello)
118 assert mview[0] == hello[0]
119 assert mview.tobytes() == hello
120
121 def test_buffer_protocol_app(self):
122 module = self.import_module(name='buffer_test')
123 arr = module.PyMyArray(10)
124 y = memoryview(arr)
125 assert y.format == 'i'
126 assert y.shape == (10,)
127 assert len(y) == 10
128 s = y[3]
129 assert s == 3
130
131 def test_buffer_protocol_capi(self):
132 foo = self.import_extension('foo', [
133 ("get_len", "METH_VARARGS",
134 """
135 Py_buffer view;
136 PyObject* obj = PyTuple_GetItem(args, 0);
137 long ret, vlen;
138 memset(&view, 0, sizeof(Py_buffer));
139 ret = PyObject_GetBuffer(obj, &view, PyBUF_FULL_RO);
140 if (ret != 0)
141 return NULL;
142 vlen = view.len / view.itemsize;
143 PyBuffer_Release(&view);
144 return PyLong_FromLong(vlen);
145 """),
146 ("test_buffer", "METH_VARARGS",
147 """
148 Py_buffer* view = NULL;
149 PyObject* obj = PyTuple_GetItem(args, 0);
150 PyObject* memoryview = PyMemoryView_FromObject(obj);
151 if (memoryview == NULL)
152 return NULL;
153 view = PyMemoryView_GET_BUFFER(memoryview);
154 Py_DECREF(memoryview);
155 return PyLong_FromLong(view->len / view->itemsize);
156 """),
157 ("test_contiguous", "METH_O",
158 """
159 Py_buffer* view;
160 PyObject * memoryview;
161 void * buf = NULL;
162 int ret;
163 Py_ssize_t len;
164 memoryview = PyMemoryView_FromObject(args);
165 if (memoryview == NULL)
166 return NULL;
167 view = PyMemoryView_GET_BUFFER(memoryview);
168 Py_DECREF(memoryview);
169 len = view->len;
170 if (len == 0)
171 return NULL;
172 buf = malloc(len);
173 ret = PyBuffer_ToContiguous(buf, view, view->len, 'A');
174 if (ret != 0)
175 {
176 free(buf);
177 return NULL;
178 }
179 ret = PyBuffer_FromContiguous(view, buf, view->len, 'A');
180 free(buf);
181 if (ret != 0)
182 return NULL;
183 Py_RETURN_NONE;
184 """),
185 ("get_contiguous", "METH_O",
186 """
187 return PyMemoryView_GetContiguous(args, PyBUF_READ, 'C');
188 """),
189 ("get_readonly", "METH_O",
190 """
191 Py_buffer view;
192 int readonly;
193 memset(&view, 0, sizeof(view));
194 if (PyObject_GetBuffer(args, &view, PyBUF_SIMPLE) != 0) {
195 return NULL;
196 }
197 readonly = view.readonly;
198 PyBuffer_Release(&view);
199 return PyLong_FromLong(readonly);
200 """),
201 ])
202 module = self.import_module(name='buffer_test')
203 arr = module.PyMyArray(10)
204 ten = foo.get_len(arr)
205 assert ten == 10
206 ten = foo.get_len(b'1234567890')
207 assert ten == 10
208 ten = foo.test_buffer(arr)
209 assert ten == 10
210 foo.test_contiguous(arr)
211 contig = foo.get_contiguous(arr)
212 foo.test_contiguous(contig)
213 ro = foo.get_readonly(b'abc')
214 assert ro == 1
215 try:
216 from _numpypy import multiarray as np
217 except ImportError:
218 skip('pypy built without _numpypy')
219 a = np.arange(20)[::2]
220 skip('not implemented yet')
221 contig = foo.get_contiguous(a)
222 foo.test_contiguous(contig)
223
224
225 def test_releasebuffer(self):
226 module = self.import_extension('foo', [
227 ("create_test", "METH_NOARGS",
228 """
229 PyObject *obj;
230 obj = PyObject_New(PyObject, (PyTypeObject*)type);
231 return obj;
232 """),
233 ("get_cnt", "METH_NOARGS",
234 'return PyLong_FromLong(cnt);'),
235 ("get_dealloc_cnt", "METH_NOARGS",
236 'return PyLong_FromLong(dealloc_cnt);'),
237 ],
238 prologue="""
239 static float test_data = 42.f;
240 static int cnt=0;
241 static int dealloc_cnt=0;
242 static PyHeapTypeObject * type=NULL;
243
244 void dealloc(PyObject *self) {
245 dealloc_cnt++;
246 }
247 int getbuffer(PyObject *obj, Py_buffer *view, int flags) {
248
249 cnt ++;
250 memset(view, 0, sizeof(Py_buffer));
251 view->obj = obj;
252 /* see the CPython docs for why we need this incref:
253 https://docs.python.org/3.5/c-api/typeobj.html#c.PyBufferProcs.bf_getbuffer */
254 Py_INCREF(obj);
255 view->ndim = 0;
256 view->buf = (void *) &test_data;
257 view->itemsize = sizeof(float);
258 view->len = 1;
259 view->strides = NULL;
260 view->shape = NULL;
261 view->format = "f";
262 return 0;
263 }
264
265 void releasebuffer(PyObject *obj, Py_buffer *view) {
266 cnt --;
267 }
268 """, more_init="""
269 type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
270
271 type->ht_type.tp_name = "Test";
272 type->ht_type.tp_basicsize = sizeof(PyObject);
273 type->ht_name = PyUnicode_FromString("Test");
274 type->ht_type.tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
275 Py_TPFLAGS_HEAPTYPE;
276 type->ht_type.tp_flags &= ~Py_TPFLAGS_HAVE_GC;
277
278 type->ht_type.tp_dealloc = dealloc;
279 type->ht_type.tp_as_buffer = &type->as_buffer;
280 type->as_buffer.bf_getbuffer = getbuffer;
281 type->as_buffer.bf_releasebuffer = releasebuffer;
282
283 if (PyType_Ready(&type->ht_type) < 0) INITERROR;
284 """, )
285 import gc
286 assert module.get_cnt() == 0
287 a = memoryview(module.create_test())
288 assert module.get_cnt() == 1
289 assert module.get_dealloc_cnt() == 0
290 del a
291 self.debug_collect()
292 assert module.get_cnt() == 0
293 assert module.get_dealloc_cnt() == 1
294
295 def test_FromMemory_readonly(self):
296 module = self.import_extension('foo', [
297 ('new', 'METH_NOARGS', """
298 static char s[5] = "hello";
299 return PyMemoryView_FromMemory(s, 4, PyBUF_READ);
300 """)])
301 mv = module.new()
302 assert mv.readonly == True
303 assert mv.tobytes() == b'hell'
304
305 def test_FromMemory_readwrite(self):
306 module = self.import_extension('foo', [
307 ('new', 'METH_NOARGS', """
308 static char s[5] = "hello";
309 return PyMemoryView_FromMemory(s, 4, PyBUF_WRITE);
310 """)])
311 mv = module.new()
312 assert mv.readonly == False
313 assert mv.tobytes() == b'hell'
314
315 def test_FromBuffer_NULL(self):
316 module = self.import_extension('foo', [
317 ('new', 'METH_NOARGS', """
318 Py_buffer info;
319 if (PyBuffer_FillInfo(&info, NULL, NULL, 1, 1, PyBUF_FULL_RO) < 0)
320 return NULL;
321 return PyMemoryView_FromBuffer(&info);
322 """)])
323 raises(ValueError, module.new)
324
325 def test_release_before_dealloc(self):
326 module = self.import_extension("foo", [
327 ("get_type","METH_NOARGS", """
328 return PyType_FromSpec(&HeapCTypeWithBuffer_spec);
329 """)], prologue="""
330 typedef struct {
331 PyObject_HEAD
332 int value;
333 } HeapCTypeObject;
334
335 typedef struct {
336 HeapCTypeObject base;
337 char buffer[4];
338 } HeapCTypeWithBufferObject;
339
340 static int
341 heapctypewithbuffer_getbuffer(HeapCTypeWithBufferObject *self,
342 Py_buffer *view, int flags)
343 {
344 self->buffer[0] = '1';
345 self->buffer[1] = '2';
346 self->buffer[2] = '3';
347 self->buffer[3] = '4';
348 int ret = PyBuffer_FillInfo(
349 view, (PyObject*)self, (void *)self->buffer, 4, 1, flags);
350 return ret;
351 }
352
353 static void
354 heapctypewithbuffer_releasebuffer(HeapCTypeWithBufferObject *self,
355 Py_buffer *view)
356 {
357 /* Make sure this is called before the dealloc */
358 assert(view->obj == (void*) self);
359 }
360
361 static PyType_Slot HeapCTypeWithBuffer_slots[] = {
362 {Py_bf_getbuffer, heapctypewithbuffer_getbuffer},
363 {Py_bf_releasebuffer, heapctypewithbuffer_releasebuffer},
364 {0, 0},
365 };
366
367 static PyType_Spec HeapCTypeWithBuffer_spec = {
368 "HeapCTypeWithBuffer",
369 sizeof(HeapCTypeWithBufferObject),
370 0,
371 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
372 HeapCTypeWithBuffer_slots
373 };
374 """)
375 HeapCTypeWithBuffer = module.get_type()
376 inst = HeapCTypeWithBuffer()
377 b = bytes(inst)
378 assert b == b"1234"
379 # release the buffer
380 del inst
381 import gc; gc.collect()