def testPickling(self):
        v = {
            "long": NSNumber.numberWithUnsignedLongLong_(2**63 + 5000),
            "int": NSNumber.numberWithInt_(42),
            "float": NSNumber.numberWithDouble_(2.0),
        }
        import pickle

        data = pickle.dumps(v)

        w = pickle.loads(data)
        if os_level_key(os_release()) < os_level_key("10.5"):
            self.assertEqual(w, {
                "long": -(2**63) + 5000,
                "int": 42,
                "float": 2.0
            })
        else:
            self.assertEqual(w, {
                "long": 2**63 + 5000,
                "int": 42,
                "float": 2.0
            })

        for o in v.values():
            self.assertTrue(hasattr(o, "__pyobjc_object__"))

        for o in w.values():
            self.assertFalse(hasattr(o, "__pyobjc_object__"))
Exemple #2
0
 def testResourcesDirect(self):
     bundle = CoreFoundation.CFURLCreateWithFileSystemPath(
         None,
         "/System/Library/Frameworks/Foundation.framework",
         CoreFoundation.kCFURLPOSIXPathStyle,
         True,
     )
     url = CoreFoundation.CFBundleCopyResourceURLInDirectory(
         bundle, "Formatter", "strings", None
     )
     self.assertIsInstance(url, CoreFoundation.CFURLRef)
     array = CoreFoundation.CFBundleCopyResourceURLsOfTypeInDirectory(
         bundle, "strings", None
     )
     self.assertIsNot(array, None)
     self.assertIsInstance(array, CoreFoundation.CFArrayRef)
     infoDict = CoreFoundation.CFBundleCopyInfoDictionaryForURL(bundle)
     self.assertIsInstance(infoDict, CoreFoundation.CFDictionaryRef)
     array = CoreFoundation.CFBundleCopyLocalizationsForURL(bundle)
     self.assertIsInstance(array, CoreFoundation.CFArrayRef)
     array = CoreFoundation.CFBundleCopyExecutableArchitecturesForURL(bundle)
     if os_level_key(os_release()) >= os_level_key("10.16"):
         self.assertIs(array, None)
     else:
         self.assertIsInstance(array, CoreFoundation.CFArrayRef)
         for a in array:
             self.assertIsInstance(a, int)
Exemple #3
0
 def test_functions10_15(self):
     if os_level_key(os_release()) < os_level_key("10.15"):
         # The latest Xcode that supports macOS 10.14 supports
         # the 10.15 SDK, but not this API
         if not hasattr(Metal, "MTLCoordinate2DMake"):
             return
     v = Metal.MTLCoordinate2DMake(0.5, 1.5)
     self.assertIsInstance(v, Metal.MTLCoordinate2D)
     self.assertEqual(v, (0.5, 1.5))
Exemple #4
0
    def testMethods32(self):
        self.assertResultIsBOOL(AppKit.NSFont.isBaseFont)
        self.assertResultIsBOOL(AppKit.NSFont.glyphIsEncoded_)
        self.assertArgHasType(AppKit.NSFont.glyphIsEncoded_, 0, b"I")
        self.assertArgHasType(
            AppKit.NSFont.positionOfGlyph_precededByGlyph_isNominal_, 0, b"I")
        self.assertArgHasType(
            AppKit.NSFont.positionOfGlyph_precededByGlyph_isNominal_, 1, b"I")
        self.assertArgHasType(
            AppKit.NSFont.positionOfGlyph_precededByGlyph_isNominal_,
            2,
            b"o^" + objc._C_NSBOOL,
        )

        self.assertArgHasType(
            AppKit.NSFont.
            positionsForCompositeSequence_numberOfGlyphs_pointArray_,
            0,
            b"n^I",
        )
        self.assertArgSizeInArg(
            AppKit.NSFont.
            positionsForCompositeSequence_numberOfGlyphs_pointArray_, 0, 1)
        self.assertArgHasType(
            AppKit.NSFont.
            positionsForCompositeSequence_numberOfGlyphs_pointArray_,
            2,
            b"o^" + AppKit.NSPoint.__typestr__,
        )
        self.assertArgSizeInArg(
            AppKit.NSFont.
            positionsForCompositeSequence_numberOfGlyphs_pointArray_, 2, 1)

        self.assertArgHasType(
            AppKit.NSFont.positionOfGlyph_struckOverGlyph_metricsExist_,
            2,
            b"o^" + objc._C_NSBOOL,
        )
        self.assertArgHasType(
            AppKit.NSFont.positionOfGlyph_struckOverRect_metricsExist_,
            2,
            b"o^" + objc._C_NSBOOL,
        )

        if os_level_key(os_release()) < os_level_key("10.10"):
            self.assertArgHasType(
                AppKit.NSFont.
                positionOfGlyph_withRelation_toBaseGlyph_totalAdvancement_metricsExist_,  # noqa: B950
                3,
                b"o^" + AppKit.NSSize.__typestr__,
            )
            self.assertArgHasType(
                AppKit.NSFont.
                positionOfGlyph_withRelation_toBaseGlyph_totalAdvancement_metricsExist_,  # noqa: B950
                4,
                b"o^" + objc._C_NSBOOL,
            )
Exemple #5
0
class TestMPNowPlayingInfoCenter(TestCase):
    @min_os_level("10.12")
    def testConstants(self):
        self.assertEqual(MediaPlayer.MPNowPlayingInfoMediaTypeNone, 0)
        self.assertEqual(MediaPlayer.MPNowPlayingInfoMediaTypeAudio, 1)
        self.assertEqual(MediaPlayer.MPNowPlayingInfoMediaTypeVideo, 2)
        self.assertEqual(MediaPlayer.MPNowPlayingPlaybackStateUnknown, 0)
        self.assertEqual(MediaPlayer.MPNowPlayingPlaybackStatePlaying, 1)
        self.assertEqual(MediaPlayer.MPNowPlayingPlaybackStatePaused, 2)
        self.assertEqual(MediaPlayer.MPNowPlayingPlaybackStateStopped, 3)
        self.assertEqual(MediaPlayer.MPNowPlayingPlaybackStateInterrupted, 4)

        self.assertIsInstance(
            MediaPlayer.MPNowPlayingInfoPropertyElapsedPlaybackTime, str)
        self.assertIsInstance(MediaPlayer.MPNowPlayingInfoPropertyPlaybackRate,
                              str)
        self.assertIsInstance(
            MediaPlayer.MPNowPlayingInfoPropertyDefaultPlaybackRate, str)
        self.assertIsInstance(
            MediaPlayer.MPNowPlayingInfoPropertyPlaybackQueueIndex, str)
        self.assertIsInstance(
            MediaPlayer.MPNowPlayingInfoPropertyPlaybackQueueCount, str)
        self.assertIsInstance(
            MediaPlayer.MPNowPlayingInfoPropertyChapterNumber, str)
        self.assertIsInstance(MediaPlayer.MPNowPlayingInfoPropertyChapterCount,
                              str)
        self.assertIsInstance(MediaPlayer.MPNowPlayingInfoPropertyIsLiveStream,
                              str)
        self.assertIsInstance(
            MediaPlayer.MPNowPlayingInfoPropertyAvailableLanguageOptions, str)
        self.assertIsInstance(
            MediaPlayer.MPNowPlayingInfoPropertyCurrentLanguageOptions, str)
        self.assertIsInstance(MediaPlayer.MPNowPlayingInfoCollectionIdentifier,
                              str)
        self.assertIsInstance(
            MediaPlayer.MPNowPlayingInfoPropertyExternalContentIdentifier, str)
        self.assertIsInstance(
            MediaPlayer.MPNowPlayingInfoPropertyExternalUserProfileIdentifier,
            str)
        self.assertIsInstance(
            MediaPlayer.MPNowPlayingInfoPropertyPlaybackProgress, str)
        self.assertIsInstance(MediaPlayer.MPNowPlayingInfoPropertyMediaType,
                              str)
        self.assertIsInstance(MediaPlayer.MPNowPlayingInfoPropertyAssetURL,
                              str)

    @min_os_level("10.13")
    @expectedFailureIf(os_level_key(os_release()) < os_level_key("10.14")
                       )  # Documented for 10.13, but doesn't work there
    def testConstants10_13(self):
        self.assertIsInstance(
            MediaPlayer.MPNowPlayingInfoPropertyServiceIdentifier, str)

    @min_os_level("10.13.1")
    def testConstants10_13_1(self):
        self.assertIsInstance(
            MediaPlayer.MPNowPlayingInfoPropertyCurrentPlaybackDate, str)
    def testLongValue(self):
        v = NSNumber.numberWithUnsignedLongLong_(2**63 + 5000)
        self.assertIsInstance(v, int)

        if os_level_key(os_release()) < os_level_key("10.5"):
            self.assertEqual(v.description(), str(-(2**63) + 5000))
        else:
            self.assertEqual(v.description(), str(2**63 + 5000))

        self.assertIsNot(type(v), int)

        self.assertRaises(AttributeError, setattr, v, "x", 42)
class TestINIntentIdentifiers(TestCase):
    @min_os_level("10.12")
    @expectedFailureIf(
        os_level_key(os_release()) < os_level_key("10.14")
    )  # Documented to be available for 10.12, but not available
    def testConstants(self):
        self.assertIsInstance(Intents.INStartAudioCallIntentIdentifier, str)
        self.assertIsInstance(Intents.INStartVideoCallIntentIdentifier, str)
        self.assertIsInstance(Intents.INSearchCallHistoryIntentIdentifier, str)
        self.assertIsInstance(Intents.INSendMessageIntentIdentifier, str)
        self.assertIsInstance(Intents.INSearchForMessagesIntentIdentifier, str)
        self.assertIsInstance(Intents.INSetMessageAttributeIntentIdentifier,
                              str)
Exemple #8
0
    def testFunctions(self):
        err = CFNetwork.CFStreamError()
        err.error = (1 << 16) + 2

        v = CFNetwork.CFSocketStreamSOCKSGetErrorSubdomain(err)
        self.assertEqual(v, 1)

        v = CFNetwork.CFSocketStreamSOCKSGetError(err)
        self.assertEqual(v, 2)

        self.assertArgIsCFRetained(CFNetwork.CFStreamCreatePairWithSocketToCFHost, 3)
        self.assertArgIsCFRetained(CFNetwork.CFStreamCreatePairWithSocketToCFHost, 4)
        self.assertArgIsOut(CFNetwork.CFStreamCreatePairWithSocketToCFHost, 3)
        self.assertArgIsOut(CFNetwork.CFStreamCreatePairWithSocketToCFHost, 4)

        host = CFNetwork.CFHostCreateWithName(None, "connect.apple.com")
        rd, wr = CFNetwork.CFStreamCreatePairWithSocketToCFHost(
            None, host, 443, None, None
        )
        self.assertIsInstance(rd, CFNetwork.CFReadStreamRef)
        self.assertIsInstance(wr, CFNetwork.CFWriteStreamRef)

        if os_level_key(os_release()) < os_level_key("10.10"):
            self.assertResultIsBOOL(CFNetwork.CFSocketStreamPairSetSecurityProtocol)
            v = CFNetwork.CFSocketStreamPairSetSecurityProtocol(
                rd, wr, CFNetwork.kCFStreamSocketSecuritySSLv23
            )
            self.assertIsInstance(v, bool)

        self.assertArgIsCFRetained(
            CFNetwork.CFStreamCreatePairWithSocketToNetService, 2
        )
        self.assertArgIsCFRetained(
            CFNetwork.CFStreamCreatePairWithSocketToNetService, 3
        )
        self.assertArgIsOut(CFNetwork.CFStreamCreatePairWithSocketToNetService, 2)
        self.assertArgIsOut(CFNetwork.CFStreamCreatePairWithSocketToNetService, 3)
        service = CFNetwork.CFNetServiceCreate(
            None, "pyobjc.local", "ssh", "pyobjc.test.local", 9999
        )
        rd, wr = CFNetwork.CFStreamCreatePairWithSocketToNetService(
            None, service, None, None
        )
        self.assertIsInstance(rd, CFNetwork.CFReadStreamRef)
        self.assertIsInstance(wr, CFNetwork.CFWriteStreamRef)
Exemple #9
0
    def test_unknown_type(self):
        try:
            orig = pycoder.decode_dispatch[pycoder.kOP_GLOBAL]
            del pycoder.decode_dispatch[pycoder.kOP_GLOBAL]

            o = TestKeyedArchiveSimple
            buf = self.archiverClass.archivedDataWithRootObject_(o)

            if os_level_key(os_release()) >= os_level_key("10.11"):
                # On OSX 10.11 (un)archivers modify exceptions, which looses
                # enough information that PyObjC can no longer reconstruct
                # the correct Python exception
                exception = (objc.error, pickle.UnpicklingError)
            else:
                exception = pickle.UnpicklingError

            self.assertRaises(
                exception, self.unarchiverClass.unarchiveObjectWithData_, buf
            )

        finally:
            pycoder.decode_dispatch[pycoder.kOP_GLOBAL] = orig
Exemple #10
0
    def testFunctions(self):
        url = CFNetwork.CFURLCreateWithString(None, "http://www.python.org/",
                                              None)
        self.assertIsInstance(url, CFNetwork.CFURLRef)

        req = CFNetwork.CFHTTPMessageCreateRequest(None, "GET", url,
                                                   CFNetwork.kCFHTTPVersion1_1)
        self.assertIsInstance(req, CFNetwork.CFHTTPMessageRef)

        self.assertResultIsCFRetained(
            CFNetwork.CFReadStreamCreateForHTTPRequest)
        v = CFNetwork.CFReadStreamCreateForHTTPRequest(None, req)
        self.assertIsInstance(v, CFNetwork.CFReadStreamRef)

        with open("/dev/null", "w") as fp:
            fd_2 = os.dup(2)
            os.dup2(fp.fileno(), 2)

        try:
            # Avoid deprecation messages from CFNetwork

            self.assertResultIsCFRetained(
                CFNetwork.CFReadStreamCreateForStreamedHTTPRequest)
            v = CFNetwork.CFReadStreamCreateForStreamedHTTPRequest(
                None, req, v)
            self.assertIsInstance(v, CFNetwork.CFReadStreamRef)

            if os_level_key(os_release()) < os_level_key("10.15"):
                self.assertArgIsBOOL(
                    CFNetwork.CFHTTPReadStreamSetRedirectsAutomatically, 1)
                CFNetwork.CFHTTPReadStreamSetRedirectsAutomatically(v, True)

            if os_level_key(os_release()) < os_level_key("10.9"):
                CFNetwork.CFHTTPReadStreamSetProxy(v, "localhost", 8080)

        finally:
            os.dup2(fd_2, 2)
Exemple #11
0
class TestCLError(TestCase):
    @min_os_level("10.6")
    def testConstants(self):
        self.assertIsInstance(CoreLocation.kCLErrorDomain, str)

        self.assertEqual(CoreLocation.kCLErrorLocationUnknown, 0)
        self.assertEqual(CoreLocation.kCLErrorDenied, 1)
        self.assertEqual(CoreLocation.kCLErrorNetwork, 2)
        self.assertEqual(CoreLocation.kCLErrorHeadingFailure, 3)
        self.assertEqual(CoreLocation.kCLErrorRegionMonitoringDenied, 4)
        self.assertEqual(CoreLocation.kCLErrorRegionMonitoringFailure, 5)
        self.assertEqual(CoreLocation.kCLErrorRegionMonitoringSetupDelayed, 6)
        self.assertEqual(CoreLocation.kCLErrorRegionMonitoringResponseDelayed,
                         7)
        self.assertEqual(CoreLocation.kCLErrorGeocodeFoundPartialResult, 9)
        self.assertEqual(CoreLocation.kCLErrorDeferredFailed, 11)
        self.assertEqual(CoreLocation.kCLErrorDeferredNotUpdatingLocation, 12)
        self.assertEqual(CoreLocation.kCLErrorDeferredAccuracyTooLow, 13)
        self.assertEqual(CoreLocation.kCLErrorDeferredDistanceFiltered, 14)
        self.assertEqual(CoreLocation.kCLErrorDeferredCanceled, 15)
        self.assertEqual(CoreLocation.kCLErrorRangingUnavailable, 16)
        self.assertEqual(CoreLocation.kCLErrorRangingFailure, 17)
        self.assertEqual(CoreLocation.kCLErrorPromptDeclined, 18)

        if int(os.uname()[2].split(".")[0]) < 12:
            self.assertEqual(CoreLocation.kCLErrorGeocodeFoundNoResult, 7)
            self.assertEqual(CoreLocation.kCLErrorGeocodeCanceled, 8)
        else:
            self.assertEqual(CoreLocation.kCLErrorGeocodeFoundNoResult, 8)
            self.assertEqual(CoreLocation.kCLErrorGeocodeCanceled, 10)

    @min_os_level("10.7")
    @expectedFailureIf(os_level_key(os_release()) < os_level_key("10.13"))
    def testConstants10_7(self):
        self.assertIsInstance(CoreLocation.kCLErrorUserInfoAlternateRegionKey,
                              str)
Exemple #12
0
    def testFunctions(self):
        CoreServices.LSInit(CoreServices.kLSInitializeDefaults)
        CoreServices.LSTerm()

        url = CoreServices.CFURLCreateFromFileSystemRepresentation(
            None, self.bpath, len(self.bpath), True)
        self.assertIsInstance(url, CoreServices.CFURLRef)

        ok, info = CoreServices.LSCopyItemInfoForURL(
            url,
            CoreServices.kLSRequestExtension
            | CoreServices.kLSRequestTypeCreator,
            None,
        )
        self.assertEqual(ok, 0)
        self.assertIsInstance(info, CoreServices.LSItemInfoRecord)

        self.assertArgIsOut(CoreServices.LSGetExtensionInfo, 2)
        ok, info = CoreServices.LSGetExtensionInfo(len(self.path), self.path,
                                                   None)
        self.assertEqual(ok, 0)
        self.assertEqual(info, self.path.rindex(".") + 1)

        self.assertArgIsOut(CoreServices.LSCopyDisplayNameForURL, 1)
        self.assertArgIsCFRetained(CoreServices.LSCopyDisplayNameForURL, 1)
        ok, info = CoreServices.LSCopyDisplayNameForURL(url, None)
        self.assertEqual(ok, 0)
        self.assertIsInstance(info, str)

        self.assertArgIsBOOL(CoreServices.LSSetExtensionHiddenForURL, 1)
        ok = CoreServices.LSSetExtensionHiddenForURL(url, True)
        self.assertEqual(ok, 0)

        self.assertArgIsOut(CoreServices.LSCopyKindStringForURL, 1)
        self.assertArgIsCFRetained(CoreServices.LSCopyKindStringForURL, 1)
        ok, info = CoreServices.LSCopyKindStringForURL(url, None)
        self.assertEqual(ok, 0)
        self.assertIsInstance(info, str)

        self.assertArgIsOut(CoreServices.LSCopyKindStringForTypeInfo, 3)
        self.assertArgIsCFRetained(CoreServices.LSCopyKindStringForTypeInfo, 3)
        ok, info = CoreServices.LSCopyKindStringForTypeInfo(
            CoreServices.kLSUnknownType, CoreServices.kLSUnknownCreator, "jpg",
            None)
        self.assertEqual(ok, 0)
        self.assertIsInstance(info, str)

        self.assertArgIsOut(CoreServices.LSCopyKindStringForMIMEType, 1)
        self.assertArgIsCFRetained(CoreServices.LSCopyKindStringForMIMEType, 1)
        ok, info = CoreServices.LSCopyKindStringForMIMEType("text/plain", None)
        self.assertIsInstance(ok, int)
        # XXX: For some reason this fails sometimes...
        # self.assertEqual(ok, 0)
        self.assertIsInstance(info, (str, type(None)))

        self.assertArgIsOut(CoreServices.LSGetApplicationForInfo, 4)
        self.assertArgIsOut(CoreServices.LSGetApplicationForInfo, 5)
        self.assertArgIsCFRetained(CoreServices.LSGetApplicationForInfo, 5)

        ok, ref, info_url = CoreServices.LSGetApplicationForInfo(
            CoreServices.kLSUnknownType,
            CoreServices.kLSUnknownCreator,
            "txt",
            CoreServices.kLSRolesAll,
            None,
            None,
        )
        self.assertEqual(ok, 0)
        self.assertIsInstance(ref, objc.FSRef)
        self.assertIsInstance(info_url, CoreServices.CFURLRef)

        self.assertArgIsOut(CoreServices.LSCopyApplicationForMIMEType, 2)
        self.assertArgIsCFRetained(CoreServices.LSCopyApplicationForMIMEType,
                                   2)
        ok, info_url = CoreServices.LSCopyApplicationForMIMEType(
            "text/plain", CoreServices.kLSRolesAll, None)
        self.assertEqual(ok, 0)
        self.assertIsInstance(info_url, CoreServices.CFURLRef)

        self.assertArgIsOut(CoreServices.LSGetApplicationForURL, 2)
        self.assertArgIsOut(CoreServices.LSGetApplicationForURL, 3)
        self.assertArgIsCFRetained(CoreServices.LSGetApplicationForURL, 3)
        ok, ref, info_url = CoreServices.LSGetApplicationForURL(
            url, CoreServices.kLSRolesAll, None, None)
        self.assertEqual(ok, 0)
        self.assertIsInstance(ref, objc.FSRef)
        self.assertIsInstance(info_url, CoreServices.CFURLRef)

        self.assertArgIsOut(CoreServices.LSFindApplicationForInfo, 3)
        self.assertArgIsOut(CoreServices.LSFindApplicationForInfo, 4)
        self.assertArgIsCFRetained(CoreServices.LSFindApplicationForInfo, 4)
        ok, ref, info_url = CoreServices.LSFindApplicationForInfo(
            CoreServices.kLSUnknownCreator, None, "foo.app", None, None)
        # XXX: The code looks correct but fails, however the corresponding C code also fails.
        # self.assertEqual(ok, 0)
        self.assertIsInstance(ok, int)
        if ref is not None:
            self.assertIsInstance(ref, objc.FSRef)
        if info_url is not None:
            self.assertIsInstance(info_url, CoreServices.CFURLRef)

        self.assertArgIsOut(CoreServices.LSCanURLAcceptURL, 4)
        ok, status = CoreServices.LSCanURLAcceptURL(
            url, url, CoreServices.kLSRolesAll, CoreServices.kLSAcceptDefault,
            None)
        self.assertIsInstance(ok, int)
        self.assertIsInstance(status, bool)

        ok = CoreServices.LSRegisterURL(url, False)
        self.assertIsInstance(ok, int)

        v = CoreServices.LSCopyApplicationURLsForURL(url,
                                                     CoreServices.kLSRolesAll)
        self.assertIsInstance(v, CoreServices.CFArrayRef)
        for a in v:
            self.assertIsInstance(a, CoreServices.CFURLRef)

        default_role = CoreServices.LSCopyDefaultRoleHandlerForContentType(
            "public.plain-text", CoreServices.kLSRolesAll)
        if os_level_key(os_release()) < os_level_key("10.7"):
            if default_role is not None:
                self.assertIsInstance(default_role, str)
        else:
            self.assertIsInstance(default_role, str)

        v = CoreServices.LSCopyAllRoleHandlersForContentType(
            "public.plain-text", CoreServices.kLSRolesAll)
        self.assertIsInstance(v, CoreServices.CFArrayRef)
        for a in v:
            self.assertIsInstance(a, str)

        ok = CoreServices.LSSetDefaultRoleHandlerForContentType(
            "public.plain-text", CoreServices.kLSRolesAll, default_role)
        self.assertIsInstance(ok, int)

        v = CoreServices.LSGetHandlerOptionsForContentType("public.plain-text")
        self.assertIsInstance(v, int)

        ok = CoreServices.LSSetHandlerOptionsForContentType(
            "public.plain-text", v)
        self.assertIsInstance(ok, int)

        self.assertResultIsCFRetained(
            CoreServices.LSCopyDefaultHandlerForURLScheme)
        default_handler = CoreServices.LSCopyDefaultHandlerForURLScheme("http")
        if os_level_key(os_release()) < os_level_key("10.7"):
            if default_handler is not None:
                self.assertIsInstance(default_handler, str)
        else:
            self.assertIsInstance(default_handler, str)

        self.assertResultIsCFRetained(
            CoreServices.LSCopyAllHandlersForURLScheme)
        v = CoreServices.LSCopyAllHandlersForURLScheme("http")
        self.assertIsInstance(v, CoreServices.CFArrayRef)
        for a in v:
            self.assertIsInstance(a, str)

        ok = CoreServices.LSSetDefaultHandlerForURLScheme(
            "http", default_handler)
        self.assertIsInstance(ok, int)
Exemple #13
0
class ObjCRoundTrip(TestCase):
    # TODO: NSProxy

    def testNSObject(self):
        container = OC_TestIdentity.alloc().init()

        cls = objc.lookUpClass("NSObject")
        container.setStoredObjectToResultOf_on_("new", cls)

        v = container.storedObject()
        self.assertTrue(container.isSameObjectAsStored_(v), repr(v))

        container.setStoredObjectToResultOf_on_("class", cls)
        v = container.storedObject()
        self.assertTrue(container.isSameObjectAsStored_(v), repr(v))

    def testNSString(self):

        container = OC_TestIdentity.alloc().init()

        cls = objc.lookUpClass("NSObject")
        container.setStoredObjectToResultOf_on_("description", cls)
        v = container.storedObject()
        self.assertTrue(container.isSameObjectAsStored_(v), repr(v))
        self.assertTrue(isinstance(v, str))

        cls = objc.lookUpClass("NSMutableString")
        container.setStoredObjectToResultOf_on_("new", cls)
        v = container.storedObject()
        self.assertTrue(container.isSameObjectAsStored_(v), repr(v))
        self.assertTrue(isinstance(v, str))

    def testProtocol(self):
        container = OC_TestIdentity.alloc().init()

        container.setStoredObjectToAProtocol()
        v = container.storedObject()
        self.assertTrue(container.isSameObjectAsStored_(v), repr(v))
        self.assertTrue(isinstance(v, objc.formal_protocol))

    if sys.maxsize < 2**32 and os_level_key(
            os_release()) < os_level_key("10.7"):

        def testObject(self):
            container = OC_TestIdentity.alloc().init()
            cls = objc.lookUpClass("Object")
            container.setStoredObjectAnInstanceOfClassic_(cls)
            v = container.storedObject()
            self.assertTrue(container.isSameObjectAsStored_(v), repr(v))
            self.assertTrue(isinstance(v, cls))

    def testNSNumber(self):
        container = OC_TestIdentity.alloc().init()

        container.setStoredObjectToInteger_(10)
        v = container.storedObject()
        self.assertTrue(container.isSameObjectAsStored_(v), repr(v))

        container.setStoredObjectToInteger_(-40)
        v = container.storedObject()
        self.assertTrue(container.isSameObjectAsStored_(v), repr(v))

        container.setStoredObjectToUnsignedInteger_(40)
        v = container.storedObject()
        self.assertTrue(container.isSameObjectAsStored_(v), repr(v))

        container.setStoredObjectToUnsignedInteger_(2**32 - 4)
        v = container.storedObject()
        self.assertTrue(container.isSameObjectAsStored_(v), repr(v))

        if sys.maxsize < 2**32:
            container.setStoredObjectToLongLong_(sys.maxsize * 2)
            v = container.storedObject()
            self.assertTrue(container.isSameObjectAsStored_(v), repr(v))

        container.setStoredObjectToLongLong_(-sys.maxsize)
        v = container.storedObject()
        self.assertTrue(container.isSameObjectAsStored_(v), repr(v))

        container.setStoredObjectToUnsignedLongLong_(sys.maxsize * 2)
        v = container.storedObject()
        self.assertTrue(container.isSameObjectAsStored_(v), repr(v))

        container.setStoredObjectToFloat_(10.0)
        v = container.storedObject()
        self.assertTrue(container.isSameObjectAsStored_(v), repr(v))

        container.setStoredObjectToDouble_(9999.0)
        v = container.storedObject()
        self.assertTrue(container.isSameObjectAsStored_(v), repr(v))

    def testNSDecimalNumber(self):
        container = OC_TestIdentity.alloc().init()
        cls = objc.lookUpClass("NSDecimalNumber")
        container.setStoredObjectToResultOf_on_("zero", cls)
        v = container.storedObject()
        self.assertTrue(container.isSameObjectAsStored_(v), repr(v))
objc.registerMetaDataForSelector(
    b"NSKeyedArchiver",
    b"archivedDataWithRootObject:requiringSecureCoding:error:",
    {
        "arguments": {
            2 + 1: {
                "type": objc._C_NSBOOL
            },
            2 + 2: {
                "type_modifier": objc._C_OUT
            },
        }
    },
)

if os_level_key(os_release()) >= os_level_key("10.13"):
    # Secure coding was introduced in 10.13.

    class TestNSKeyedArchivingInterop(TestCase):
        @classmethod
        def setUpClass(cls):
            src = os.path.join(MYDIR, "dump-nsarchive-securecoding.m")
            dst = cls.progpath = os.path.join(MYDIR,
                                              "dump-nsarchive-securecoding")

            subprocess.check_call([
                "cc",
                "-o",
                dst,
                src,
                "-framework",
Exemple #15
0
class TestArchiveNative(TestCase):
    # Self-referential graphs with collections are broken
    # in Cocoa, these are tested here because this behavior
    # is mentioned in PyObjC's documentation, that documentation
    # needs to be updated when these tests start to pass.
    #
    # Filed RADAR #13429469 for this.

    def dumps(self, arg, proto=0, fast=0):
        # Ignore proto and fast
        return NSArchiver.archivedDataWithRootObject_(arg)

    def loads(self, buf):
        return NSUnarchiver.unarchiveObjectWithData_(buf)

    @expectedFailure
    def test_self_referential_array(self):
        s1 = NSString.stringWithString_("hello")
        s2 = NSString.stringWithString_("world")

        a = NSMutableArray.arrayWithArray_([s1, s2])
        a.addObject_(a)

        buf = self.dumps(a)
        self.assertIsInstance(buf, NSData)

        b = self.loads(buf)
        self.assertEqual(b[0], s1)
        self.assertEqual(b[1], s2)
        self.assertIs(b[2], b)

    @expectedFailure
    def test_self_referential_dictionary(self):
        s1 = NSString.stringWithString_("hello")
        s2 = NSString.stringWithString_("world")

        a = NSMutableDictionary.dictionary()
        a.setValue_forKey_(s1, s2)
        a.setValue_forKey_(a, s1)

        buf = self.dumps(a)
        self.assertIsInstance(buf, NSData)

        b = self.loads(buf)
        self.assertEqual(b.valueForKey_(s2), s1)
        self.assertIs(b.valueForKey_(s1), b)

    def test_numbers(self):
        a = 1
        buf = self.dumps(a)
        self.assertIsInstance(buf, NSData)
        b = self.loads(buf)
        self.assertEqual(a, b)
        self.assertIsInstance(b, int)

        a = 1.5
        buf = self.dumps(a)
        self.assertIsInstance(buf, NSData)
        b = self.loads(buf)
        self.assertEqual(a, b)
        self.assertIsInstance(b, float)

        a = float_subclass(1.5)
        buf = self.dumps(a)
        self.assertIsInstance(buf, NSData)
        b = self.loads(buf)
        self.assertEqual(a, b)
        self.assertIsInstance(b, float_subclass)

    @expectedFailureIf(os_level_key(os_release()) <= os_level_key("10.6"))
    def test_more_state(self):
        a = with_getstate(1.5)
        self.assertEqual(a.value, 1.5)
        buf = self.dumps(a)
        self.assertIsInstance(buf, NSData)
        b = self.loads(buf)
        self.assertIsInstance(b, with_getstate)
        self.assertEqual(a.value, b.value)
        self.assertIsInstance(b.value, float)

        a = with_getstate(42)
        self.assertEqual(a.value, 42)
        buf = self.dumps(a)
        self.assertIsInstance(buf, NSData)
        b = self.loads(buf)
        self.assertIsInstance(b, with_getstate)
        self.assertEqual(a.value, b.value)
        self.assertIsInstance(b.value, int)

        a = with_getstate(1 << 100)
        self.assertEqual(a.value, 1 << 100)
        buf = self.dumps(a)
        self.assertIsInstance(buf, NSData)
        b = self.loads(buf)
        self.assertIsInstance(b, with_getstate)
        self.assertEqual(a.value, b.value)
        self.assertIsInstance(b.value, int)

        a = with_getstate((1, 2))
        self.assertEqual(a.value, (1, 2))
        buf = self.dumps(a)
        self.assertIsInstance(buf, NSData)
        b = self.loads(buf)
        self.assertIsInstance(b, with_getstate)
        self.assertEqual(a.value, b.value)
        self.assertIsInstance(b.value, tuple)

        a = only_getstate(
            {"a": 42, "b": 9, NSString("otherstr"): "b"},
            {"c": 4, "d": 7, 42: "b", "a": 1, NSString("nsstr"): NSString("xx")},
        )
        buf = self.dumps(a)
        self.assertIsInstance(buf, NSData)
        b = self.loads(buf)
        self.assertIsInstance(b, only_getstate)
        self.assertEqual(
            b.__dict__,
            {"a": 42, "b": 9, "c": 4, "d": 7, 42: "b", "nsstr": "xx", "otherstr": "b"},
        )
        for k in b.__dict__:
            self.assertNotIsInstance(k, objc.pyobjc_unicode)
            self.assertNotIsInstance(k, bytes)

        a = with_reduce_func([1, 2], (3, 4), {"a": 4}, {"d", "e"}, frozenset(["f"]), id)
        buf = self.dumps(a)
        self.assertIsInstance(buf, NSData)
        b = self.loads(buf)
        self.assertIsInstance(b, with_reduce_func)
        self.assertEqual(a.args, b.args)
        self.assertIsInstance(b.args[0], list)
        self.assertIsInstance(b.args[1], tuple)
        self.assertIsInstance(b.args[2], dict)
        self.assertIsInstance(b.args[3], set)
        self.assertIsInstance(b.args[4], frozenset)
Exemple #16
0
    def testResources(self):
        url = CoreFoundation.CFURLCreateWithFileSystemPath(
            None,
            "/System/Library/Frameworks/Foundation.framework",
            CoreFoundation.kCFURLPOSIXPathStyle,
            True,
        )
        bundle = CoreFoundation.CFBundleCreate(None, url)
        self.assertIsInstance(bundle, CoreFoundation.CFBundleRef)
        url = CoreFoundation.CFURLCreateWithFileSystemPath(
            None,
            "/System/Library/Frameworks/Tcl.framework",
            CoreFoundation.kCFURLPOSIXPathStyle,
            True,
        )
        bundle2 = CoreFoundation.CFBundleCreate(None, url)
        self.assertIsInstance(bundle2, CoreFoundation.CFBundleRef)
        url = CoreFoundation.CFBundleCopyResourceURL(
            bundle, "Formatter", "strings", None
        )
        self.assertIsInstance(url, CoreFoundation.CFURLRef)
        url = CoreFoundation.CFBundleCopyResourceURL(
            bundle, "Formatter", "strings", "helloworld.lproj"
        )
        self.assertIs(url, None)
        array = CoreFoundation.CFBundleCopyResourceURLsOfType(bundle, "strings", None)
        self.assertIsNot(array, None)
        self.assertIsInstance(array, CoreFoundation.CFArrayRef)
        val = CoreFoundation.CFBundleCopyLocalizedString(
            bundle, "Err640.f", "value", "FoundationErrors"
        )
        self.assertIsInstance(val, str)
        self.assertNotEqual(val, "value")
        CoreFoundation.CFCopyLocalizedString("python", "error")
        CoreFoundation.CFCopyLocalizedStringFromTable("pyobjc", "python", "error")
        CoreFoundation.CFCopyLocalizedStringFromTableInBundle(
            "pyobjc", "python", bundle, "comment"
        )
        CoreFoundation.CFCopyLocalizedStringWithDefaultValue(
            "pyobjc", "python", bundle, "default", "comment"
        )

        array = CoreFoundation.CFBundleCopyBundleLocalizations(bundle)
        self.assertIsNot(array, None)
        self.assertIsInstance(array, CoreFoundation.CFArrayRef)
        arr2 = CoreFoundation.CFBundleCopyPreferredLocalizationsFromArray(array)
        self.assertIsNot(arr2, None)
        self.assertIsInstance(arr2, CoreFoundation.CFArrayRef)
        arr2 = CoreFoundation.CFBundleCopyLocalizationsForPreferences(array, None)
        self.assertIsNot(arr2, None)
        self.assertIsInstance(arr2, CoreFoundation.CFArrayRef)
        url = CoreFoundation.CFBundleCopyResourceURLForLocalization(
            bundle, "Formatter", "strings", None, "Dutch"
        )
        if url is None:
            url = CoreFoundation.CFBundleCopyResourceURLForLocalization(
                bundle, "Formatter", "strings", None, "nl"
            )
        if url is None:
            url = CoreFoundation.CFBundleCopyResourceURLForLocalization(
                bundle, "Formatter", "strings", None, "en"
            )
        self.assertIsInstance(url, CoreFoundation.CFURLRef)

        array = CoreFoundation.CFBundleCopyResourceURLsOfTypeForLocalization(
            bundle, "strings", None, "Dutch"
        )
        self.assertIsNot(array, None)
        self.assertIsInstance(array, CoreFoundation.CFArrayRef)
        url = CoreFoundation.CFBundleCopyExecutableURL(bundle)
        self.assertIsInstance(url, CoreFoundation.CFURLRef)
        array = CoreFoundation.CFBundleCopyExecutableArchitectures(bundle)
        if os_level_key(os_release()) >= os_level_key("10.16"):
            self.assertIs(array, None)
        else:
            self.assertIsNot(array, None)
            self.assertIsInstance(array, CoreFoundation.CFArrayRef)
        self.assertArgIsOut(CoreFoundation.CFBundlePreflightExecutable, 1)
        ok, error = CoreFoundation.CFBundlePreflightExecutable(bundle, None)
        self.assertTrue((ok is True) or (ok is False))
        if ok:
            self.assertIs(error, None)
        else:
            self.assertIsInstance(error, CoreFoundation.CFErrorRef)
        self.assertArgIsOut(CoreFoundation.CFBundleLoadExecutableAndReturnError, 1)
        ok, error = CoreFoundation.CFBundleLoadExecutableAndReturnError(bundle2, None)
        self.assertTrue((ok is True) or (ok is False))
        if ok:
            self.assertIs(error, None)
        else:
            self.assertIsInstance(error, CoreFoundation.CFErrorRef)
        ok = CoreFoundation.CFBundleLoadExecutable(bundle2)
        self.assertTrue(ok)

        ok = CoreFoundation.CFBundleIsExecutableLoaded(bundle2)
        self.assertTrue(ok)

        CoreFoundation.CFBundleUnloadExecutable(bundle2)
        ok = CoreFoundation.CFBundleIsExecutableLoaded(bundle2)
        # self.assertFalse(ok)
        ok = CoreFoundation.CFBundleLoadExecutable(bundle2)
        self.assertTrue(ok)

        try:
            CoreFoundation.CFBundleGetFunctionPointerForName
        except AttributeError:
            pass
        else:
            self.fail("CFBundleGetFunctionPointerForName")

        try:
            CoreFoundation.CFBundleGetFunctionPointersForNames
        except AttributeError:
            pass
        else:
            self.fail("CFBundleGetFunctionPointersForNames")

        try:
            CoreFoundation.CFBundleGetDataPointerForName
        except AttributeError:
            pass
        else:
            self.fail("CFBundleGetDataPointerForName")

        try:
            CoreFoundation.CFBundleGetDataPointersForNames
        except AttributeError:
            pass
        else:
            self.fail("CFBundleGetDataPointersForNames")

        url = CoreFoundation.CFBundleCopyAuxiliaryExecutableURL(bundle, "Foundation")
        self.assertIsInstance(url, CoreFoundation.CFURLRef)
        map_id = CoreFoundation.CFBundleOpenBundleResourceMap(bundle)
        self.assertIsInstance(map_id, int)
        CoreFoundation.CFBundleCloseBundleResourceMap(bundle, map_id)

        err, id1, id2 = CoreFoundation.CFBundleOpenBundleResourceFiles(
            bundle, None, None
        )
        self.assertIsInstance(err, int)
        self.assertIsInstance(id1, int)
        self.assertIsInstance(id2, int)
        if id1 != -1:
            CoreFoundation.CFBundleCloseBundleResourceMap(bundle, id1)
        if id2 != -1:
            CoreFoundation.CFBundleCloseBundleResourceMap(bundle, id2)
Exemple #17
0
    def test_dyld_library(self):
        for k in (
                "DYLD_LIBRARY_PATH",
                "DYLD_FALLBACK_LIBRARY_PATH",
                "DYLD_IMAGE_SUFFIX",
        ):
            if k in os.environ:
                del os.environ[k]

        orig = os.path.exists
        try:
            os.path.exists = lambda fn: lst.append(fn)

            lst = []
            self.assertRaises(
                ValueError,
                dyld.dyld_library,
                "/usr/lib/libSystem.dylib",
                "libXSystem.dylib",
            )
            self.assertEqual(
                lst,
                [
                    "/usr/lib/libSystem.dylib",
                    os.path.expanduser("~/lib/libXSystem.dylib"),
                    "/usr/local/lib/libXSystem.dylib",
                    "/lib/libXSystem.dylib",
                    "/usr/lib/libXSystem.dylib",
                ],
            )

            os.environ["DYLD_IMAGE_SUFFIX"] = "_debug"
            lst = []
            self.assertRaises(
                ValueError,
                dyld.dyld_library,
                "/usr/lib/libSystem.dylib",
                "libXSystem.dylib",
            )
            self.assertEqual(
                lst,
                [
                    "/usr/lib/libSystem_debug.dylib",
                    "/usr/lib/libSystem.dylib",
                    os.path.expanduser("~/lib/libXSystem_debug.dylib"),
                    os.path.expanduser("~/lib/libXSystem.dylib"),
                    "/usr/local/lib/libXSystem_debug.dylib",
                    "/usr/local/lib/libXSystem.dylib",
                    "/lib/libXSystem_debug.dylib",
                    "/lib/libXSystem.dylib",
                    "/usr/lib/libXSystem_debug.dylib",
                    "/usr/lib/libXSystem.dylib",
                ],
            )

            del os.environ["DYLD_IMAGE_SUFFIX"]

            os.environ["DYLD_LIBRARY_PATH"] = "/slib:/usr/slib"
            lst = []
            self.assertRaises(
                ValueError,
                dyld.dyld_library,
                "/usr/lib/libSystem.dylib",
                "libXSystem.dylib",
            )
            self.assertEqual(
                lst,
                [
                    "/slib/libXSystem.dylib",
                    "/usr/slib/libXSystem.dylib",
                    "/usr/lib/libSystem.dylib",
                    os.path.expanduser("~/lib/libXSystem.dylib"),
                    "/usr/local/lib/libXSystem.dylib",
                    "/lib/libXSystem.dylib",
                    "/usr/lib/libXSystem.dylib",
                ],
            )
            del os.environ["DYLD_LIBRARY_PATH"]

            os.environ["DYLD_FALLBACK_LIBRARY_PATH"] = "/slib:/usr/slib"
            lst = []
            self.assertRaises(
                ValueError,
                dyld.dyld_library,
                "/usr/lib/libSystem.dylib",
                "libXSystem.dylib",
            )
            self.assertEqual(
                lst,
                [
                    "/usr/lib/libSystem.dylib",
                    "/slib/libXSystem.dylib",
                    "/usr/slib/libXSystem.dylib",
                ],
            )
            del os.environ["DYLD_FALLBACK_LIBRARY_PATH"]

            os.environ["DYLD_LIBRARY_PATH"] = "/lib2:/lib3"
            os.environ["DYLD_FALLBACK_LIBRARY_PATH"] = "/lib4:/lib5"
            os.environ["DYLD_IMAGE_SUFFIX"] = "_profile"

            lst = []
            self.assertRaises(
                ValueError,
                dyld.dyld_library,
                "/usr/lib/libSystem.dylib",
                "libXSystem.dylib",
            )
            self.assertEqual(
                lst,
                [
                    "/lib2/libXSystem_profile.dylib",
                    "/lib2/libXSystem.dylib",
                    "/lib3/libXSystem_profile.dylib",
                    "/lib3/libXSystem.dylib",
                    "/usr/lib/libSystem_profile.dylib",
                    "/usr/lib/libSystem.dylib",
                    "/lib4/libXSystem_profile.dylib",
                    "/lib4/libXSystem.dylib",
                    "/lib5/libXSystem_profile.dylib",
                    "/lib5/libXSystem.dylib",
                ],
            )
            del os.environ["DYLD_LIBRARY_PATH"]
            del os.environ["DYLD_FALLBACK_LIBRARY_PATH"]
            del os.environ["DYLD_IMAGE_SUFFIX"]

        finally:
            os.path.exists = orig

        self.assertEqual(
            dyld.dyld_library("/usr/lib/libSystem.dylib", "libXSystem.dylib"),
            "/usr/lib/libSystem.dylib",
        )

        # When the 'command line tools for xcode' are not installed
        # there is no debug version of libsystem in the system wide
        # library directory. In that case we look in the SDK instead.
        if os.path.exists("/usr/lib/libSystem_debug.dylib"):
            os.environ["DYLD_IMAGE_SUFFIX"] = "_debug"
            self.assertEqual(
                dyld.dyld_library("/usr/lib/libSystem.dylib",
                                  "libSystem.dylib"),
                "/usr/lib/libSystem_debug.dylib",
            )

        else:
            p = subprocess.check_output(["xcrun", "--show-sdk-path"]).strip()
            os.environ["DYLD_LIBRARY_PATH"] = os.path.join(
                p.decode("utf-8"), "usr", "lib")
            os.environ["DYLD_IMAGE_SUFFIX"] = "_debug"

            # The OSX 10.11 SDK no longer contains ".dylib" files, which
            # makes the test useless when running up-to-date
            # tools on OSX 10.10 or later.
            if os_level_key(os_release()) < os_level_key("10.10"):
                self.assertEqual(
                    dyld.dyld_library("/usr/lib/libSystem.dylib",
                                      "libSystem.dylib"),
                    os.path.join(os.environ["DYLD_LIBRARY_PATH"],
                                 "libSystem_debug.dylib"),
                )
Exemple #18
0
class TestABGlobals(TestCase):
    @min_os_level("10.12")
    def testConstants10_12(self):
        self.assertIsInstance(AddressBook.kABOrganizationPhoneticProperty, str)

    @min_os_level("10.9")
    def testConstants10_9(self):
        self.assertIsInstance(AddressBook.kABSocialProfileServiceTencentWeibo, str)

    @min_os_level("10.10")
    def testConstants10_10(self):
        self.assertIsInstance(AddressBook.kABSocialProfileServiceYelp, str)
        self.assertIsInstance(AddressBook.kABAlternateBirthdayComponentsProperty, str)

    @min_os_level("10.8")
    def testConstants10_8(self):
        self.assertIsInstance(AddressBook.kABSocialProfileServiceSinaWeibo, str)

    @min_os_level("10.7")
    def testConstants10_7(self):
        self.assertIsInstance(AddressBook.kABMobileMeLabel, str)
        self.assertIsInstance(AddressBook.kABBirthdayComponentsProperty, str)
        self.assertIsInstance(AddressBook.kABOtherDateComponentsProperty, str)
        self.assertIsInstance(AddressBook.kABInstantMessageProperty, str)
        self.assertIsInstance(AddressBook.kABInstantMessageUsernameKey, str)
        self.assertIsInstance(AddressBook.kABInstantMessageServiceKey, str)
        self.assertIsInstance(AddressBook.kABInstantMessageServiceAIM, str)
        self.assertIsInstance(AddressBook.kABInstantMessageServiceFacebook, str)
        self.assertIsInstance(AddressBook.kABInstantMessageServiceGaduGadu, str)
        self.assertIsInstance(AddressBook.kABInstantMessageServiceGoogleTalk, str)
        self.assertIsInstance(AddressBook.kABInstantMessageServiceICQ, str)
        self.assertIsInstance(AddressBook.kABInstantMessageServiceJabber, str)
        self.assertIsInstance(AddressBook.kABInstantMessageServiceMSN, str)
        self.assertIsInstance(AddressBook.kABInstantMessageServiceQQ, str)
        self.assertIsInstance(AddressBook.kABInstantMessageServiceSkype, str)
        self.assertIsInstance(AddressBook.kABInstantMessageServiceYahoo, str)
        self.assertIsInstance(AddressBook.kABSocialProfileProperty, str)
        self.assertIsInstance(AddressBook.kABSocialProfileURLKey, str)
        self.assertIsInstance(AddressBook.kABSocialProfileUsernameKey, str)
        self.assertIsInstance(AddressBook.kABSocialProfileUserIdentifierKey, str)
        self.assertIsInstance(AddressBook.kABSocialProfileServiceKey, str)
        self.assertIsInstance(AddressBook.kABSocialProfileServiceTwitter, str)
        self.assertIsInstance(AddressBook.kABSocialProfileServiceFacebook, str)
        self.assertIsInstance(AddressBook.kABSocialProfileServiceLinkedIn, str)
        self.assertIsInstance(AddressBook.kABSocialProfileServiceFlickr, str)
        self.assertIsInstance(AddressBook.kABSocialProfileServiceMySpace, str)

    @min_os_level("10.6")
    def testConstants10_6(self):
        self.assertIsInstance(AddressBook.kABPhoneiPhoneLabel, str)
        self.assertEqual(AddressBook.kABShowAsResource, 2)
        self.assertEqual(AddressBook.kABShowAsRoom, 3)

    @min_os_level("10.5")
    def testConstants10_5(self):
        self.assertIsInstance(AddressBook.kABCalendarURIsProperty, str)

    @expectedFailureIf(os_level_key(os_release()) < os_level_key("10.14"))
    def testConstants_10_7_broken(self):
        self.assertIsInstance(AddressBook.kABEmailMobileMeLabel, str)
        self.assertIsInstance(AddressBook.kABAIMMobileMeLabel, str)

    def testConstants(self):
        self.assertEqual(AddressBook.kABShowAsMask, 0o7)
        self.assertEqual(AddressBook.kABShowAsPerson, 0o0)
        self.assertEqual(AddressBook.kABShowAsCompany, 0o1)
        self.assertEqual(AddressBook.kABNameOrderingMask, 0o70)
        self.assertEqual(AddressBook.kABDefaultNameOrdering, 0o0)
        self.assertEqual(AddressBook.kABFirstNameFirst, 0o40)
        self.assertEqual(AddressBook.kABLastNameFirst, 0o20)

        self.assertIsInstance(AddressBook.kABUIDProperty, str)
        self.assertIsInstance(AddressBook.kABCreationDateProperty, str)
        self.assertIsInstance(AddressBook.kABModificationDateProperty, str)
        self.assertIsInstance(AddressBook.kABFirstNameProperty, str)
        self.assertIsInstance(AddressBook.kABLastNameProperty, str)
        self.assertIsInstance(AddressBook.kABFirstNamePhoneticProperty, str)
        self.assertIsInstance(AddressBook.kABLastNamePhoneticProperty, str)
        self.assertIsInstance(AddressBook.kABNicknameProperty, str)
        self.assertIsInstance(AddressBook.kABMaidenNameProperty, str)
        self.assertIsInstance(AddressBook.kABBirthdayProperty, str)

        self.assertIsInstance(AddressBook.kABOrganizationProperty, str)
        self.assertIsInstance(AddressBook.kABJobTitleProperty, str)
        self.assertIsInstance(AddressBook.kABHomePageProperty, str)
        self.assertIsInstance(AddressBook.kABURLsProperty, str)
        self.assertIsInstance(AddressBook.kABHomePageLabel, str)
        self.assertIsInstance(AddressBook.kABEmailProperty, str)
        self.assertIsInstance(AddressBook.kABEmailWorkLabel, str)
        self.assertIsInstance(AddressBook.kABEmailHomeLabel, str)
        self.assertIsInstance(AddressBook.kABAddressProperty, str)
        self.assertIsInstance(AddressBook.kABAddressStreetKey, str)
        self.assertIsInstance(AddressBook.kABAddressCityKey, str)
        self.assertIsInstance(AddressBook.kABAddressStateKey, str)
        self.assertIsInstance(AddressBook.kABAddressZIPKey, str)
        self.assertIsInstance(AddressBook.kABAddressCountryKey, str)
        self.assertIsInstance(AddressBook.kABAddressCountryCodeKey, str)
        self.assertIsInstance(AddressBook.kABAddressHomeLabel, str)
        self.assertIsInstance(AddressBook.kABAddressWorkLabel, str)
        self.assertIsInstance(AddressBook.kABOtherDatesProperty, str)
        self.assertIsInstance(AddressBook.kABAnniversaryLabel, str)
        self.assertIsInstance(AddressBook.kABRelatedNamesProperty, str)
        self.assertIsInstance(AddressBook.kABFatherLabel, str)
        self.assertIsInstance(AddressBook.kABMotherLabel, str)
        self.assertIsInstance(AddressBook.kABParentLabel, str)
        self.assertIsInstance(AddressBook.kABBrotherLabel, str)
        self.assertIsInstance(AddressBook.kABSisterLabel, str)
        self.assertIsInstance(AddressBook.kABChildLabel, str)
        self.assertIsInstance(AddressBook.kABFriendLabel, str)
        self.assertIsInstance(AddressBook.kABSpouseLabel, str)
        self.assertIsInstance(AddressBook.kABPartnerLabel, str)
        self.assertIsInstance(AddressBook.kABAssistantLabel, str)
        self.assertIsInstance(AddressBook.kABManagerLabel, str)
        self.assertIsInstance(AddressBook.kABDepartmentProperty, str)
        self.assertIsInstance(AddressBook.kABPersonFlags, str)
        self.assertIsInstance(AddressBook.kABPhoneProperty, str)
        self.assertIsInstance(AddressBook.kABPhoneWorkLabel, str)
        self.assertIsInstance(AddressBook.kABPhoneHomeLabel, str)
        self.assertIsInstance(AddressBook.kABPhoneMobileLabel, str)
        self.assertIsInstance(AddressBook.kABPhoneMainLabel, str)
        self.assertIsInstance(AddressBook.kABPhoneHomeFAXLabel, str)
        self.assertIsInstance(AddressBook.kABPhoneWorkFAXLabel, str)
        self.assertIsInstance(AddressBook.kABPhonePagerLabel, str)
        self.assertIsInstance(AddressBook.kABAIMInstantProperty, str)
        self.assertIsInstance(AddressBook.kABAIMWorkLabel, str)
        self.assertIsInstance(AddressBook.kABAIMHomeLabel, str)
        self.assertIsInstance(AddressBook.kABJabberInstantProperty, str)
        self.assertIsInstance(AddressBook.kABJabberWorkLabel, str)
        self.assertIsInstance(AddressBook.kABJabberHomeLabel, str)
        self.assertIsInstance(AddressBook.kABMSNInstantProperty, str)
        self.assertIsInstance(AddressBook.kABMSNWorkLabel, str)
        self.assertIsInstance(AddressBook.kABMSNHomeLabel, str)
        self.assertIsInstance(AddressBook.kABYahooInstantProperty, str)
        self.assertIsInstance(AddressBook.kABYahooWorkLabel, str)
        self.assertIsInstance(AddressBook.kABYahooHomeLabel, str)
        self.assertIsInstance(AddressBook.kABICQInstantProperty, str)
        self.assertIsInstance(AddressBook.kABICQWorkLabel, str)
        self.assertIsInstance(AddressBook.kABICQHomeLabel, str)
        self.assertIsInstance(AddressBook.kABNoteProperty, str)
        self.assertIsInstance(AddressBook.kABMiddleNameProperty, str)
        self.assertIsInstance(AddressBook.kABMiddleNamePhoneticProperty, str)
        self.assertIsInstance(AddressBook.kABTitleProperty, str)
        self.assertIsInstance(AddressBook.kABSuffixProperty, str)
        self.assertIsInstance(AddressBook.kABGroupNameProperty, str)
        self.assertIsInstance(AddressBook.kABWorkLabel, str)
        self.assertIsInstance(AddressBook.kABHomeLabel, str)
        self.assertIsInstance(AddressBook.kABOtherLabel, str)
        self.assertIsInstance(AddressBook.kABDatabaseChangedNotification, str)
        self.assertIsInstance(AddressBook.kABDatabaseChangedExternallyNotification, str)
        self.assertIsInstance(AddressBook.kABInsertedRecords, str)
        self.assertIsInstance(AddressBook.kABUpdatedRecords, str)
        self.assertIsInstance(AddressBook.kABDeletedRecords, str)

    def testFunctions(self):
        v = AddressBook.ABLocalizedPropertyOrLabel(AddressBook.kABAssistantLabel)
        self.assertIsInstance(v, str)
Exemple #19
0
    def test_misc_globals(self):
        global mystr
        orig = mystr
        try:
            del mystr

            o = orig("hello")

            data = NSMutableData.alloc().init()
            archiver = self.archiverClass.alloc().initForWritingWithMutableData_(data)
            self.assertRaises(pickle.PicklingError, archiver.encodeRootObject_, o)

            if self.archiverClass is NSKeyedArchiver:
                archiver.finishEncoding()

        finally:
            mystr = orig

        try:
            mystr = None

            o = orig("hello")
            data = NSMutableData.alloc().init()
            archiver = self.archiverClass.alloc().initForWritingWithMutableData_(data)
            self.assertRaises(pickle.PicklingError, archiver.encodeRootObject_, o)
            if self.archiverClass is NSKeyedArchiver:
                archiver.finishEncoding()

        finally:
            mystr = orig  # noqa: F841

        try:
            copyreg.add_extension(
                a_newstyle_class.__module__, a_newstyle_class.__name__, 42
            )
            self.assertIn(
                (a_newstyle_class.__module__, a_newstyle_class.__name__),
                copyreg._extension_registry,
            )

            o = a_newstyle_class
            buf = self.archiverClass.archivedDataWithRootObject_(o)
            self.assertIsInstance(buf, NSData)
            v = self.unarchiverClass.unarchiveObjectWithData_(buf)
            self.assertIs(v, o)

            self.assertIsInstance(buf, NSData)
            v = self.unarchiverClass.unarchiveObjectWithData_(buf)
            self.assertIs(v, o)

            copyreg.remove_extension(
                a_newstyle_class.__module__, a_newstyle_class.__name__, 42
            )

            if os_level_key(os_release()) >= os_level_key("10.11"):
                # On OSX 10.11 (un)archivers modify exceptions, which looses
                # enough information that PyObjC can no longer reconstruct
                # the correct Python exception
                exception = (objc.error, ValueError)
            else:
                exception = ValueError
            self.assertRaises(
                exception, self.unarchiverClass.unarchiveObjectWithData_, buf
            )

        finally:
            try:
                copyreg.remove_extension(
                    a_newstyle_class.__module__, a_newstyle_class.__name__, 42
                )
            except ValueError:
                pass

        def f():
            pass

        del f.__module__
        if hasattr(f, "__qualname__"):
            f.__qualname__ = f.__name__
        try:
            sys.f = f

            buf = self.archiverClass.archivedDataWithRootObject_(f)
            self.assertIsInstance(buf, NSData)
            v = self.unarchiverClass.unarchiveObjectWithData_(buf)
            self.assertIs(v, f)

        finally:
            del f