Debian Codegraph @

Lib/test/test_ctypes/test_arrays.py

raw
1 import ctypes
2 import sys
3 import unittest
4 from ctypes import (Structure, Array, ARRAY, sizeof, addressof,
5 create_string_buffer, create_unicode_buffer,
6 c_char, c_wchar, c_byte, c_ubyte, c_short, c_ushort, c_int, c_uint,
7 c_long, c_ulonglong, c_float, c_double, c_longdouble)
8 from test.support import bigmemtest, _2G, threading_helper, Py_GIL_DISABLED
9 from ._support import (_CData, PyCArrayType, Py_TPFLAGS_DISALLOW_INSTANTIATION,
10 Py_TPFLAGS_IMMUTABLETYPE)
11
12
13 formats = "bBhHiIlLqQfd"
14
15 formats = c_byte, c_ubyte, c_short, c_ushort, c_int, c_uint, \
16 c_long, c_ulonglong, c_float, c_double, c_longdouble
17
18
19 class ArrayTestCase(unittest.TestCase):
20 def test_inheritance_hierarchy(self):
21 self.assertEqual(Array.mro(), [Array, _CData, object])
22
23 self.assertEqual(PyCArrayType.__name__, "PyCArrayType")
24 self.assertEqual(type(PyCArrayType), type)
25
26 def test_type_flags(self):
27 for cls in Array, PyCArrayType:
28 with self.subTest(cls=cls):
29 self.assertTrue(cls.__flags__ & Py_TPFLAGS_IMMUTABLETYPE)
30 self.assertFalse(cls.__flags__ & Py_TPFLAGS_DISALLOW_INSTANTIATION)
31
32 def test_metaclass_details(self):
33 # Abstract classes (whose metaclass __init__ was not called) can't be
34 # instantiated directly
35 NewArray = PyCArrayType.__new__(PyCArrayType, 'NewArray', (Array,), {})
36 for cls in Array, NewArray:
37 with self.subTest(cls=cls):
38 with self.assertRaisesRegex(TypeError, "abstract class"):
39 obj = cls()
40
41 # Cannot call the metaclass __init__ more than once
42 class T(Array):
43 _type_ = c_int
44 _length_ = 13
45 with self.assertRaisesRegex(SystemError, "already initialized"):
46 PyCArrayType.__init__(T, 'ptr', (), {})
47
48 def test_simple(self):
49 # create classes holding simple numeric types, and check
50 # various properties.
51
52 init = list(range(15, 25))
53
54 for fmt in formats:
55 alen = len(init)
56 int_array = ARRAY(fmt, alen)
57
58 ia = int_array(*init)
59 # length of instance ok?
60 self.assertEqual(len(ia), alen)
61
62 # slot values ok?
63 values = [ia[i] for i in range(alen)]
64 self.assertEqual(values, init)
65
66 # out-of-bounds accesses should be caught
67 with self.assertRaises(IndexError): ia[alen]
68 with self.assertRaises(IndexError): ia[-alen-1]
69
70 # change the items
71 new_values = list(range(42, 42+alen))
72 for n in range(alen):
73 ia[n] = new_values[n]
74 values = [ia[i] for i in range(alen)]
75 self.assertEqual(values, new_values)
76
77 # are the items initialized to 0?
78 ia = int_array()
79 values = [ia[i] for i in range(alen)]
80 self.assertEqual(values, [0] * alen)
81
82 # Too many initializers should be caught
83 self.assertRaises(IndexError, int_array, *range(alen*2))
84
85 CharArray = ARRAY(c_char, 3)
86
87 ca = CharArray(b"a", b"b", b"c")
88
89 # Should this work? It doesn't:
90 # CharArray("abc")
91 self.assertRaises(TypeError, CharArray, "abc")
92
93 self.assertEqual(ca[0], b"a")
94 self.assertEqual(ca[1], b"b")
95 self.assertEqual(ca[2], b"c")
96 self.assertEqual(ca[-3], b"a")
97 self.assertEqual(ca[-2], b"b")
98 self.assertEqual(ca[-1], b"c")
99
100 self.assertEqual(len(ca), 3)
101
102 # cannot delete items
103 with self.assertRaises(TypeError):
104 del ca[0]
105
106 def test_step_overflow(self):
107 a = (c_int * 5)()
108 a[3::sys.maxsize] = (1,)
109 self.assertListEqual(a[3::sys.maxsize], [1])
110 a = (c_char * 5)()
111 a[3::sys.maxsize] = b"A"
112 self.assertEqual(a[3::sys.maxsize], b"A")
113 a = (c_wchar * 5)()
114 a[3::sys.maxsize] = u"X"
115 self.assertEqual(a[3::sys.maxsize], u"X")
116
117 def test_numeric_arrays(self):
118
119 alen = 5
120
121 numarray = ARRAY(c_int, alen)
122
123 na = numarray()
124 values = [na[i] for i in range(alen)]
125 self.assertEqual(values, [0] * alen)
126
127 na = numarray(*[c_int()] * alen)
128 values = [na[i] for i in range(alen)]
129 self.assertEqual(values, [0]*alen)
130
131 na = numarray(1, 2, 3, 4, 5)
132 values = [i for i in na]
133 self.assertEqual(values, [1, 2, 3, 4, 5])
134
135 na = numarray(*map(c_int, (1, 2, 3, 4, 5)))
136 values = [i for i in na]
137 self.assertEqual(values, [1, 2, 3, 4, 5])
138
139 def test_classcache(self):
140 self.assertIsNot(ARRAY(c_int, 3), ARRAY(c_int, 4))
141 self.assertIs(ARRAY(c_int, 3), ARRAY(c_int, 3))
142
143 def test_from_address(self):
144 # Failed with 0.9.8, reported by JUrner
145 p = create_string_buffer(b"foo")
146 sz = (c_char * 3).from_address(addressof(p))
147 self.assertEqual(sz[:], b"foo")
148 self.assertEqual(sz[::], b"foo")
149 self.assertEqual(sz[::-1], b"oof")
150 self.assertEqual(sz[::3], b"f")
151 self.assertEqual(sz[1:4:2], b"o")
152 self.assertEqual(sz.value, b"foo")
153
154 def test_from_addressW(self):
155 p = create_unicode_buffer("foo")
156 sz = (c_wchar * 3).from_address(addressof(p))
157 self.assertEqual(sz[:], "foo")
158 self.assertEqual(sz[::], "foo")
159 self.assertEqual(sz[::-1], "oof")
160 self.assertEqual(sz[::3], "f")
161 self.assertEqual(sz[1:4:2], "o")
162 self.assertEqual(sz.value, "foo")
163
164 def test_cache(self):
165 # Array types are cached internally in the _ctypes extension,
166 # in a WeakValueDictionary. Make sure the array type is
167 # removed from the cache when the itemtype goes away. This
168 # test will not fail, but will show a leak in the testsuite.
169
170 # Create a new type:
171 class my_int(c_int):
172 pass
173 # Create a new array type based on it:
174 t1 = my_int * 1
175 t2 = my_int * 1
176 self.assertIs(t1, t2)
177
178 def test_subclass(self):
179 class T(Array):
180 _type_ = c_int
181 _length_ = 13
182 class U(T):
183 pass
184 class V(U):
185 pass
186 class W(V):
187 pass
188 class X(T):
189 _type_ = c_short
190 class Y(T):
191 _length_ = 187
192
193 for c in [T, U, V, W]:
194 self.assertEqual(c._type_, c_int)
195 self.assertEqual(c._length_, 13)
196 self.assertEqual(c()._type_, c_int)
197 self.assertEqual(c()._length_, 13)
198
199 self.assertEqual(X._type_, c_short)
200 self.assertEqual(X._length_, 13)
201 self.assertEqual(X()._type_, c_short)
202 self.assertEqual(X()._length_, 13)
203
204 self.assertEqual(Y._type_, c_int)
205 self.assertEqual(Y._length_, 187)
206 self.assertEqual(Y()._type_, c_int)
207 self.assertEqual(Y()._length_, 187)
208
209 def test_bad_subclass(self):
210 with self.assertRaises(AttributeError):
211 class T(Array):
212 pass
213 with self.assertRaises(AttributeError):
214 class T2(Array):
215 _type_ = c_int
216 with self.assertRaises(AttributeError):
217 class T3(Array):
218 _length_ = 13
219
220 def test_bad_length(self):
221 with self.assertRaises(ValueError):
222 class T(Array):
223 _type_ = c_int
224 _length_ = - sys.maxsize * 2
225 with self.assertRaises(ValueError):
226 class T2(Array):
227 _type_ = c_int
228 _length_ = -1
229 with self.assertRaises(TypeError):
230 class T3(Array):
231 _type_ = c_int
232 _length_ = 1.87
233 with self.assertRaises(OverflowError):
234 class T4(Array):
235 _type_ = c_int
236 _length_ = sys.maxsize * 2
237
238 def test_zero_length(self):
239 # _length_ can be zero.
240 class T(Array):
241 _type_ = c_int
242 _length_ = 0
243
244 def test_empty_element_struct(self):
245 class EmptyStruct(Structure):
246 _fields_ = []
247
248 obj = (EmptyStruct * 2)() # bpo37188: Floating-point exception
249 self.assertEqual(sizeof(obj), 0)
250
251 def test_empty_element_array(self):
252 class EmptyArray(Array):
253 _type_ = c_int
254 _length_ = 0
255
256 obj = (EmptyArray * 2)() # bpo37188: Floating-point exception
257 self.assertEqual(sizeof(obj), 0)
258
259 def test_bpo36504_signed_int_overflow(self):
260 # The overflow check in PyCArrayType_new() could cause signed integer
261 # overflow.
262 with self.assertRaises(OverflowError):
263 c_char * sys.maxsize * 2
264
265 @unittest.skipUnless(sys.maxsize > 2**32, 'requires 64bit platform')
266 @bigmemtest(size=_2G, memuse=1, dry_run=False)
267 def test_large_array(self, size):
268 c_char * size
269
270 @threading_helper.requires_working_threading()
271 @unittest.skipUnless(Py_GIL_DISABLED, "only meaningful if the GIL is disabled")
272 def test_thread_safety(self):
273 from threading import Thread
274
275 buffer = (ctypes.c_char_p * 10)()
276
277 def run():
278 for i in range(100):
279 buffer.value = b"hello"
280 buffer[0] = b"j"
281
282 with threading_helper.catch_threading_exception() as cm:
283 threads = (Thread(target=run) for _ in range(25))
284 with threading_helper.start_threads(threads):
285 pass
286
287 if cm.exc_value:
288 raise cm.exc_value
289
290
291 if __name__ == '__main__':
292 unittest.main()