Debian Codegraph @

Lib/test/test_ctypes/test_init.py

raw
1 import unittest
2 from ctypes import Structure, c_int
3
4
5 class X(Structure):
6 _fields_ = [("a", c_int),
7 ("b", c_int)]
8 new_was_called = False
9
10 def __new__(cls):
11 result = super().__new__(cls)
12 result.new_was_called = True
13 return result
14
15 def __init__(self):
16 self.a = 9
17 self.b = 12
18
19
20 class Y(Structure):
21 _fields_ = [("x", X)]
22
23
24 class InitTest(unittest.TestCase):
25 def test_get(self):
26 # make sure the only accessing a nested structure
27 # doesn't call the structure's __new__ and __init__
28 y = Y()
29 self.assertEqual((y.x.a, y.x.b), (0, 0))
30 self.assertEqual(y.x.new_was_called, False)
31
32 # But explicitly creating an X structure calls __new__ and __init__, of course.
33 x = X()
34 self.assertEqual((x.a, x.b), (9, 12))
35 self.assertEqual(x.new_was_called, True)
36
37 y.x = x
38 self.assertEqual((y.x.a, y.x.b), (9, 12))
39 self.assertEqual(y.x.new_was_called, False)
40
41
42 if __name__ == "__main__":
43 unittest.main()