|
| 1 | +from tests.cpyext import CPyExtType, CPyExtHeapType, assert_raises |
| 2 | + |
| 3 | +NativeTypeWithoutDict = CPyExtType( |
| 4 | + name='NativeTypeWithoutDict', |
| 5 | +) |
| 6 | + |
| 7 | +NativeTypeWithDict = CPyExtType( |
| 8 | + name='NativeTypeWithDict', |
| 9 | + cmembers='PyObject* dict;', |
| 10 | + tp_dictoffset='offsetof(NativeTypeWithDictObject, dict)', |
| 11 | + tp_getset='{"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict}', |
| 12 | +) |
| 13 | + |
| 14 | +NativeHeapTypeWithoutDict = CPyExtHeapType( |
| 15 | + name='NativeTypeWithManagedDict', |
| 16 | +) |
| 17 | + |
| 18 | +NativeHeapTypeWithDict = CPyExtHeapType( |
| 19 | + name='NativeHeapTypeWithManagedDict', |
| 20 | + cmembers='PyObject* dict;', |
| 21 | + code=''' |
| 22 | + static PyMemberDef memberlist[] = { |
| 23 | + {"__dictoffset__", T_PYSSIZET, offsetof(NativeHeapTypeWithManagedDictObject, dict), READONLY}, |
| 24 | + {NULL} |
| 25 | + }; |
| 26 | + static PyGetSetDef getsetlist[] = { |
| 27 | + {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict}, |
| 28 | + {NULL} |
| 29 | + }; |
| 30 | + ''', |
| 31 | + slots=[ |
| 32 | + '{Py_tp_members, memberlist}', |
| 33 | + '{Py_tp_getset, getsetlist}', |
| 34 | + ], |
| 35 | +) |
| 36 | + |
| 37 | + |
| 38 | +# TODO it would be great if we could test creating heap types with Py_TPFLAGS_MANAGED_DICT, because pybind11 does that, |
| 39 | +# but there's no way to do that without abusing abusing implementations details |
| 40 | + |
| 41 | + |
| 42 | +class NativeSubtypeWithDict(NativeTypeWithDict): |
| 43 | + pass |
| 44 | + |
| 45 | + |
| 46 | +class NativeSubtypeWithAddedDict(NativeTypeWithoutDict): |
| 47 | + pass |
| 48 | + |
| 49 | + |
| 50 | +class TestObjectDict: |
| 51 | + @staticmethod |
| 52 | + def assert_has_no_dict(obj): |
| 53 | + assert_raises(AttributeError, setattr, obj, 'foo', 1) |
| 54 | + assert_raises(AttributeError, getattr, obj, '__dict__') |
| 55 | + |
| 56 | + @staticmethod |
| 57 | + def assert_has_working_dict(obj): |
| 58 | + obj.foo = 1 |
| 59 | + assert obj.foo == 1 |
| 60 | + assert obj.__dict__ == {'foo': 1} |
| 61 | + |
| 62 | + def test_no_dict(self): |
| 63 | + self.assert_has_no_dict(NativeTypeWithoutDict()) |
| 64 | + self.assert_has_no_dict(NativeHeapTypeWithoutDict()) |
| 65 | + |
| 66 | + def test_dict(self): |
| 67 | + self.assert_has_working_dict(NativeTypeWithDict()) |
| 68 | + self.assert_has_working_dict(NativeHeapTypeWithDict()) |
| 69 | + self.assert_has_working_dict(NativeSubtypeWithDict()) |
| 70 | + self.assert_has_working_dict(NativeSubtypeWithAddedDict()) |
0 commit comments