ยปCore Development>Code coverage>Lib/ctypes/test/test_objects.py

Python code coverage for Lib/ctypes/test/test_objects.py

#countcontent
1n/ar'''
2n/aThis tests the '_objects' attribute of ctypes instances. '_objects'
3n/aholds references to objects that must be kept alive as long as the
4n/actypes instance, to make sure that the memory buffer is valid.
5n/a
6n/aWARNING: The '_objects' attribute is exposed ONLY for debugging ctypes itself,
7n/ait MUST NEVER BE MODIFIED!
8n/a
9n/a'_objects' is initialized to a dictionary on first use, before that it
10n/ais None.
11n/a
12n/aHere is an array of string pointers:
13n/a
14n/a>>> from ctypes import *
15n/a>>> array = (c_char_p * 5)()
16n/a>>> print(array._objects)
17n/aNone
18n/a>>>
19n/a
20n/aThe memory block stores pointers to strings, and the strings itself
21n/aassigned from Python must be kept.
22n/a
23n/a>>> array[4] = b'foo bar'
24n/a>>> array._objects
25n/a{'4': b'foo bar'}
26n/a>>> array[4]
27n/ab'foo bar'
28n/a>>>
29n/a
30n/aIt gets more complicated when the ctypes instance itself is contained
31n/ain a 'base' object.
32n/a
33n/a>>> class X(Structure):
34n/a... _fields_ = [("x", c_int), ("y", c_int), ("array", c_char_p * 5)]
35n/a...
36n/a>>> x = X()
37n/a>>> print(x._objects)
38n/aNone
39n/a>>>
40n/a
41n/aThe'array' attribute of the 'x' object shares part of the memory buffer
42n/aof 'x' ('_b_base_' is either None, or the root object owning the memory block):
43n/a
44n/a>>> print(x.array._b_base_) # doctest: +ELLIPSIS
45n/a<ctypes.test.test_objects.X object at 0x...>
46n/a>>>
47n/a
48n/a>>> x.array[0] = b'spam spam spam'
49n/a>>> x._objects
50n/a{'0:2': b'spam spam spam'}
51n/a>>> x.array._b_base_._objects
52n/a{'0:2': b'spam spam spam'}
53n/a>>>
54n/a
55n/a'''
56n/a
57n/aimport unittest, doctest
58n/a
59n/aimport ctypes.test.test_objects
60n/a
61n/aclass TestCase(unittest.TestCase):
62n/a def test(self):
63n/a failures, tests = doctest.testmod(ctypes.test.test_objects)
64n/a self.assertFalse(failures, 'doctests failed, see output above')
65n/a
66n/aif __name__ == '__main__':
67n/a doctest.testmod(ctypes.test.test_objects)