| 1 | from rpython.rtyper.lltypesystem import rffi, lltype |
| 2 | from pypy.module.cpyext.test.test_api import BaseApiTest |
| 3 | from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase |
| 4 | from pypy.module.cpyext.api import PyObject |
| 5 | |
| 6 | class AppTestStructSeq(AppTestCpythonExtensionBase): |
| 7 | def test_StructSeq(self): |
| 8 | module = self.import_extension('foo', |
| 9 | prologue=""" |
| 10 | #include <structseq.h> |
| 11 | static PyTypeObject* PyDatatype; |
| 12 | |
| 13 | static PyStructSequence_Field Data_fields[] = { |
| 14 | {"value", "value_doc"}, |
| 15 | {"value2", "value_doc"}, |
| 16 | {"text", "text_doc"}, |
| 17 | {"other", "other_doc"}, |
| 18 | {NULL} /* Sentinel */ |
| 19 | }; |
| 20 | static PyStructSequence_Desc Data_desc = { |
| 21 | "cpyext_test.data", /*name*/ |
| 22 | "data_doc", /*doc*/ |
| 23 | Data_fields, /*fields*/ |
| 24 | 3, /*n_in_sequence*/ |
| 25 | }; |
| 26 | """, more_init = """ |
| 27 | """, |
| 28 | functions=[ |
| 29 | ("new_structdata", "METH_NOARGS", |
| 30 | """ |
| 31 | PyObject *seq; |
| 32 | PyDatatype = PyStructSequence_NewType(&Data_desc); |
| 33 | seq = PyStructSequence_New(PyDatatype); |
| 34 | if (!seq) return NULL; |
| 35 | PyStructSequence_SET_ITEM(seq, 0, PyLong_FromLong(42)); |
| 36 | PyStructSequence_SET_ITEM(seq, 1, PyLong_FromLong(43)); |
| 37 | PyStructSequence_SetItem(seq, 2, PyUnicode_FromString("hello")); |
| 38 | PyStructSequence_SetItem(seq, 3, PyUnicode_FromString("other")); |
| 39 | Py_DECREF(PyDatatype); |
| 40 | return seq; |
| 41 | """), |
| 42 | ("getitem", "METH_VARARGS", |
| 43 | """ |
| 44 | PyObject *obj, *result=NULL; |
| 45 | int i; |
| 46 | if (PyArg_ParseTuple(args, "Oi:test_get_item", &obj, &i)) { |
| 47 | result = PyStructSequence_GetItem(obj, i); |
| 48 | Py_INCREF(result); |
| 49 | }; |
| 50 | return result; |
| 51 | """), |
| 52 | ]) |
| 53 | s = module.new_structdata() |
| 54 | assert tuple(s) == (42, 43, 'hello') |
| 55 | assert s.value == 42 |
| 56 | assert s.text == 'hello' |
| 57 | assert s.other == 'other' |
| 58 | assert 'hello' in s |
| 59 | assert 'other' not in s |
| 60 | assert module.getitem(s, 1) == 43 |
| 61 | del s |
| 62 |