| 1 |
import py |
| 2 |
from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase |
| 3 |
from pypy.module.cpyext.test.test_api import BaseApiTest |
| 4 |
from pypy.module.cpyext.pyobject import make_ref |
| 5 |
|
| 6 |
|
| 7 |
class AppTestBorrow(AppTestCpythonExtensionBase): |
| 8 |
def test_tuple_borrowing(self): |
| 9 |
module = self.import_extension('foo', [ |
| 10 |
("test_borrowing", "METH_NOARGS", |
| 11 |
""" |
| 12 |
PyObject *t = PyTuple_New(1); |
| 13 |
if (t == NULL) { |
| 14 |
return NULL; |
| 15 |
} |
| 16 |
PyObject *f = PyFloat_FromDouble(42.0); |
| 17 |
PyObject *g = NULL; |
| 18 |
printf("Refcnt1: %ld\\n", f->ob_refcnt); |
| 19 |
PyTuple_SetItem(t, 0, f); // steals reference |
| 20 |
printf("Refcnt2: %ld\\n", f->ob_refcnt); |
| 21 |
f = PyTuple_GetItem(t, 0); // borrows reference |
| 22 |
printf("Refcnt3: %ld\\n", f->ob_refcnt); |
| 23 |
g = PyTuple_GetItem(t, 0); // borrows reference again |
| 24 |
printf("Refcnt4: %ld\\n", f->ob_refcnt); |
| 25 |
printf("COMPARE: %i\\n", f == g); |
| 26 |
fflush(stdout); |
| 27 |
Py_DECREF(t); |
| 28 |
Py_RETURN_TRUE; |
| 29 |
"""), |
| 30 |
]) |
| 31 |
assert module.test_borrowing() |
| 32 |
|
| 33 |
def test_borrow_destroy(self): |
| 34 |
module = self.import_extension('foo', [ |
| 35 |
("test_borrow_destroy", "METH_NOARGS", |
| 36 |
""" |
| 37 |
PyObject *i = PyLong_FromLong(42); |
| 38 |
PyObject *j; |
| 39 |
PyObject *t1 = PyTuple_Pack(1, i); |
| 40 |
if (t1 == NULL) { |
| 41 |
return NULL; |
| 42 |
} |
| 43 |
PyObject *t2 = PyTuple_Pack(1, i); |
| 44 |
if (t2 == NULL) { |
| 45 |
return NULL; |
| 46 |
} |
| 47 |
Py_DECREF(i); |
| 48 |
|
| 49 |
i = PyTuple_GetItem(t1, 0); |
| 50 |
PyTuple_GetItem(t2, 0); |
| 51 |
Py_DECREF(t2); |
| 52 |
|
| 53 |
j = PyLong_FromLong(PyLong_AsLong(i)); |
| 54 |
Py_DECREF(t1); |
| 55 |
return j; |
| 56 |
"""), |
| 57 |
]) |
| 58 |
assert module.test_borrow_destroy() == 42 |
| 59 |
|
| 60 |
def test_double_borrow(self): |
| 61 |
module = self.import_extension('foo', [ |
| 62 |
("run", "METH_NOARGS", |
| 63 |
""" |
| 64 |
PyObject *t = PyTuple_New(1); |
| 65 |
PyObject *s = PyRun_String("set()", Py_eval_input, |
| 66 |
Py_None, Py_None); |
| 67 |
PyObject *w = PyWeakref_NewRef(s, Py_None); |
| 68 |
PyTuple_SetItem(t, 0, s); |
| 69 |
PyTuple_GetItem(t, 0); |
| 70 |
PyTuple_GetItem(t, 0); |
| 71 |
Py_DECREF(t); |
| 72 |
return w; |
| 73 |
"""), |
| 74 |
]) |
| 75 |
wr = module.run() |
| 76 |
|
| 77 |
self.debug_collect() |
| 78 |
assert wr() is None |