PageRenderTime 10ms CodeModel.GetById 1ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 0ms

/Lib/ctypes/test/test_anon.py

http://unladen-swallow.googlecode.com/
Python | 60 lines | 46 code | 12 blank | 2 comment | 1 complexity | 5b941e6ca4cde98c1f6dbedefd609872 MD5 | raw file
 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.failUnlessEqual(Y.a.offset, sizeof(c_int))
18        self.failUnlessEqual(Y.b.offset, sizeof(c_int))
19
20        self.failUnlessEqual(ANON.a.offset, 0)
21        self.failUnlessEqual(ANON.b.offset, 0)
22
23    def test_anon_nonseq(self):
24        # TypeError: _anonymous_ must be a sequence
25        self.failUnlessRaises(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.failUnlessRaises(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.failUnlessEqual(Y.x.offset, 0)
54        self.failUnlessEqual(Y.a.offset, sizeof(c_int))
55        self.failUnlessEqual(Y.b.offset, sizeof(c_int))
56        self.failUnlessEqual(Y._.offset, sizeof(c_int))
57        self.failUnlessEqual(Y.y.offset, sizeof(c_int) * 2)
58
59if __name__ == "__main__":
60    unittest.main()