1from PyObjCTools.TestSupport import *
2import objc, sys
3from PyObjCTest.opaque import *
4
5class TestFromPython (TestCase):
6    def testBasic (self):
7        tp = objc.createOpaquePointerType(
8                "BarHandle", BarEncoded, "BarHandle doc")
9
10        self.assertIsInstance(tp, type)
11
12        f = OC_OpaqueTest.createBarWithFirst_andSecond_(1.0, 4.5)
13        self.assertIsInstance(f, tp)
14        x = OC_OpaqueTest.getFirst_(f)
15        self.assertEqual(x, 1.0)
16        x = OC_OpaqueTest.getSecond_(f)
17        self.assertEqual(x, 4.5)
18
19        # NULL pointer is converted to None
20        self.assertEqual(OC_OpaqueTest.nullBar(), None)
21
22
23class TestFromC (TestCase):
24    def testMutable(self):
25        self.assertIsInstance(FooHandle, type)
26
27        def create(cls, value):
28            return OC_OpaqueTest.createFoo_(value)
29        FooHandle.create = classmethod(create)
30        FooHandle.delete = lambda self: OC_OpaqueTest.deleteFoo_(self)
31        FooHandle.get = lambda self: OC_OpaqueTest.getValueOf_(self)
32        FooHandle.set = lambda self, v: OC_OpaqueTest.setValue_forFoo_(v, self)
33
34        self.assertHasAttr(FooHandle, 'create')
35        self.assertHasAttr(FooHandle, 'delete')
36
37        f = FooHandle.create(42)
38        self.assertIsInstance(f, FooHandle)
39        self.assertEqual( f.get(), 42 )
40
41        f.set(f.get() + 20)
42        self.assertEqual( f.get(), 62 )
43
44        FooHandle.__int__ = lambda self: self.get()
45        FooHandle.__getitem__ = lambda self, x: self.get() * x
46
47        self.assertEqual(int(f), 62)
48        self.assertEqual(f[4], 4 * 62)
49
50    def testBasic(self):
51        f = OC_OpaqueTest.createFoo_(99)
52        self.assertIsInstance(f, FooHandle)
53        self.assertEqual( OC_OpaqueTest.getValueOf_(f), 99 )
54
55        self.assertHasAttr(f, "__pointer__")
56        if sys.version_info[0] == 2:
57            self.assertIsInstance(f.__pointer__, (int, long))
58        else:
59            self.assertIsInstance(f.__pointer__, int)
60
61        # NULL pointer is converted to None
62        self.assertEqual(OC_OpaqueTest.nullFoo(), None)
63
64        # There is no exposed type object that for PyCObject, test the
65        # type name instead
66        if sys.version_info[0] == 2 and sys.version_info[1] < 7:
67            self.assertEqual( type(f.__cobject__()).__name__, 'PyCObject' )
68        else:
69            self.assertEqual( type(f.__cobject__()).__name__, 'PyCapsule' )
70
71        # Check round tripping through a PyCObject.
72        co = f.__cobject__()
73        g = FooHandle(co)
74        self.assertEqual(f.__pointer__, g.__pointer__)
75
76if __name__ == "__main__":
77    main()
78