Debian Codegraph @

lib-python/3/ctypes/test/test_internals.py

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