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