1import unittest 2from ctypes import * 3 4class AnonTest(unittest.TestCase): 5 6 def test_anon(self): 7 class ANON(Union): 8 _fields_ = [("a", c_int), 9 ("b", c_int)] 10 11 class Y(Structure): 12 _fields_ = [("x", c_int), 13 ("_", ANON), 14 ("y", c_int)] 15 _anonymous_ = ["_"] 16 17 self.assertEqual(Y.a.offset, sizeof(c_int)) 18 self.assertEqual(Y.b.offset, sizeof(c_int)) 19 20 self.assertEqual(ANON.a.offset, 0) 21 self.assertEqual(ANON.b.offset, 0) 22 23 def test_anon_nonseq(self): 24 # TypeError: _anonymous_ must be a sequence 25 self.assertRaises(TypeError, 26 lambda: type(Structure)("Name", 27 (Structure,), 28 {"_fields_": [], "_anonymous_": 42})) 29 30 def test_anon_nonmember(self): 31 # AttributeError: type object 'Name' has no attribute 'x' 32 self.assertRaises(AttributeError, 33 lambda: type(Structure)("Name", 34 (Structure,), 35 {"_fields_": [], 36 "_anonymous_": ["x"]})) 37 38 def test_nested(self): 39 class ANON_S(Structure): 40 _fields_ = [("a", c_int)] 41 42 class ANON_U(Union): 43 _fields_ = [("_", ANON_S), 44 ("b", c_int)] 45 _anonymous_ = ["_"] 46 47 class Y(Structure): 48 _fields_ = [("x", c_int), 49 ("_", ANON_U), 50 ("y", c_int)] 51 _anonymous_ = ["_"] 52 53 self.assertEqual(Y.x.offset, 0) 54 self.assertEqual(Y.a.offset, sizeof(c_int)) 55 self.assertEqual(Y.b.offset, sizeof(c_int)) 56 self.assertEqual(Y._.offset, sizeof(c_int)) 57 self.assertEqual(Y.y.offset, sizeof(c_int) * 2) 58 59if __name__ == "__main__": 60 unittest.main() 61