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