Debian Codegraph @

lib-python/3/ctypes/test/test_structures.py

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