Debian Codegraph @

Lib/test/test_ctypes/test_keeprefs.py

raw
1 import unittest
2 from ctypes import (Structure, POINTER, pointer, _pointer_type_cache,
3 c_char_p, c_int)
4
5
6 class SimpleTestCase(unittest.TestCase):
7 def test_cint(self):
8 x = c_int()
9 self.assertEqual(x._objects, None)
10 x.value = 42
11 self.assertEqual(x._objects, None)
12 x = c_int(99)
13 self.assertEqual(x._objects, None)
14
15 def test_ccharp(self):
16 x = c_char_p()
17 self.assertEqual(x._objects, None)
18 x.value = b"abc"
19 self.assertEqual(x._objects, b"abc")
20 x = c_char_p(b"spam")
21 self.assertEqual(x._objects, b"spam")
22
23
24 class StructureTestCase(unittest.TestCase):
25 def test_cint_struct(self):
26 class X(Structure):
27 _fields_ = [("a", c_int),
28 ("b", c_int)]
29
30 x = X()
31 self.assertEqual(x._objects, None)
32 x.a = 42
33 x.b = 99
34 self.assertEqual(x._objects, None)
35
36 def test_ccharp_struct(self):
37 class X(Structure):
38 _fields_ = [("a", c_char_p),
39 ("b", c_char_p)]
40 x = X()
41 self.assertEqual(x._objects, None)
42
43 x.a = b"spam"
44 x.b = b"foo"
45 self.assertEqual(x._objects, {"0": b"spam", "1": b"foo"})
46
47 def test_struct_struct(self):
48 class POINT(Structure):
49 _fields_ = [("x", c_int), ("y", c_int)]
50 class RECT(Structure):
51 _fields_ = [("ul", POINT), ("lr", POINT)]
52
53 r = RECT()
54 r.ul.x = 0
55 r.ul.y = 1
56 r.lr.x = 2
57 r.lr.y = 3
58 self.assertEqual(r._objects, None)
59
60 r = RECT()
61 pt = POINT(1, 2)
62 r.ul = pt
63 self.assertEqual(r._objects, {'0': {}})
64 r.ul.x = 22
65 r.ul.y = 44
66 self.assertEqual(r._objects, {'0': {}})
67 r.lr = POINT()
68 self.assertEqual(r._objects, {'0': {}, '1': {}})
69
70
71 class ArrayTestCase(unittest.TestCase):
72 def test_cint_array(self):
73 INTARR = c_int * 3
74
75 ia = INTARR()
76 self.assertEqual(ia._objects, None)
77 ia[0] = 1
78 ia[1] = 2
79 ia[2] = 3
80 self.assertEqual(ia._objects, None)
81
82 class X(Structure):
83 _fields_ = [("x", c_int),
84 ("a", INTARR)]
85
86 x = X()
87 x.x = 1000
88 x.a[0] = 42
89 x.a[1] = 96
90 self.assertEqual(x._objects, None)
91 x.a = ia
92 self.assertEqual(x._objects, {'1': {}})
93
94
95 class PointerTestCase(unittest.TestCase):
96 def test_p_cint(self):
97 i = c_int(42)
98 x = pointer(i)
99 self.assertEqual(x._objects, {'1': i})
100
101
102 class PointerToStructure(unittest.TestCase):
103 def test(self):
104 class POINT(Structure):
105 _fields_ = [("x", c_int), ("y", c_int)]
106 class RECT(Structure):
107 _fields_ = [("a", POINTER(POINT)),
108 ("b", POINTER(POINT))]
109 r = RECT()
110 p1 = POINT(1, 2)
111
112 r.a = pointer(p1)
113 r.b = pointer(p1)
114
115 r.a[0].x = 42
116 r.a[0].y = 99
117
118 # to avoid leaking when tests are run several times
119 # clean up the types left in the cache.
120 del _pointer_type_cache[POINT]
121
122
123 if __name__ == "__main__":
124 unittest.main()