File: test_init.py

package info (click to toggle)
python2.6 2.6.8-1.1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 65,740 kB
  • sloc: ansic: 389,342; python: 376,882; asm: 9,734; sh: 4,934; makefile: 4,040; lisp: 2,933; objc: 775; xml: 62
file content (40 lines) | stat: -rw-r--r-- 1,070 bytes parent folder | download | duplicates (15)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from ctypes import *
import unittest

class X(Structure):
    _fields_ = [("a", c_int),
                ("b", c_int)]
    new_was_called = False

    def __new__(cls):
        result = super(X, cls).__new__(cls)
        result.new_was_called = True
        return result

    def __init__(self):
        self.a = 9
        self.b = 12

class Y(Structure):
    _fields_ = [("x", X)]


class InitTest(unittest.TestCase):
    def test_get(self):
        # make sure the only accessing a nested structure
        # doesn't call the structure's __new__ and __init__
        y = Y()
        self.failUnlessEqual((y.x.a, y.x.b), (0, 0))
        self.failUnlessEqual(y.x.new_was_called, False)

        # But explicitely creating an X structure calls __new__ and __init__, of course.
        x = X()
        self.failUnlessEqual((x.a, x.b), (9, 12))
        self.failUnlessEqual(x.new_was_called, True)

        y.x = x
        self.failUnlessEqual((y.x.a, y.x.b), (9, 12))
        self.failUnlessEqual(y.x.new_was_called, False)

if __name__ == "__main__":
    unittest.main()