Debian Codegraph @

Lib/test/test_ctypes/test_anon.py

raw
1 import unittest
2 import test.support
3 from ctypes import c_int, Union, Structure, sizeof
4 from ._support import StructCheckMixin
5
6
7 class AnonTest(unittest.TestCase, StructCheckMixin):
8
9 def test_anon(self):
10 class ANON(Union):
11 _fields_ = [("a", c_int),
12 ("b", c_int)]
13 self.check_union(ANON)
14
15 class Y(Structure):
16 _fields_ = [("x", c_int),
17 ("_", ANON),
18 ("y", c_int)]
19 _anonymous_ = ["_"]
20 self.check_struct(Y)
21
22 self.assertEqual(Y.a.offset, sizeof(c_int))
23 self.assertEqual(Y.b.offset, sizeof(c_int))
24
25 self.assertEqual(ANON.a.offset, 0)
26 self.assertEqual(ANON.b.offset, 0)
27
28 def test_anon_nonseq(self):
29 # TypeError: _anonymous_ must be a sequence
30 self.assertRaises(TypeError,
31 lambda: type(Structure)("Name",
32 (Structure,),
33 {"_fields_": [], "_anonymous_": 42}))
34
35 def test_anon_nonmember(self):
36 # AttributeError: type object 'Name' has no attribute 'x'
37 self.assertRaises(AttributeError,
38 lambda: type(Structure)("Name",
39 (Structure,),
40 {"_fields_": [],
41 "_anonymous_": ["x"]}))
42
43 @test.support.cpython_only
44 def test_issue31490(self):
45 # There shouldn't be an assertion failure in case the class has an
46 # attribute whose name is specified in _anonymous_ but not in _fields_.
47
48 # AttributeError: 'x' is specified in _anonymous_ but not in _fields_
49 with self.assertRaises(AttributeError):
50 class Name(Structure):
51 _fields_ = []
52 _anonymous_ = ["x"]
53 x = 42
54
55 def test_nested(self):
56 class ANON_S(Structure):
57 _fields_ = [("a", c_int)]
58 self.check_struct(ANON_S)
59
60 class ANON_U(Union):
61 _fields_ = [("_", ANON_S),
62 ("b", c_int)]
63 _anonymous_ = ["_"]
64 self.check_union(ANON_U)
65
66 class Y(Structure):
67 _fields_ = [("x", c_int),
68 ("_", ANON_U),
69 ("y", c_int)]
70 _anonymous_ = ["_"]
71 self.check_struct(Y)
72
73 self.assertEqual(Y.x.offset, 0)
74 self.assertEqual(Y.a.offset, sizeof(c_int))
75 self.assertEqual(Y.b.offset, sizeof(c_int))
76 self.assertEqual(Y._.offset, sizeof(c_int))
77 self.assertEqual(Y.y.offset, sizeof(c_int) * 2)
78
79
80 if __name__ == "__main__":
81 unittest.main()