Debian Codegraph @

Lib/test/test_ctypes/test_structures.py

raw
1 from platform import architecture as _architecture
2 import struct
3 import sys
4 import unittest
5 from ctypes import (CDLL, Array, Structure, Union, POINTER, sizeof, byref, alignment,
6 c_void_p, c_char, c_wchar, c_byte, c_ubyte,
7 c_uint8, c_uint16, c_uint32,
8 c_short, c_ushort, c_int, c_uint,
9 c_long, c_ulong, c_longlong, c_ulonglong, c_float, c_double)
10 from ctypes.util import find_library
11 from struct import calcsize
12 from collections import namedtuple
13 from test import support
14 from test.support import import_helper
15 _ctypes_test = import_helper.import_module("_ctypes_test")
16 from ._support import (_CData, PyCStructType, Py_TPFLAGS_DISALLOW_INSTANTIATION,
17 Py_TPFLAGS_IMMUTABLETYPE)
18
19
20 class SubclassesTest(unittest.TestCase):
21 def test_subclass(self):
22 class X(Structure):
23 _fields_ = [("a", c_int)]
24
25 class Y(X):
26 _fields_ = [("b", c_int)]
27
28 class Z(X):
29 pass
30
31 self.assertEqual(sizeof(X), sizeof(c_int))
32 self.assertEqual(sizeof(Y), sizeof(c_int)*2)
33 self.assertEqual(sizeof(Z), sizeof(c_int))
34 self.assertEqual(X._fields_, [("a", c_int)])
35 self.assertEqual(Y._fields_, [("b", c_int)])
36 self.assertEqual(Z._fields_, [("a", c_int)])
37
38 def test_subclass_delayed(self):
39 class X(Structure):
40 pass
41 self.assertEqual(sizeof(X), 0)
42 X._fields_ = [("a", c_int)]
43
44 class Y(X):
45 pass
46 self.assertEqual(sizeof(Y), sizeof(X))
47 Y._fields_ = [("b", c_int)]
48
49 class Z(X):
50 pass
51
52 self.assertEqual(sizeof(X), sizeof(c_int))
53 self.assertEqual(sizeof(Y), sizeof(c_int)*2)
54 self.assertEqual(sizeof(Z), sizeof(c_int))
55 self.assertEqual(X._fields_, [("a", c_int)])
56 self.assertEqual(Y._fields_, [("b", c_int)])
57 self.assertEqual(Z._fields_, [("a", c_int)])
58
59
60 class StructureTestCase(unittest.TestCase):
61 formats = {"c": c_char,
62 "b": c_byte,
63 "B": c_ubyte,
64 "h": c_short,
65 "H": c_ushort,
66 "i": c_int,
67 "I": c_uint,
68 "l": c_long,
69 "L": c_ulong,
70 "q": c_longlong,
71 "Q": c_ulonglong,
72 "f": c_float,
73 "d": c_double,
74 }
75
76 def test_inheritance_hierarchy(self):
77 self.assertEqual(Structure.mro(), [Structure, _CData, object])
78
79 self.assertEqual(PyCStructType.__name__, "PyCStructType")
80 self.assertEqual(type(PyCStructType), type)
81
82
83 def test_type_flags(self):
84 for cls in Structure, PyCStructType:
85 with self.subTest(cls=cls):
86 self.assertTrue(Structure.__flags__ & Py_TPFLAGS_IMMUTABLETYPE)
87 self.assertFalse(Structure.__flags__ & Py_TPFLAGS_DISALLOW_INSTANTIATION)
88
89 def test_metaclass_details(self):
90 # Abstract classes (whose metaclass __init__ was not called) can't be
91 # instantiated directly
92 NewStructure = PyCStructType.__new__(PyCStructType, 'NewStructure',
93 (Structure,), {})
94 for cls in Structure, NewStructure:
95 with self.subTest(cls=cls):
96 with self.assertRaisesRegex(TypeError, "abstract class"):
97 obj = cls()
98
99 # Cannot call the metaclass __init__ more than once
100 class T(Structure):
101 _fields_ = [("x", c_char),
102 ("y", c_char)]
103 with self.assertRaisesRegex(SystemError, "already initialized"):
104 PyCStructType.__init__(T, 'ptr', (), {})
105
106 def test_simple_structs(self):
107 for code, tp in self.formats.items():
108 class X(Structure):
109 _fields_ = [("x", c_char),
110 ("y", tp)]
111 self.assertEqual((sizeof(X), code),
112 (calcsize("c%c0%c" % (code, code)), code))
113
114 def test_unions(self):
115 for code, tp in self.formats.items():
116 class X(Union):
117 _fields_ = [("x", c_char),
118 ("y", tp)]
119 self.assertEqual((sizeof(X), code),
120 (calcsize("%c" % (code)), code))
121
122 def test_struct_alignment(self):
123 class X(Structure):
124 _fields_ = [("x", c_char * 3)]
125 self.assertEqual(alignment(X), calcsize("s"))
126 self.assertEqual(sizeof(X), calcsize("3s"))
127
128 class Y(Structure):
129 _fields_ = [("x", c_char * 3),
130 ("y", c_int)]
131 self.assertEqual(alignment(Y), alignment(c_int))
132 self.assertEqual(sizeof(Y), calcsize("3si"))
133
134 class SI(Structure):
135 _fields_ = [("a", X),
136 ("b", Y)]
137 self.assertEqual(alignment(SI), max(alignment(Y), alignment(X)))
138 self.assertEqual(sizeof(SI), calcsize("3s0i 3si 0i"))
139
140 class IS(Structure):
141 _fields_ = [("b", Y),
142 ("a", X)]
143
144 self.assertEqual(alignment(SI), max(alignment(X), alignment(Y)))
145 self.assertEqual(sizeof(IS), calcsize("3si 3s 0i"))
146
147 class XX(Structure):
148 _fields_ = [("a", X),
149 ("b", X)]
150 self.assertEqual(alignment(XX), alignment(X))
151 self.assertEqual(sizeof(XX), calcsize("3s 3s 0s"))
152
153 def test_empty(self):
154 # I had problems with these
155 #
156 # Although these are pathological cases: Empty Structures!
157 class X(Structure):
158 _fields_ = []
159
160 class Y(Union):
161 _fields_ = []
162
163 # Is this really the correct alignment, or should it be 0?
164 self.assertTrue(alignment(X) == alignment(Y) == 1)
165 self.assertTrue(sizeof(X) == sizeof(Y) == 0)
166
167 class XX(Structure):
168 _fields_ = [("a", X),
169 ("b", X)]
170
171 self.assertEqual(alignment(XX), 1)
172 self.assertEqual(sizeof(XX), 0)
173
174 def test_fields(self):
175 # test the offset and size attributes of Structure/Union fields.
176 class X(Structure):
177 _fields_ = [("x", c_int),
178 ("y", c_char)]
179
180 self.assertEqual(X.x.offset, 0)
181 self.assertEqual(X.x.size, sizeof(c_int))
182
183 self.assertEqual(X.y.offset, sizeof(c_int))
184 self.assertEqual(X.y.size, sizeof(c_char))
185
186 # readonly
187 self.assertRaises((TypeError, AttributeError), setattr, X.x, "offset", 92)
188 self.assertRaises((TypeError, AttributeError), setattr, X.x, "size", 92)
189
190 class X(Union):
191 _fields_ = [("x", c_int),
192 ("y", c_char)]
193
194 self.assertEqual(X.x.offset, 0)
195 self.assertEqual(X.x.size, sizeof(c_int))
196
197 self.assertEqual(X.y.offset, 0)
198 self.assertEqual(X.y.size, sizeof(c_char))
199
200 # readonly
201 self.assertRaises((TypeError, AttributeError), setattr, X.x, "offset", 92)
202 self.assertRaises((TypeError, AttributeError), setattr, X.x, "size", 92)
203
204 # XXX Should we check nested data types also?
205 # offset is always relative to the class...
206
207 def test_packed(self):
208 class X(Structure):
209 _fields_ = [("a", c_byte),
210 ("b", c_longlong)]
211 _pack_ = 1
212
213 self.assertEqual(sizeof(X), 9)
214 self.assertEqual(X.b.offset, 1)
215
216 class X(Structure):
217 _fields_ = [("a", c_byte),
218 ("b", c_longlong)]
219 _pack_ = 2
220 self.assertEqual(sizeof(X), 10)
221 self.assertEqual(X.b.offset, 2)
222
223 longlong_size = struct.calcsize("q")
224 longlong_align = struct.calcsize("bq") - longlong_size
225
226 class X(Structure):
227 _fields_ = [("a", c_byte),
228 ("b", c_longlong)]
229 _pack_ = 4
230 self.assertEqual(sizeof(X), min(4, longlong_align) + longlong_size)
231 self.assertEqual(X.b.offset, min(4, longlong_align))
232
233 class X(Structure):
234 _fields_ = [("a", c_byte),
235 ("b", c_longlong)]
236 _pack_ = 8
237
238 self.assertEqual(sizeof(X), min(8, longlong_align) + longlong_size)
239 self.assertEqual(X.b.offset, min(8, longlong_align))
240
241
242 d = {"_fields_": [("a", "b"),
243 ("b", "q")],
244 "_pack_": -1}
245 self.assertRaises(ValueError, type(Structure), "X", (Structure,), d)
246
247 @support.cpython_only
248 def test_packed_c_limits(self):
249 # Issue 15989
250 import _testcapi
251 d = {"_fields_": [("a", c_byte)],
252 "_pack_": _testcapi.INT_MAX + 1}
253 self.assertRaises(ValueError, type(Structure), "X", (Structure,), d)
254 d = {"_fields_": [("a", c_byte)],
255 "_pack_": _testcapi.UINT_MAX + 2}
256 self.assertRaises(ValueError, type(Structure), "X", (Structure,), d)
257
258 def test_initializers(self):
259 class Person(Structure):
260 _fields_ = [("name", c_char*6),
261 ("age", c_int)]
262
263 self.assertRaises(TypeError, Person, 42)
264 self.assertRaises(ValueError, Person, b"asldkjaslkdjaslkdj")
265 self.assertRaises(TypeError, Person, "Name", "HI")
266
267 # short enough
268 self.assertEqual(Person(b"12345", 5).name, b"12345")
269 # exact fit
270 self.assertEqual(Person(b"123456", 5).name, b"123456")
271 # too long
272 self.assertRaises(ValueError, Person, b"1234567", 5)
273
274 def test_conflicting_initializers(self):
275 class POINT(Structure):
276 _fields_ = [("phi", c_float), ("rho", c_float)]
277 # conflicting positional and keyword args
278 self.assertRaisesRegex(TypeError, "phi", POINT, 2, 3, phi=4)
279 self.assertRaisesRegex(TypeError, "rho", POINT, 2, 3, rho=4)
280
281 # too many initializers
282 self.assertRaises(TypeError, POINT, 2, 3, 4)
283
284 def test_keyword_initializers(self):
285 class POINT(Structure):
286 _fields_ = [("x", c_int), ("y", c_int)]
287 pt = POINT(1, 2)
288 self.assertEqual((pt.x, pt.y), (1, 2))
289
290 pt = POINT(y=2, x=1)
291 self.assertEqual((pt.x, pt.y), (1, 2))
292
293 def test_invalid_field_types(self):
294 class POINT(Structure):
295 pass
296 self.assertRaises(TypeError, setattr, POINT, "_fields_", [("x", 1), ("y", 2)])
297
298 def test_invalid_name(self):
299 # field name must be string
300 def declare_with_name(name):
301 class S(Structure):
302 _fields_ = [(name, c_int)]
303
304 self.assertRaises(TypeError, declare_with_name, b"x")
305
306 def test_intarray_fields(self):
307 class SomeInts(Structure):
308 _fields_ = [("a", c_int * 4)]
309
310 # can use tuple to initialize array (but not list!)
311 self.assertEqual(SomeInts((1, 2)).a[:], [1, 2, 0, 0])
312 self.assertEqual(SomeInts((1, 2)).a[::], [1, 2, 0, 0])
313 self.assertEqual(SomeInts((1, 2)).a[::-1], [0, 0, 2, 1])
314 self.assertEqual(SomeInts((1, 2)).a[::2], [1, 0])
315 self.assertEqual(SomeInts((1, 2)).a[1:5:6], [2])
316 self.assertEqual(SomeInts((1, 2)).a[6:4:-1], [])
317 self.assertEqual(SomeInts((1, 2, 3, 4)).a[:], [1, 2, 3, 4])
318 self.assertEqual(SomeInts((1, 2, 3, 4)).a[::], [1, 2, 3, 4])
319 # too long
320 # XXX Should raise ValueError?, not RuntimeError
321 self.assertRaises(RuntimeError, SomeInts, (1, 2, 3, 4, 5))
322
323 def test_nested_initializers(self):
324 # test initializing nested structures
325 class Phone(Structure):
326 _fields_ = [("areacode", c_char*6),
327 ("number", c_char*12)]
328
329 class Person(Structure):
330 _fields_ = [("name", c_char * 12),
331 ("phone", Phone),
332 ("age", c_int)]
333
334 p = Person(b"Someone", (b"1234", b"5678"), 5)
335
336 self.assertEqual(p.name, b"Someone")
337 self.assertEqual(p.phone.areacode, b"1234")
338 self.assertEqual(p.phone.number, b"5678")
339 self.assertEqual(p.age, 5)
340
341 def test_structures_with_wchar(self):
342 class PersonW(Structure):
343 _fields_ = [("name", c_wchar * 12),
344 ("age", c_int)]
345
346 p = PersonW("Someone \xe9")
347 self.assertEqual(p.name, "Someone \xe9")
348
349 self.assertEqual(PersonW("1234567890").name, "1234567890")
350 self.assertEqual(PersonW("12345678901").name, "12345678901")
351 # exact fit
352 self.assertEqual(PersonW("123456789012").name, "123456789012")
353 #too long
354 self.assertRaises(ValueError, PersonW, "1234567890123")
355
356 def test_init_errors(self):
357 class Phone(Structure):
358 _fields_ = [("areacode", c_char*6),
359 ("number", c_char*12)]
360
361 class Person(Structure):
362 _fields_ = [("name", c_char * 12),
363 ("phone", Phone),
364 ("age", c_int)]
365
366 cls, msg = self.get_except(Person, b"Someone", (1, 2))
367 self.assertEqual(cls, RuntimeError)
368 self.assertEqual(msg,
369 "(Phone) TypeError: "
370 "expected bytes, int found")
371
372 cls, msg = self.get_except(Person, b"Someone", (b"a", b"b", b"c"))
373 self.assertEqual(cls, RuntimeError)
374 self.assertEqual(msg,
375 "(Phone) TypeError: too many initializers")
376
377 def test_huge_field_name(self):
378 # issue12881: segfault with large structure field names
379 def create_class(length):
380 class S(Structure):
381 _fields_ = [('x' * length, c_int)]
382
383 for length in [10 ** i for i in range(0, 8)]:
384 try:
385 create_class(length)
386 except MemoryError:
387 # MemoryErrors are OK, we just don't want to segfault
388 pass
389
390 def get_except(self, func, *args):
391 try:
392 func(*args)
393 except Exception as detail:
394 return detail.__class__, str(detail)
395
396 def test_abstract_class(self):
397 class X(Structure):
398 _abstract_ = "something"
399 # try 'X()'
400 cls, msg = self.get_except(eval, "X()", locals())
401 self.assertEqual((cls, msg), (TypeError, "abstract class"))
402
403 def test_methods(self):
404 self.assertIn("in_dll", dir(type(Structure)))
405 self.assertIn("from_address", dir(type(Structure)))
406 self.assertIn("in_dll", dir(type(Structure)))
407
408 def test_positional_args(self):
409 # see also http://bugs.python.org/issue5042
410 class W(Structure):
411 _fields_ = [("a", c_int), ("b", c_int)]
412 class X(W):
413 _fields_ = [("c", c_int)]
414 class Y(X):
415 pass
416 class Z(Y):
417 _fields_ = [("d", c_int), ("e", c_int), ("f", c_int)]
418
419 z = Z(1, 2, 3, 4, 5, 6)
420 self.assertEqual((z.a, z.b, z.c, z.d, z.e, z.f),
421 (1, 2, 3, 4, 5, 6))
422 z = Z(1)
423 self.assertEqual((z.a, z.b, z.c, z.d, z.e, z.f),
424 (1, 0, 0, 0, 0, 0))
425 self.assertRaises(TypeError, lambda: Z(1, 2, 3, 4, 5, 6, 7))
426
427 def test_pass_by_value(self):
428 # This should mirror the Test structure
429 # in Modules/_ctypes/_ctypes_test.c
430 class Test(Structure):
431 _fields_ = [
432 ('first', c_ulong),
433 ('second', c_ulong),
434 ('third', c_ulong),
435 ]
436
437 s = Test()
438 s.first = 0xdeadbeef
439 s.second = 0xcafebabe
440 s.third = 0x0bad1dea
441 dll = CDLL(_ctypes_test.__file__)
442 func = dll._testfunc_large_struct_update_value
443 func.argtypes = (Test,)
444 func.restype = None
445 func(s)
446 self.assertEqual(s.first, 0xdeadbeef)
447 self.assertEqual(s.second, 0xcafebabe)
448 self.assertEqual(s.third, 0x0bad1dea)
449
450 def test_pass_by_value_finalizer(self):
451 # bpo-37140: Similar to test_pass_by_value(), but the Python structure
452 # has a finalizer (__del__() method): the finalizer must only be called
453 # once.
454
455 finalizer_calls = []
456
457 class Test(Structure):
458 _fields_ = [
459 ('first', c_ulong),
460 ('second', c_ulong),
461 ('third', c_ulong),
462 ]
463 def __del__(self):
464 finalizer_calls.append("called")
465
466 s = Test(1, 2, 3)
467 # Test the StructUnionType_paramfunc() code path which copies the
468 # structure: if the structure is larger than sizeof(void*).
469 self.assertGreater(sizeof(s), sizeof(c_void_p))
470
471 dll = CDLL(_ctypes_test.__file__)
472 func = dll._testfunc_large_struct_update_value
473 func.argtypes = (Test,)
474 func.restype = None
475 func(s)
476 # bpo-37140: Passing the structure by reference must not call
477 # its finalizer!
478 self.assertEqual(finalizer_calls, [])
479 self.assertEqual(s.first, 1)
480 self.assertEqual(s.second, 2)
481 self.assertEqual(s.third, 3)
482
483 # The finalizer must be called exactly once
484 s = None
485 support.gc_collect()
486 self.assertEqual(finalizer_calls, ["called"])
487
488 def test_pass_by_value_in_register(self):
489 class X(Structure):
490 _fields_ = [
491 ('first', c_uint),
492 ('second', c_uint)
493 ]
494
495 s = X()
496 s.first = 0xdeadbeef
497 s.second = 0xcafebabe
498 dll = CDLL(_ctypes_test.__file__)
499 func = dll._testfunc_reg_struct_update_value
500 func.argtypes = (X,)
501 func.restype = None
502 func(s)
503 self.assertEqual(s.first, 0xdeadbeef)
504 self.assertEqual(s.second, 0xcafebabe)
505 got = X.in_dll(dll, "last_tfrsuv_arg")
506 self.assertEqual(s.first, got.first)
507 self.assertEqual(s.second, got.second)
508
509 def _test_issue18060(self, Vector):
510 # The call to atan2() should succeed if the
511 # class fields were correctly cloned in the
512 # subclasses. Otherwise, it will segfault.
513 if sys.platform == 'win32':
514 libm = CDLL(find_library('msvcrt.dll'))
515 else:
516 libm = CDLL(find_library('m'))
517
518 libm.atan2.argtypes = [Vector]
519 libm.atan2.restype = c_double
520
521 arg = Vector(y=0.0, x=-1.0)
522 self.assertAlmostEqual(libm.atan2(arg), 3.141592653589793)
523
524 @unittest.skipIf(_architecture() == ('64bit', 'WindowsPE'), "can't test Windows x64 build")
525 @unittest.skipUnless(sys.byteorder == 'little', "can't test on this platform")
526 def test_issue18060_a(self):
527 # This test case calls
528 # PyCStructUnionType_update_stginfo() for each
529 # _fields_ assignment, and PyCStgInfo_clone()
530 # for the Mid and Vector class definitions.
531 class Base(Structure):
532 _fields_ = [('y', c_double),
533 ('x', c_double)]
534 class Mid(Base):
535 pass
536 Mid._fields_ = []
537 class Vector(Mid): pass
538 self._test_issue18060(Vector)
539
540 @unittest.skipIf(_architecture() == ('64bit', 'WindowsPE'), "can't test Windows x64 build")
541 @unittest.skipUnless(sys.byteorder == 'little', "can't test on this platform")
542 def test_issue18060_b(self):
543 # This test case calls
544 # PyCStructUnionType_update_stginfo() for each
545 # _fields_ assignment.
546 class Base(Structure):
547 _fields_ = [('y', c_double),
548 ('x', c_double)]
549 class Mid(Base):
550 _fields_ = []
551 class Vector(Mid):
552 _fields_ = []
553 self._test_issue18060(Vector)
554
555 @unittest.skipIf(_architecture() == ('64bit', 'WindowsPE'), "can't test Windows x64 build")
556 @unittest.skipUnless(sys.byteorder == 'little', "can't test on this platform")
557 def test_issue18060_c(self):
558 # This test case calls
559 # PyCStructUnionType_update_stginfo() for each
560 # _fields_ assignment.
561 class Base(Structure):
562 _fields_ = [('y', c_double)]
563 class Mid(Base):
564 _fields_ = []
565 class Vector(Mid):
566 _fields_ = [('x', c_double)]
567 self._test_issue18060(Vector)
568
569 def test_array_in_struct(self):
570 # See bpo-22273
571
572 # Load the shared library
573 dll = CDLL(_ctypes_test.__file__)
574
575 # These should mirror the structures in Modules/_ctypes/_ctypes_test.c
576 class Test2(Structure):
577 _fields_ = [
578 ('data', c_ubyte * 16),
579 ]
580
581 class Test3AParent(Structure):
582 _fields_ = [
583 ('data', c_float * 2),
584 ]
585
586 class Test3A(Test3AParent):
587 _fields_ = [
588 ('more_data', c_float * 2),
589 ]
590
591 class Test3B(Structure):
592 _fields_ = [
593 ('data', c_double * 2),
594 ]
595
596 class Test3C(Structure):
597 _fields_ = [
598 ("data", c_double * 4)
599 ]
600
601 class Test3D(Structure):
602 _fields_ = [
603 ("data", c_double * 8)
604 ]
605
606 class Test3E(Structure):
607 _fields_ = [
608 ("data", c_double * 9)
609 ]
610
611
612 # Tests for struct Test2
613 s = Test2()
614 expected = 0
615 for i in range(16):
616 s.data[i] = i
617 expected += i
618 func = dll._testfunc_array_in_struct2
619 func.restype = c_int
620 func.argtypes = (Test2,)
621 result = func(s)
622 self.assertEqual(result, expected)
623 # check the passed-in struct hasn't changed
624 for i in range(16):
625 self.assertEqual(s.data[i], i)
626
627 # Tests for struct Test3A
628 s = Test3A()
629 s.data[0] = 3.14159
630 s.data[1] = 2.71828
631 s.more_data[0] = -3.0
632 s.more_data[1] = -2.0
633 expected = 3.14159 + 2.71828 - 3.0 - 2.0
634 func = dll._testfunc_array_in_struct3A
635 func.restype = c_double
636 func.argtypes = (Test3A,)
637 result = func(s)
638 self.assertAlmostEqual(result, expected, places=6)
639 # check the passed-in struct hasn't changed
640 self.assertAlmostEqual(s.data[0], 3.14159, places=6)
641 self.assertAlmostEqual(s.data[1], 2.71828, places=6)
642 self.assertAlmostEqual(s.more_data[0], -3.0, places=6)
643 self.assertAlmostEqual(s.more_data[1], -2.0, places=6)
644
645 # Test3B, Test3C, Test3D, Test3E have the same logic with different
646 # sizes hence putting them in a loop.
647 StructCtype = namedtuple(
648 "StructCtype",
649 ["cls", "cfunc1", "cfunc2", "items"]
650 )
651 structs_to_test = [
652 StructCtype(
653 Test3B,
654 dll._testfunc_array_in_struct3B,
655 dll._testfunc_array_in_struct3B_set_defaults,
656 2),
657 StructCtype(
658 Test3C,
659 dll._testfunc_array_in_struct3C,
660 dll._testfunc_array_in_struct3C_set_defaults,
661 4),
662 StructCtype(
663 Test3D,
664 dll._testfunc_array_in_struct3D,
665 dll._testfunc_array_in_struct3D_set_defaults,
666 8),
667 StructCtype(
668 Test3E,
669 dll._testfunc_array_in_struct3E,
670 dll._testfunc_array_in_struct3E_set_defaults,
671 9),
672 ]
673
674 for sut in structs_to_test:
675 s = sut.cls()
676
677 # Test for cfunc1
678 expected = 0
679 for i in range(sut.items):
680 float_i = float(i)
681 s.data[i] = float_i
682 expected += float_i
683 func = sut.cfunc1
684 func.restype = c_double
685 func.argtypes = (sut.cls,)
686 result = func(s)
687 self.assertEqual(result, expected)
688 # check the passed-in struct hasn't changed
689 for i in range(sut.items):
690 self.assertEqual(s.data[i], float(i))
691
692 # Test for cfunc2
693 func = sut.cfunc2
694 func.restype = sut.cls
695 result = func()
696 # check if the default values have been set correctly
697 for i in range(sut.items):
698 self.assertEqual(result.data[i], float(i+1))
699
700 def test_38368(self):
701 class U(Union):
702 _fields_ = [
703 ('f1', c_uint8 * 16),
704 ('f2', c_uint16 * 8),
705 ('f3', c_uint32 * 4),
706 ]
707 u = U()
708 u.f3[0] = 0x01234567
709 u.f3[1] = 0x89ABCDEF
710 u.f3[2] = 0x76543210
711 u.f3[3] = 0xFEDCBA98
712 f1 = [u.f1[i] for i in range(16)]
713 f2 = [u.f2[i] for i in range(8)]
714 if sys.byteorder == 'little':
715 self.assertEqual(f1, [0x67, 0x45, 0x23, 0x01,
716 0xef, 0xcd, 0xab, 0x89,
717 0x10, 0x32, 0x54, 0x76,
718 0x98, 0xba, 0xdc, 0xfe])
719 self.assertEqual(f2, [0x4567, 0x0123, 0xcdef, 0x89ab,
720 0x3210, 0x7654, 0xba98, 0xfedc])
721
722 @unittest.skipIf(True, 'Test disabled for now - see bpo-16575/bpo-16576')
723 def test_union_by_value(self):
724 # See bpo-16575
725
726 # These should mirror the structures in Modules/_ctypes/_ctypes_test.c
727
728 class Nested1(Structure):
729 _fields_ = [
730 ('an_int', c_int),
731 ('another_int', c_int),
732 ]
733
734 class Test4(Union):
735 _fields_ = [
736 ('a_long', c_long),
737 ('a_struct', Nested1),
738 ]
739
740 class Nested2(Structure):
741 _fields_ = [
742 ('an_int', c_int),
743 ('a_union', Test4),
744 ]
745
746 class Test5(Structure):
747 _fields_ = [
748 ('an_int', c_int),
749 ('nested', Nested2),
750 ('another_int', c_int),
751 ]
752
753 test4 = Test4()
754 dll = CDLL(_ctypes_test.__file__)
755 with self.assertRaises(TypeError) as ctx:
756 func = dll._testfunc_union_by_value1
757 func.restype = c_long
758 func.argtypes = (Test4,)
759 result = func(test4)
760 self.assertEqual(ctx.exception.args[0], 'item 1 in _argtypes_ passes '
761 'a union by value, which is unsupported.')
762 test5 = Test5()
763 with self.assertRaises(TypeError) as ctx:
764 func = dll._testfunc_union_by_value2
765 func.restype = c_long
766 func.argtypes = (Test5,)
767 result = func(test5)
768 self.assertEqual(ctx.exception.args[0], 'item 1 in _argtypes_ passes '
769 'a union by value, which is unsupported.')
770
771 # passing by reference should be OK
772 test4.a_long = 12345;
773 func = dll._testfunc_union_by_reference1
774 func.restype = c_long
775 func.argtypes = (POINTER(Test4),)
776 result = func(byref(test4))
777 self.assertEqual(result, 12345)
778 self.assertEqual(test4.a_long, 0)
779 self.assertEqual(test4.a_struct.an_int, 0)
780 self.assertEqual(test4.a_struct.another_int, 0)
781 test4.a_struct.an_int = 0x12340000
782 test4.a_struct.another_int = 0x5678
783 func = dll._testfunc_union_by_reference2
784 func.restype = c_long
785 func.argtypes = (POINTER(Test4),)
786 result = func(byref(test4))
787 self.assertEqual(result, 0x12345678)
788 self.assertEqual(test4.a_long, 0)
789 self.assertEqual(test4.a_struct.an_int, 0)
790 self.assertEqual(test4.a_struct.another_int, 0)
791 test5.an_int = 0x12000000
792 test5.nested.an_int = 0x345600
793 test5.another_int = 0x78
794 func = dll._testfunc_union_by_reference3
795 func.restype = c_long
796 func.argtypes = (POINTER(Test5),)
797 result = func(byref(test5))
798 self.assertEqual(result, 0x12345678)
799 self.assertEqual(test5.an_int, 0)
800 self.assertEqual(test5.nested.an_int, 0)
801 self.assertEqual(test5.another_int, 0)
802
803 @unittest.skipIf(True, 'Test disabled for now - see bpo-16575/bpo-16576')
804 def test_bitfield_by_value(self):
805 # See bpo-16576
806
807 # These should mirror the structures in Modules/_ctypes/_ctypes_test.c
808
809 class Test6(Structure):
810 _fields_ = [
811 ('A', c_int, 1),
812 ('B', c_int, 2),
813 ('C', c_int, 3),
814 ('D', c_int, 2),
815 ]
816
817 test6 = Test6()
818 # As these are signed int fields, all are logically -1 due to sign
819 # extension.
820 test6.A = 1
821 test6.B = 3
822 test6.C = 7
823 test6.D = 3
824 dll = CDLL(_ctypes_test.__file__)
825 with self.assertRaises(TypeError) as ctx:
826 func = dll._testfunc_bitfield_by_value1
827 func.restype = c_long
828 func.argtypes = (Test6,)
829 result = func(test6)
830 self.assertEqual(ctx.exception.args[0], 'item 1 in _argtypes_ passes '
831 'a struct/union with a bitfield by value, which is '
832 'unsupported.')
833 # passing by reference should be OK
834 func = dll._testfunc_bitfield_by_reference1
835 func.restype = c_long
836 func.argtypes = (POINTER(Test6),)
837 result = func(byref(test6))
838 self.assertEqual(result, -4)
839 self.assertEqual(test6.A, 0)
840 self.assertEqual(test6.B, 0)
841 self.assertEqual(test6.C, 0)
842 self.assertEqual(test6.D, 0)
843
844 class Test7(Structure):
845 _fields_ = [
846 ('A', c_uint, 1),
847 ('B', c_uint, 2),
848 ('C', c_uint, 3),
849 ('D', c_uint, 2),
850 ]
851 test7 = Test7()
852 test7.A = 1
853 test7.B = 3
854 test7.C = 7
855 test7.D = 3
856 func = dll._testfunc_bitfield_by_reference2
857 func.restype = c_long
858 func.argtypes = (POINTER(Test7),)
859 result = func(byref(test7))
860 self.assertEqual(result, 14)
861 self.assertEqual(test7.A, 0)
862 self.assertEqual(test7.B, 0)
863 self.assertEqual(test7.C, 0)
864 self.assertEqual(test7.D, 0)
865
866 # for a union with bitfields, the union check happens first
867 class Test8(Union):
868 _fields_ = [
869 ('A', c_int, 1),
870 ('B', c_int, 2),
871 ('C', c_int, 3),
872 ('D', c_int, 2),
873 ]
874
875 test8 = Test8()
876 with self.assertRaises(TypeError) as ctx:
877 func = dll._testfunc_bitfield_by_value2
878 func.restype = c_long
879 func.argtypes = (Test8,)
880 result = func(test8)
881 self.assertEqual(ctx.exception.args[0], 'item 1 in _argtypes_ passes '
882 'a union by value, which is unsupported.')
883
884
885 class PointerMemberTestCase(unittest.TestCase):
886
887 def test(self):
888 # a Structure with a POINTER field
889 class S(Structure):
890 _fields_ = [("array", POINTER(c_int))]
891
892 s = S()
893 # We can assign arrays of the correct type
894 s.array = (c_int * 3)(1, 2, 3)
895 items = [s.array[i] for i in range(3)]
896 self.assertEqual(items, [1, 2, 3])
897
898 # The following are bugs, but are included here because the unittests
899 # also describe the current behaviour.
900 #
901 # This fails with SystemError: bad arg to internal function
902 # or with IndexError (with a patch I have)
903
904 s.array[0] = 42
905
906 items = [s.array[i] for i in range(3)]
907 self.assertEqual(items, [42, 2, 3])
908
909 s.array[0] = 1
910
911 items = [s.array[i] for i in range(3)]
912 self.assertEqual(items, [1, 2, 3])
913
914 def test_none_to_pointer_fields(self):
915 class S(Structure):
916 _fields_ = [("x", c_int),
917 ("p", POINTER(c_int))]
918
919 s = S()
920 s.x = 12345678
921 s.p = None
922 self.assertEqual(s.x, 12345678)
923
924
925 class TestRecursiveStructure(unittest.TestCase):
926 def test_contains_itself(self):
927 class Recursive(Structure):
928 pass
929
930 try:
931 Recursive._fields_ = [("next", Recursive)]
932 except AttributeError as details:
933 self.assertIn("Structure or union cannot contain itself",
934 str(details))
935 else:
936 self.fail("Structure or union cannot contain itself")
937
938
939 def test_vice_versa(self):
940 class First(Structure):
941 pass
942 class Second(Structure):
943 pass
944
945 First._fields_ = [("second", Second)]
946
947 try:
948 Second._fields_ = [("first", First)]
949 except AttributeError as details:
950 self.assertIn("_fields_ is final", str(details))
951 else:
952 self.fail("AttributeError not raised")
953
954
955 if __name__ == '__main__':
956 unittest.main()