Debian Codegraph @

pypy/module/cpyext/test/test_object.py

raw symbols SCIP
1 import pytest
2
3 from pypy.module.cpyext.test.test_api import BaseApiTest, raises_w
4 from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase
5 from rpython.rtyper.lltypesystem import rffi
6 from pypy.module.cpyext.pyobject import get_w_obj_and_decref
7 from pypy.module.cpyext.api import (
8 Py_LT, Py_LE, Py_NE, Py_EQ, Py_GE, Py_GT, INTP_real)
9 from pypy.module.cpyext.object import (
10 PyObject_IsTrue, PyObject_Not, PyObject_GetAttrString,
11 PyObject_GetAttr, PyObject_GetItem, PyObject_SetAttrString,
12 PyObject_SetAttr,
13 PyObject_IsInstance, PyObject_IsSubclass, PyObject_AsFileDescriptor,
14 PyObject_Hash)
15
16 class TestObject(BaseApiTest):
17 def test_IsTrue(self, space, api):
18 assert api.PyObject_IsTrue(space.wrap(1.0)) == 1
19 assert api.PyObject_IsTrue(space.wrap(False)) == 0
20 assert api.PyObject_IsTrue(space.wrap(0)) == 0
21
22 def test_Not(self, space, api):
23 assert api.PyObject_Not(space.wrap(False)) == 1
24 assert api.PyObject_Not(space.wrap(0)) == 1
25 assert api.PyObject_Not(space.wrap(True)) == 0
26 assert api.PyObject_Not(space.wrap(3.14)) == 0
27
28 def test_exception(self, space, api):
29 w_obj = space.appexec([], """():
30 class C:
31 def __bool__(self):
32 raise ValueError
33 return C()""")
34
35 with raises_w(space, ValueError):
36 PyObject_IsTrue(space, w_obj)
37 with raises_w(space, ValueError):
38 PyObject_Not(space, w_obj)
39
40 def test_HasAttr(self, space, api):
41 hasattr_ = lambda w_obj, name: api.PyObject_HasAttr(w_obj,
42 space.wrap(name))
43 assert hasattr_(space.wrap(''), '__len__')
44 assert hasattr_(space.w_int, '__eq__')
45 assert not hasattr_(space.w_int, 'nonexistingattr')
46
47 buf = rffi.str2charp('__len__')
48 assert api.PyObject_HasAttrString(space.w_bytes, buf)
49 assert not api.PyObject_HasAttrString(space.w_int, buf)
50 rffi.free_charp(buf)
51
52 def test_SetAttr(self, space, api):
53 w_obj = space.appexec([], """():
54 class C:
55 pass
56 return C()""")
57
58 api.PyObject_SetAttr(w_obj, space.wrap('test'), space.wrap(5))
59 assert not api.PyErr_Occurred()
60 assert space.unwrap(space.getattr(w_obj, space.wrap('test'))) == 5
61 assert api.PyObject_HasAttr(w_obj, space.wrap('test'))
62 api.PyObject_SetAttr(w_obj, space.wrap('test'), space.wrap(10))
63 assert space.unwrap(space.getattr(w_obj, space.wrap('test'))) == 10
64
65 buf = rffi.str2charp('test')
66 api.PyObject_SetAttrString(w_obj, buf, space.wrap(20))
67 rffi.free_charp(buf)
68 assert space.unwrap(space.getattr(w_obj, space.wrap('test'))) == 20
69
70 def test_getattr(self, space):
71 charp1 = rffi.str2charp("__len__")
72 charp2 = rffi.str2charp("not_real")
73 assert get_w_obj_and_decref(space,
74 PyObject_GetAttrString(space, space.wrap(""), charp1))
75
76 with raises_w(space, AttributeError):
77 PyObject_GetAttrString(space, space.wrap(""), charp2)
78 with raises_w(space, AttributeError):
79 PyObject_SetAttrString(space, space.wrap(""), charp1, None)
80 rffi.free_charp(charp1)
81 rffi.free_charp(charp2)
82
83 assert get_w_obj_and_decref(space,
84 PyObject_GetAttr(space, space.wrap(""), space.wrap("__len__")))
85 with raises_w(space, AttributeError):
86 PyObject_SetAttr(space, space.wrap(""), space.wrap("__len__"), None)
87
88 def test_getitem(self, space, api):
89 w_t = space.wrap((1, 2, 3, 4, 5))
90 assert space.unwrap(get_w_obj_and_decref(space,
91 api.PyObject_GetItem(w_t, space.wrap(3)))) == 4
92
93 w_d = space.newdict()
94 space.setitem(w_d, space.wrap("a key!"), space.wrap(72))
95 assert space.unwrap(get_w_obj_and_decref(space,
96 api.PyObject_GetItem(w_d, space.wrap("a key!")))) == 72
97
98 assert api.PyObject_SetItem(w_d, space.wrap("key"), space.w_None) == 0
99 assert space.getitem(w_d, space.wrap("key")) is space.w_None
100
101 assert api.PyObject_DelItem(w_d, space.wrap("key")) == 0
102 with raises_w(space, KeyError):
103 PyObject_GetItem(space, w_d, space.wrap("key"))
104
105 def test_size(self, space, api):
106 assert api.PyObject_Size(space.newlist([space.w_None])) == 1
107
108 def test_str(self, space, api):
109 w_list = space.newlist([space.w_None, space.wrap(42)])
110 assert space.text_w(api.PyObject_Str(None)) == "<NULL>"
111 assert space.text_w(api.PyObject_Str(w_list)) == "[None, 42]"
112 assert space.text_w(api.PyObject_Str(space.wrap("a"))) == "a"
113
114 def test_repr(self, space, api):
115 w_list = space.newlist([space.w_None, space.wrap(42)])
116 assert space.text_w(api.PyObject_Repr(None)) == "<NULL>"
117 assert space.text_w(api.PyObject_Repr(w_list)) == "[None, 42]"
118 assert space.text_w(api.PyObject_Repr(space.wrap("a"))) == "'a'"
119
120 def test_RichCompare(self, space, api):
121 def compare(w_o1, w_o2, opid):
122 res = api.PyObject_RichCompareBool(w_o1, w_o2, opid)
123 w_res = api.PyObject_RichCompare(w_o1, w_o2, opid)
124 assert space.is_true(w_res) == res
125 return res
126
127 def test_compare(o1, o2):
128 w_o1 = space.wrap(o1)
129 w_o2 = space.wrap(o2)
130
131 for opid, expected in [
132 (Py_LT, o1 < o2), (Py_LE, o1 <= o2),
133 (Py_NE, o1 != o2), (Py_EQ, o1 == o2),
134 (Py_GT, o1 > o2), (Py_GE, o1 >= o2)]:
135 assert compare(w_o1, w_o2, opid) == expected
136
137 test_compare(1, 2)
138 test_compare(2, 2)
139 test_compare('2', '1')
140
141 w_i = space.wrap(1)
142 with raises_w(space, SystemError):
143 api.PyObject_RichCompareBool(w_i, w_i, 123456)
144
145 def test_RichCompareNanlike(self, space,api):
146 w_obj = space.appexec([], """():
147 class Nanlike(object):
148 def __eq__(self, other):
149 raise RuntimeError('unreachable')
150 return Nanlike()""")
151 res = api.PyObject_RichCompareBool(w_obj, w_obj, Py_EQ)
152 assert res == 1
153 res = api.PyObject_RichCompareBool(w_obj, w_obj, Py_NE)
154 assert res == 0
155
156 def test_IsInstance(self, space, api):
157 assert api.PyObject_IsInstance(space.wrap(1), space.w_int) == 1
158 assert api.PyObject_IsInstance(space.wrap(1), space.w_float) == 0
159 assert api.PyObject_IsInstance(space.w_True, space.w_int) == 1
160 assert api.PyObject_IsInstance(
161 space.wrap(1), space.newtuple([space.w_int, space.w_float])) == 1
162 assert api.PyObject_IsInstance(space.w_type, space.w_type) == 1
163 with raises_w(space, TypeError):
164 PyObject_IsInstance(space, space.wrap(1), space.w_None)
165
166 def test_IsSubclass(self, space, api):
167 assert api.PyObject_IsSubclass(space.w_type, space.w_type) == 1
168 assert api.PyObject_IsSubclass(space.w_type, space.w_object) == 1
169 assert api.PyObject_IsSubclass(space.w_object, space.w_type) == 0
170 assert api.PyObject_IsSubclass(
171 space.w_type, space.newtuple([space.w_int, space.w_type])) == 1
172 with raises_w(space, TypeError):
173 PyObject_IsSubclass(space, space.wrap(1), space.w_type)
174
175 def test_fileno(self, space, api):
176 assert api.PyObject_AsFileDescriptor(space.wrap(1)) == 1
177 with raises_w(space, ValueError):
178 PyObject_AsFileDescriptor(space, space.wrap(-20))
179
180 w_File = space.appexec([], """():
181 class File:
182 def fileno(self):
183 return 42
184 return File""")
185 w_f = space.call_function(w_File)
186 assert api.PyObject_AsFileDescriptor(w_f) == 42
187
188 def test_hash(self, space, api):
189 assert api.PyObject_Hash(space.wrap(72)) == 72
190 assert api.PyObject_Hash(space.wrap(-1)) == -2
191 with raises_w(space, TypeError):
192 PyObject_Hash(space, space.wrap([]))
193
194 def test_hash_double(self, space, api):
195 from pypy.interpreter.typedef import default_identity_hash
196 assert api._Py_HashDouble(space.newfloat(72.0), 72.0) == 72
197 # for non-nans the object is ignored anyway
198 assert api._Py_HashDouble(space.newfloat(72.0), 123.0) == 123
199
200 w_F = space.appexec([], """():
201 class F(float):
202 def __hash__(self):
203 return 42
204 return F
205 """)
206 w_f = space.call_function(w_F, space.newfloat(72.0))
207 assert api._Py_HashDouble(w_f, 72.0) == 72
208 w_f = space.call_function(w_F, space.newfloat(float('nan')))
209 assert api._Py_HashDouble(w_f, float('nan')) == space.int_w(default_identity_hash(space, w_f))
210
211 def test_type(self, space, api):
212 assert api.PyObject_Type(space.wrap(72)) is space.w_int
213
214 def test_dir(self, space, api):
215 w_dir = api.PyObject_Dir(space.sys)
216 assert space.isinstance_w(w_dir, space.w_list)
217 assert space.contains_w(w_dir, space.wrap('modules'))
218
219 def test_format(self, space, api):
220 w_int = space.wrap(42)
221 fmt = space.text_w(api.PyObject_Format(w_int, space.wrap('#b')))
222 assert fmt == '0b101010'
223
224 class AppTestObject(AppTestCpythonExtensionBase):
225 def setup_class(cls):
226 from rpython.rlib import rgc
227 from pypy.interpreter import gateway
228
229 AppTestCpythonExtensionBase.setup_class.im_func(cls)
230 tmpname = str(pytest.ensuretemp('out', dir=0))
231 cls.w_tmpname = cls.space.wrap(tmpname)
232
233 if not cls.runappdirect:
234 cls.total_mem = 0
235 def add_memory_pressure(estimate, object=None):
236 assert estimate >= 0
237 cls.total_mem += estimate
238 cls.orig_add_memory_pressure = [rgc.add_memory_pressure]
239 rgc.add_memory_pressure = add_memory_pressure
240
241 def _reset_memory_pressure(space):
242 cls.total_mem = 0
243 cls.w_reset_memory_pressure = cls.space.wrap(
244 gateway.interp2app(_reset_memory_pressure))
245
246 def _cur_memory_pressure(space):
247 return space.newint(cls.total_mem)
248 cls.w_cur_memory_pressure = cls.space.wrap(
249 gateway.interp2app(_cur_memory_pressure))
250 else:
251 def _skip_test(*ignored):
252 skip("not for -A testing")
253 cls.w_reset_memory_pressure = _skip_test
254
255 def teardown_class(cls):
256 from rpython.rlib import rgc
257 if hasattr(cls, 'orig_add_memory_pressure'):
258 [rgc.add_memory_pressure] = cls.orig_add_memory_pressure
259
260 def test_object_malloc(self):
261 module = self.import_extension('foo', [
262 ("malloctest", "METH_NOARGS",
263 """
264 PyObject *obj = PyObject_MALLOC(sizeof(PyFloatObject));
265 obj = PyObject_Init(obj, &PyFloat_Type);
266 if (obj != NULL)
267 ((PyFloatObject *)obj)->ob_fval = -12.34;
268 return obj;
269 """)])
270 x = module.malloctest()
271 assert type(x) is float
272 assert x == -12.34
273
274 def test_object_calloc(self):
275 module = self.import_extension('foo', [
276 ("calloctest", "METH_NOARGS",
277 """
278 PyObject *obj = PyObject_Calloc(1, sizeof(PyFloatObject));
279 if (obj == NULL)
280 return NULL;
281 obj = PyObject_Init(obj, &PyFloat_Type);
282 return obj;
283 """)])
284 x = module.calloctest()
285 assert type(x) is float
286 assert x == 0.0
287
288 def test_object_realloc(self):
289 if not self.runappdirect:
290 skip('no untranslated support for realloc')
291 module = self.import_extension('foo', [
292 ("realloctest", "METH_NOARGS",
293 """
294 PyObject * ret;
295 char *copy, *orig = PyObject_MALLOC(12);
296 memcpy(orig, "hello world", 12);
297 copy = PyObject_REALLOC(orig, 15);
298 /* realloc() takes care of freeing orig, if changed */
299 if (copy == NULL)
300 Py_RETURN_NONE;
301 ret = PyBytes_FromStringAndSize(copy, 12);
302 PyObject_Free(copy);
303 return ret;
304 """)])
305 x = module.realloctest()
306 assert x == b'hello world\x00'
307
308 def test_TypeCheck(self):
309 module = self.import_extension('foo', [
310 ("typecheck", "METH_VARARGS",
311 """
312 PyObject *obj = PyTuple_GET_ITEM(args, 0);
313 PyTypeObject *type = (PyTypeObject *)PyTuple_GET_ITEM(args, 1);
314 return PyBool_FromLong(PyObject_TypeCheck(obj, type));
315 """)])
316 assert module.typecheck(1, int)
317 assert module.typecheck('foo', str)
318 assert module.typecheck('foo', object)
319 assert module.typecheck(True, bool)
320 assert module.typecheck(1.2, float)
321 assert module.typecheck(int, type)
322
323 def test_print(self):
324 module = self.import_extension('foo', [
325 ("dump", "METH_VARARGS",
326 """
327 PyObject *fname = PyTuple_GetItem(args, 0);
328 PyObject *obj = PyTuple_GetItem(args, 1);
329
330 FILE *fp = fopen(_PyUnicode_AsString(fname), "wb");
331 int ret;
332 if (fp == NULL)
333 Py_RETURN_NONE;
334 ret = PyObject_Print(obj, fp, Py_PRINT_RAW);
335 if (ret < 0) {
336 fclose(fp);
337 return NULL;
338 }
339 ret = PyObject_Print(NULL, fp, Py_PRINT_RAW);
340 if (ret < 0) {
341 fclose(fp);
342 return NULL;
343 }
344 fclose(fp);
345 Py_RETURN_TRUE;
346 """),
347 ("print_empty", "METH_O",
348 """
349 FILE *fp = fopen(_PyUnicode_AsString(args), "wb");
350 if (fp == NULL)
351 Py_RETURN_NONE;
352 PyObject *obj = PyUnicode_FromStringAndSize(NULL, 0);
353 int ret = PyObject_Print(obj, fp, 0);
354 fclose(fp);
355 if (ret < 0) {
356 return NULL;
357 }
358 Py_RETURN_TRUE;
359 """)])
360 assert module.dump(self.tmpname, None)
361 result = ''
362 with open(self.tmpname) as fid:
363 result = fid.read()
364 assert result == 'None<nil>'
365 assert module.print_empty(self.tmpname)
366 with open(self.tmpname) as fid:
367 result = fid.read()
368 # print("result=", result, len(result))
369 assert result == "''"
370
371 def test_isinstance(self):
372 module = self.import_extension('foo', [
373 ("ismapping", "METH_O",
374 """
375 PyObject* collections_mod =
376 PyImport_ImportModule("collections.abc");
377 if (collections_mod == NULL) {
378 return NULL;
379 }
380 PyObject* mapping_t = PyObject_GetAttrString(
381 collections_mod, "Mapping");
382 Py_DECREF(collections_mod);
383 if (mapping_t == NULL) {
384 return NULL;
385 }
386 if (PyObject_IsInstance(args, mapping_t)) {
387 Py_DECREF(mapping_t);
388 Py_RETURN_TRUE;
389 } else {
390 Py_DECREF(mapping_t);
391 Py_RETURN_FALSE;
392 }
393 """),
394 ("is_function", "METH_O",
395 """
396 if (PyObject_IsInstance(args, (PyObject *)&PyFunction_Type)) {
397 Py_RETURN_TRUE;
398 } else {
399 Py_RETURN_FALSE;
400 }
401 """),])
402 import collections.abc
403 assert isinstance(dict(), collections.abc.Mapping)
404 assert module.ismapping(dict())
405 def f():
406 pass
407 assert not module.is_function(1)
408 assert module.is_function(f)
409
410 def test_format_returns_unicode(self):
411 module = self.import_extension('foo', [
412 ("empty_format", "METH_O",
413 """
414 PyObject* empty_unicode = PyUnicode_FromStringAndSize("", 0);
415 PyObject* obj = PyObject_Format(args, empty_unicode);
416 return obj;
417 """)])
418 a = module.empty_format('hello')
419 assert isinstance(a, str)
420 a = module.empty_format(type('hello'))
421 assert isinstance(a, str)
422
423 def test_Bytes(self):
424 class sub1(bytes):
425 pass
426 class sub2(bytes):
427 def __bytes__(self):
428 return self
429 module = self.import_extension('test_Bytes', [
430 ('asbytes', 'METH_O',
431 """
432 return PyObject_Bytes(args);
433 """)])
434 assert type(module.asbytes(sub1(b''))) is bytes
435 assert type(module.asbytes(sub2(b''))) is sub2
436 assert module.asbytes(list(b"a")) == b"a"
437
438 def test_LengthHint(self):
439 import operator
440 class WithLen:
441 def __len__(self):
442 return 1
443 def __length_hint__(self):
444 return 42
445 class NoLen:
446 def __length_hint__(self):
447 return 2
448 module = self.import_extension('test_LengthHint', [
449 ('length_hint', 'METH_VARARGS',
450 """
451 PyObject *obj = PyTuple_GET_ITEM(args, 0);
452 Py_ssize_t i = PyLong_AsSsize_t(PyTuple_GET_ITEM(args, 1));
453 return PyLong_FromSsize_t(PyObject_LengthHint(obj, i));
454 """)])
455 assert module.length_hint(WithLen(), 5) == operator.length_hint(WithLen(), 5) == 1
456 assert module.length_hint(NoLen(), 5) == operator.length_hint(NoLen(), 5) == 2
457 assert module.length_hint(object(), 5) == operator.length_hint(object(), 5) == 5
458
459 def test_add_memory_pressure(self):
460 self.reset_memory_pressure() # for the potential skip
461 module = self.import_extension('foo', [
462 ("foo", "METH_O",
463 """
464 PyTraceMalloc_Track(0, 0, PyLong_AsLong(args) - sizeof(long));
465 Py_INCREF(Py_None);
466 return Py_None;
467 """)])
468 self.reset_memory_pressure()
469 module.foo(42)
470 assert self.cur_memory_pressure() == 0
471 module.foo(65000 - 42)
472 assert self.cur_memory_pressure() == 0
473 module.foo(536)
474 assert self.cur_memory_pressure() == 65536
475 module.foo(40000)
476 assert self.cur_memory_pressure() == 65536
477 module.foo(40000)
478 assert self.cur_memory_pressure() == 65536 + 80000
479 module.foo(35000)
480 assert self.cur_memory_pressure() == 65536 + 80000
481 module.foo(35000)
482 assert self.cur_memory_pressure() == 65536 + 80000 + 70000
483
484 def test_repr_enter_leave(self):
485 module = self.import_extension('foo', [
486 ("enter", "METH_O",
487 """
488 return PyLong_FromLong(Py_ReprEnter(args));
489 """),
490 ("leave", "METH_O",
491 """
492 Py_ReprLeave(args);
493 Py_INCREF(Py_None);
494 return Py_None;
495 """)])
496 obj1 = [42]
497 obj2 = [42] # another list
498
499 n = module.enter(obj1)
500 assert n == 0
501 module.leave(obj1)
502
503 n = module.enter(obj1)
504 assert n == 0
505 n = module.enter(obj1)
506 assert n == 1
507 n = module.enter(obj1)
508 assert n == 1
509 module.leave(obj1)
510
511 n = module.enter(obj1)
512 assert n == 0
513 n = module.enter(obj2)
514 assert n == 0
515 n = module.enter(obj1)
516 assert n == 1
517 n = module.enter(obj2)
518 assert n == 1
519 module.leave(obj1)
520 n = module.enter(obj2)
521 assert n == 1
522 module.leave(obj2)
523
524 def test_GenericGetSetDict(self):
525 module = self.import_extension('test_GenericGetSetDict', [
526 ('test1', 'METH_VARARGS',
527 """
528 PyObject *obj = PyTuple_GET_ITEM(args, 0);
529 PyObject *newdict = PyTuple_GET_ITEM(args, 1);
530
531 PyObject *olddict = PyObject_GenericGetDict(obj, NULL);
532 if (olddict == NULL)
533 return NULL;
534 int res = PyObject_GenericSetDict(obj, newdict, NULL);
535 if (res != 0)
536 return NULL;
537 return olddict;
538 """)])
539 class A:
540 pass
541 a = A()
542 a.x = 42
543 nd = {'y': 43}
544 d = module.test1(a, nd)
545 assert d == {'x': 42}
546 assert a.y == 43
547 assert a.__dict__ is nd
548
549 def test_Py_Is(self):
550 module = self.import_extension('foo', [
551 ('test_is', 'METH_VARARGS',
552 """
553 PyObject *obj1 = PyTuple_GET_ITEM(args, 0);
554 PyObject *obj2 = PyTuple_GET_ITEM(args, 1);
555 int res = Py_Is(obj1, obj2);
556 return PyLong_FromLong(res);
557 """)])
558 nan1 = float('nan')
559 nan2 = float('nan')
560 assert module.test_is(nan1, nan2)
561 a = 1
562 b = 1
563 assert module.test_is(a, b)
564 assert not module.test_is(a, nan1)
565
566 def test_SetAttrNull(self):
567 module = self.import_extension('foo', [
568 ('set_attr_null', 'METH_VARARGS',
569 """
570 PyObject *obj = PyTuple_GET_ITEM(args, 0);
571 PyObject *name = PyTuple_GET_ITEM(args, 1);
572 PyObject_SetAttr(obj, name, NULL);
573 Py_RETURN_TRUE;
574 """),
575 ('set_test_null', 'METH_O',
576 """
577 PyObject_SetAttrString(args, "test", NULL);
578 Py_RETURN_TRUE;
579 """),
580 ])
581 class A(object):
582 pass
583 a = A()
584 a.test = 20
585 module.set_attr_null(a, "test")
586 assert not hasattr(a, "test")
587 a.test = 20
588 module.set_test_null(a)
589 assert not hasattr(a, "test")
590
591 class AppTestPyBufferObject(AppTestCpythonExtensionBase):
592 """
593 PyBuffer_FillInfo populates the fields of a Py_buffer from its arguments.
594 """
595 def test_fillWithoutObject(self):
596 """
597 PyBuffer_FillInfo populates the C{buf} and C{length}fields of the
598 Py_buffer passed to it.
599 """
600 module = self.import_extension('foo', [
601 ("fillinfo", "METH_NOARGS",
602 """
603 Py_buffer buf;
604 PyObject *str = PyBytes_FromString("hello, world.");
605 PyObject *result;
606
607 if (PyBuffer_FillInfo(&buf, NULL, PyBytes_AsString(str), 13, 0, 0)) {
608 return NULL;
609 }
610
611 /* Check a few things we want to have happened.
612 */
613 if (buf.buf != PyBytes_AsString(str)) {
614 PyErr_SetString(PyExc_ValueError, "buf field not initialized");
615 return NULL;
616 }
617
618 if (buf.len != 13) {
619 PyErr_SetString(PyExc_ValueError, "len field not initialized");
620 return NULL;
621 }
622
623 if (buf.obj != NULL) {
624 PyErr_SetString(PyExc_ValueError, "obj field not initialized");
625 return NULL;
626 }
627
628 /* Give back a new string to the caller, constructed from data in the
629 * Py_buffer.
630 */
631 if (!(result = PyBytes_FromStringAndSize(buf.buf, buf.len))) {
632 return NULL;
633 }
634
635 /* Free that string we allocated above. result does not share storage with
636 * it.
637 */
638 Py_DECREF(str);
639
640 return result;
641 """)])
642 result = module.fillinfo()
643 assert b"hello, world." == result
644
645
646 def test_fillWithObject(self):
647 """
648 PyBuffer_FillInfo populates the C{buf}, C{length}, and C{obj} fields of
649 the Py_buffer passed to it and increments the reference count of the
650 object.
651 """
652 module = self.import_extension('foo', [
653 ("fillinfo", "METH_NOARGS",
654 """
655 Py_buffer buf;
656 PyObject *str = PyBytes_FromString("hello, world.");
657 PyObject *result;
658
659 if (PyBuffer_FillInfo(&buf, str, PyBytes_AsString(str), 13, 0, 0)) {
660 return NULL;
661 }
662
663 /* Get rid of our own reference to the object, but the Py_buffer should
664 * still have a reference.
665 */
666 Py_DECREF(str);
667
668 /* Give back a new string to the caller, constructed from data in the
669 * Py_buffer. It better still be valid.
670 */
671 if (!(result = PyBytes_FromStringAndSize(buf.buf, buf.len))) {
672 return NULL;
673 }
674
675 /* Now the data in the Py_buffer is really no longer needed, get rid of it
676 *(could use PyBuffer_Release here, but that would drag in more code than
677 * necessary).
678 */
679 Py_DECREF(buf.obj);
680
681 /* Py_DECREF can't directly signal error to us, but if it makes a reference
682 * count go negative, it will set an error.
683 */
684 if (PyErr_Occurred()) {
685 return NULL;
686 }
687
688 return result;
689 """)])
690 result = module.fillinfo()
691 assert b"hello, world." == result
692
693
694 def test_fillReadonly(self):
695 """
696 PyBuffer_FillInfo fails if WRITABLE is passed but object is readonly.
697 """
698 module = self.import_extension('foo', [
699 ("fillinfo", "METH_NOARGS",
700 """
701 Py_buffer buf;
702 PyObject *str = PyBytes_FromString("hello, world.");
703
704 if (PyBuffer_FillInfo(&buf, str, PyBytes_AsString(str), 13,
705 1, PyBUF_WRITABLE)) {
706 Py_DECREF(str);
707 return NULL;
708 }
709 Py_DECREF(str);
710 PyBuffer_Release(&buf);
711 Py_RETURN_NONE;
712 """)])
713 raises((BufferError, ValueError), module.fillinfo)
714
715
716 def test_decrefObject(self):
717 """
718 The PyObject referenced by Py_buffer.obj has its reference count
719 decremented by PyBuffer_Release.
720 """
721 module = self.import_extension('foo', [
722 ("release", "METH_NOARGS",
723 """
724 Py_buffer buf;
725 buf.obj = PyBytes_FromString("release me!");
726 buf.buf = PyBytes_AsString(buf.obj);
727 buf.len = PyBytes_Size(buf.obj);
728
729 /* The Py_buffer owns the only reference to that string. Release the
730 * Py_buffer and the string should be released as well.
731 */
732 PyBuffer_Release(&buf);
733 assert(!buf.obj);
734 PyBuffer_Release(&buf); /* call again, should not have any more effect */
735 PyBuffer_Release(&buf);
736 PyBuffer_Release(&buf);
737
738 Py_RETURN_NONE;
739 """)])
740 assert module.release() is None
741
742
743 def test_richcomp_nan(self):
744 module = self.import_extension('foo', [
745 ("comp_eq", "METH_VARARGS",
746 """
747 PyObject *a = PyTuple_GetItem(args, 0);
748 PyObject *b = PyTuple_GetItem(args, 1);
749 int res = PyObject_RichCompareBool(a, b, Py_EQ);
750 return PyLong_FromLong(res);
751 """),])
752 a = float('nan')
753 b = float('nan')
754 assert a is b
755 res = module.comp_eq(a, b)
756 assert res == 1