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