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