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

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

#countcontent
1n/a# This tests the internal _objects attribute
2n/aimport unittest
3n/afrom ctypes import *
4n/afrom sys import getrefcount as grc
5n/a
6n/a# XXX This test must be reviewed for correctness!!!
7n/a
8n/a# ctypes' types are container types.
9n/a#
10n/a# They have an internal memory block, which only consists of some bytes,
11n/a# but it has to keep references to other objects as well. This is not
12n/a# really needed for trivial C types like int or char, but it is important
13n/a# for aggregate types like strings or pointers in particular.
14n/a#
15n/a# What about pointers?
16n/a
17n/aclass ObjectsTestCase(unittest.TestCase):
18n/a def assertSame(self, a, b):
19n/a self.assertEqual(id(a), id(b))
20n/a
21n/a def test_ints(self):
22n/a i = 42000123
23n/a refcnt = grc(i)
24n/a ci = c_int(i)
25n/a self.assertEqual(refcnt, grc(i))
26n/a self.assertEqual(ci._objects, None)
27n/a
28n/a def test_c_char_p(self):
29n/a s = b"Hello, World"
30n/a refcnt = grc(s)
31n/a cs = c_char_p(s)
32n/a self.assertEqual(refcnt + 1, grc(s))
33n/a self.assertSame(cs._objects, s)
34n/a
35n/a def test_simple_struct(self):
36n/a class X(Structure):
37n/a _fields_ = [("a", c_int), ("b", c_int)]
38n/a
39n/a a = 421234
40n/a b = 421235
41n/a x = X()
42n/a self.assertEqual(x._objects, None)
43n/a x.a = a
44n/a x.b = b
45n/a self.assertEqual(x._objects, None)
46n/a
47n/a def test_embedded_structs(self):
48n/a class X(Structure):
49n/a _fields_ = [("a", c_int), ("b", c_int)]
50n/a
51n/a class Y(Structure):
52n/a _fields_ = [("x", X), ("y", X)]
53n/a
54n/a y = Y()
55n/a self.assertEqual(y._objects, None)
56n/a
57n/a x1, x2 = X(), X()
58n/a y.x, y.y = x1, x2
59n/a self.assertEqual(y._objects, {"0": {}, "1": {}})
60n/a x1.a, x2.b = 42, 93
61n/a self.assertEqual(y._objects, {"0": {}, "1": {}})
62n/a
63n/a def test_xxx(self):
64n/a class X(Structure):
65n/a _fields_ = [("a", c_char_p), ("b", c_char_p)]
66n/a
67n/a class Y(Structure):
68n/a _fields_ = [("x", X), ("y", X)]
69n/a
70n/a s1 = b"Hello, World"
71n/a s2 = b"Hallo, Welt"
72n/a
73n/a x = X()
74n/a x.a = s1
75n/a x.b = s2
76n/a self.assertEqual(x._objects, {"0": s1, "1": s2})
77n/a
78n/a y = Y()
79n/a y.x = x
80n/a self.assertEqual(y._objects, {"0": {"0": s1, "1": s2}})
81n/a## x = y.x
82n/a## del y
83n/a## print x._b_base_._objects
84n/a
85n/a def test_ptr_struct(self):
86n/a class X(Structure):
87n/a _fields_ = [("data", POINTER(c_int))]
88n/a
89n/a A = c_int*4
90n/a a = A(11, 22, 33, 44)
91n/a self.assertEqual(a._objects, None)
92n/a
93n/a x = X()
94n/a x.data = a
95n/a##XXX print x._objects
96n/a##XXX print x.data[0]
97n/a##XXX print x.data._objects
98n/a
99n/aif __name__ == '__main__':
100n/a unittest.main()