1from __future__ import unicode_literals
2from PyObjCTools.TestSupport import *
3import objc
4from PyObjCTest.testbndl import PyObjC_TestClass4
5from . import fnd as Foundation
6from .fnd import NSObject, NSArray, NSAttributedString
7import sys
8import os
9
10
11class TestConstants(TestCase):
12    def testBooleans(self):
13        self.assertTrue(objc.YES, "YES was not true.")
14        self.assertTrue(not objc.NO, "NO was true.")
15
16    def testNil(self):
17        self.assertIsNone(objc.nil, "nil is not nil/None.")
18
19
20class TestObjCRuntime (TestCase):
21    # Tests for objc.runtime
22    def setUp(self):
23        import warnings
24        warnings.filterwarnings('ignore', category=DeprecationWarning)
25
26    def tearDown(self):
27        import warnings
28        del warnings.filters[0]
29
30    def testClasses(self):
31        classes = objc.runtime.__objc_classes__
32        for cls in classes:
33            self.assertIsInstance(cls, objc.objc_class)
34
35    def testKind(self):
36        self.assertEqual(objc.runtime.__kind__, "python")
37
38    def testRepr(self):
39        self.assertEqual(repr(objc.runtime), "objc.runtime")
40
41
42    def testRuntimeNoSuchClassErrorRaised(self):
43        try:
44            objc.runtime.ThisClassReallyShouldNotExist
45        except AttributeError:
46            pass
47        except AttributeError:
48            pass
49        else:
50            fail("objc.runtime.ThisClassReallyShouldNotExist should have thrown a nosuchclass_error.  It didn't.")
51
52    def testRuntimeConsistency(self):
53        self.assertIsNotNone(objc.lookUpClass("NSObject"))
54        self.assertIs(objc.lookUpClass( "NSObject" ), objc.runtime.NSObject)
55
56
57class TestClassLookup(TestCase):
58    def testLookupClassNoSuchClassErrorRaised(self):
59        self.assertRaises(objc.nosuchclass_error, objc.lookUpClass, "")
60        self.assertRaises(objc.nosuchclass_error, objc.lookUpClass, "ThisClassReallyShouldNotExist")
61        self.assertRaises(TypeError, objc.lookUpClass, 1)
62
63
64
65    def testClassList(self):
66        ###! This test should probably be moved down to the Foundation test suite...
67
68        NSObject = objc.lookUpClass('NSObject')
69        NSException = objc.lookUpClass('NSException')
70        NSMutableArray = objc.lookUpClass('NSMutableArray')
71
72        self.assertIn(NSObject, objc.getClassList())
73        self.assertIn(NSException, objc.getClassList())
74        self.assertIn(NSMutableArray, objc.getClassList())
75
76class TestMethodInvocation(TestCase):
77    def setUp(self):
78        self.NSObjectInstance = NSObject.alloc().init()
79
80
81    def testClassInvocation(self):
82        self.assertTrue(NSObject.pyobjc_classMethods.description())
83
84    def testInstanceInvocation(self):
85        self.assertTrue(self.NSObjectInstance.description())
86        self.assertEqual(self.NSObjectInstance.self(), self.NSObjectInstance)
87        self.assertEqual(self.NSObjectInstance.pyobjc_instanceMethods.self(), self.NSObjectInstance.self())
88        self.assertEqual(type(self.NSObjectInstance).pyobjc_instanceMethods.self(self.NSObjectInstance), self.NSObjectInstance.self())
89
90class TestClassDict(TestCase):
91    def testDict(self):
92        self.assertIn("attributesAtIndex_longestEffectiveRange_inRange_", NSAttributedString.__dict__)
93
94class TestPickle(TestCase):
95    # We don't support pickling at the moment, make sure we enforce that.
96
97    def testPicklePure(self):
98        import pickle
99
100        o = NSObject.alloc().init()
101        self.assertRaises((TypeError, ValueError), pickle.dumps, o, 0)
102        self.assertRaises((TypeError, ValueError), pickle.dumps, o, 1)
103        self.assertRaises((TypeError, ValueError), pickle.dumps, o, 2)
104
105    @onlyIf(sys.version_info[0] == 2, "python 2.x test")
106    def testCPicklePure(self):
107        import cPickle as pickle
108
109        o = NSObject.alloc().init()
110        self.assertRaises((TypeError, ValueError), pickle.dumps, o, 0)
111        self.assertRaises((TypeError, ValueError), pickle.dumps, o, 1)
112        self.assertRaises((TypeError, ValueError), pickle.dumps, o, 2)
113
114
115class TestDescription (TestCase):
116    def testSimple(self):
117        TESTS   = ['a'], 'hello', 2
118        a = NSArray.arrayWithArray_(['a'])
119        EXPECTS = '(a)', 'hello', '2'
120        EXPECTS = repr(a), 'hello', '2'
121        for obj,expect in zip(TESTS, EXPECTS):
122            self.assertEqual(expect, PyObjC_TestClass4.fetchObjectDescription_(obj))
123
124class TestPrivate (TestCase):
125    def test_resolve_name(self):
126        resolve = objc._resolve_name
127
128        self.assertRaises(ValueError, resolve, "sys")
129
130        self.assertIs(resolve("sys.path"), sys.path)
131
132        v = resolve("distutils.command.sdist.show_formats")
133
134        from distutils.command.sdist import show_formats
135        self.assertIs(v, show_formats)
136
137        self.assertRaises(AttributeError, resolve, "distutils.command.sdist.dont_show_formats")
138        self.assertRaises(AttributeError, resolve, "sys.does_not_exist")
139
140class TestPluginSupport (TestCase):
141    def test_deprecated(self):
142        with filterWarnings("error", DeprecationWarning):
143            self.assertRaises(DeprecationWarning, objc.registerPlugin, "myplugin")
144            self.assertRaises(DeprecationWarning, objc.pluginBundle, "myplugin")
145
146    def test_usage(self):
147        with filterWarnings("ignore", DeprecationWarning):
148            self.assertRaises(KeyError, objc.pluginBundle, "myplugin")
149
150            self.assertNotIn('RESOURCEPATH', os.environ)
151            self.assertRaises(KeyError, objc.registerPlugin, "myplugin")
152
153            # Actual plugin is .../MyPlugin.bundle/Contents/Resources, this is close enought and
154            # ensures that we can actually create as NSBundle later on.
155            os.environ['RESOURCEPATH'] = '/System/Library/Frameworks/Cocoa.framework/Contents/Resources'
156            try:
157                objc.registerPlugin("myplugin")
158
159                if sys.version_info[0] == 2:
160                    os.environ['RESOURCEPATH'] = b'/System/Library/Frameworks/Cocoa.framework/Contents/Resources'
161                    objc.registerPlugin("myplugin")
162            finally:
163                del os.environ['RESOURCEPATH']
164
165            b = objc.pluginBundle("myplugin")
166            self.assertIsInstance(b, objc.lookUpClass("NSBundle"))
167            self.assertEqual(b.bundlePath(), '/System/Library/Frameworks/Cocoa.framework')
168
169class TestCompatJunk (TestCase):
170    def test_loadFunctionList(self):
171        with filterWarnings("error", DeprecationWarning):
172            self.assertRaises(DeprecationWarning, objc._loadFunctionList, [])
173
174        orig = objc.loadFunctionList
175        try:
176            l = []
177            objc.loadFunctionList = lambda *args, **kwds: l.append((args, kwds))
178
179            objc._loadFunctionList(1, 2, a=3, b=3)
180            self.assertEqual(l, [((1,2), {'a':3, 'b':3})])
181
182        finally:
183            objc.loadFunctionList = orig
184
185if __name__ == '__main__':
186    main()
187