1from PyObjCTools.TestSupport import * 2import objc 3import objc._convenience as convenience 4 5class TestConvenienceHelpers (TestCase): 6 def test_add_for_selector(self): 7 methods = [ 8 ('add', lambda self, x: self.testMethod_(x)) 9 ] 10 11 with filterWarnings("error", DeprecationWarning): 12 self.assertRaises(DeprecationWarning, objc.addConvenienceForSelector, b'testMethod:', methods) 13 if b'testMethod' in convenience._CONVENIENCE_METHODS: 14 del convenience._CONVENIENCE_METHODS[b'testMethods:'] 15 16 with filterWarnings("ignore", DeprecationWarning): 17 self.assertNotIn(b'testMethod:', convenience._CONVENIENCE_METHODS) 18 try: 19 objc.addConvenienceForSelector(b'testMethod:', methods) 20 21 self.assertEqual(convenience._CONVENIENCE_METHODS[b'testMethod:'], methods) 22 23 finally: 24 if b'testMethod' in convenience._CONVENIENCE_METHODS: 25 del convenience._CONVENIENCE_METHODS[b'testMethods:'] 26 27 28 def test_add_for_class(self): 29 self.assertNotIn("MyObject", convenience.CLASS_METHODS) 30 31 methods = [ 32 ('info', lambda self: self.description()) 33 ] 34 35 try: 36 objc.addConvenienceForClass("MyObject", methods) 37 self.assertEqual(convenience.CLASS_METHODS["MyObject"], methods) 38 39 finally: 40 if 'MyObject' in convenience.CLASS_METHODS: 41 del convenience.CLASS_METHODS["MyObject"] 42 43 44 45class TestBasicConveniences (TestCase): 46 def testBundleForClass(self): 47 orig = convenience.currentBundle 48 try: 49 the_bundle = object() 50 def currentBundle(): 51 return the_bundle 52 convenience.currentBundle = currentBundle 53 54 class OC_Test_Basic_Convenience_1 (objc.lookUpClass("NSObject")): 55 pass 56 57 self.assertIs(OC_Test_Basic_Convenience_1.bundleForClass(), the_bundle) 58 finally: 59 convenience.currentBundle = orig 60 61 def test_kvc_helper(self): 62 o = objc.lookUpClass('NSURL').URLWithString_('http://www.python.org/') 63 self.assertEqual(o.host(), 'www.python.org') 64 65 self.assertEqual(o._.host, 'www.python.org') 66 self.assertEqual(o._['host'], 'www.python.org') 67 self.assertRaises(TypeError, lambda: o._[42]) 68 self.assertEqual(repr(o._), '<KVC accessor for %r>'%(o,)) 69 self.assertRaises(AttributeError, getattr, o._, 'nosuchattr') 70 self.assertRaises(TypeError, o._.__setitem__, 42) 71 72 o = objc.lookUpClass('NSMutableDictionary').dictionary() 73 o._.key1 = 1 74 o._['key2'] = 2 75 76 self.assertEqual(o, {'key1': 1, 'key2': 2 }) 77 self.assertRaises(AttributeError, o._.nosuchattr) 78 self.assertRaises(TypeError, o._.__setitem__, 42) 79 80 81 82# TODO: Explicit tests for add_convenience_methods. 83 84if __name__ == "__main__": 85 main() 86