示例#1
0
    def testFunctions(self):

        err = SystemConfiguration.SCError()
        self.assertIsInstance(err, int)

        err = SystemConfiguration.SCErrorString(
            SystemConfiguration.kSCStatusNoLink)
        self.assertIsInstance(err, bytes)
示例#2
0
def realms():
    if not bound():
        raise NotBound
    store = SystemConfiguration.SCDynamicStoreCreate(None, 'default-realms',
                                                     None, None)
    realms = SystemConfiguration.SCDynamicStoreCopyValue(
        store, 'Kerberos-Default-Realms')
    return list(realms) if realms else None
示例#3
0
    def testFunctions(self):
        r, flags = SystemConfiguration.SCNetworkCheckReachabilityByName(
            b"www.python.org", None
        )
        self.assertTrue(r is True or r is False)
        self.assertTrue(isinstance(flags, int))

        r = SystemConfiguration.SCNetworkInterfaceRefreshConfiguration("en0")
        self.assertTrue(r is True or r is False)
示例#4
0
 def setup_helper():
     sc = SystemConfiguration.SCDynamicStoreCreate(None, "f5vpn-login", None, None)
     d = SystemConfiguration.NSMutableDictionary.new()
     d[u'ServerAddresses'] = dns_servers
     if override_gateway:
         d[u'SearchDomains'] = dns_domains
     else:
         d[u'SupplementalMatchDomains'] = dns_domains + revdns_domains
     SystemConfiguration.SCDynamicStoreSetValue(sc, 'State:/Network/Service/%s/DNS' % service_id, d)
示例#5
0
def domain_dns():
    if not bound():
        raise NotBound
    net_config = SystemConfiguration.SCDynamicStoreCreate(
        None, 'active-directory', None, None)
    ad_info = SystemConfiguration.SCDynamicStoreCopyValue(
        net_config, 'com.apple.opendirectoryd.ActiveDirectory')
    if ad_info:
        return ad_info.get('DomainNameDns')
    else:
        return None
示例#6
0
def searchnodes():
    if not bound():
        raise NotBound
    net_config = SystemConfiguration.SCDynamicStoreCreate(
        None, 'directory-nodes', None, None)
    nodes = SystemConfiguration.SCDynamicStoreCopyValue(
        net_config, 'com.apple.opendirectoryd.node:/Search')
    if nodes:
        return list(nodes)
    else:
        return None
示例#7
0
def fetchCurrentService(protocol):
    global currentService
    status = SystemConfiguration.SCDynamicStoreCopyValue(None, "State:/Network/Global/" + protocol)
    if not status:
        currentService = None
        return
    serviceID = status['PrimaryService']
    service = SystemConfiguration.SCDynamicStoreCopyValue(None, "Setup:/Network/Service/" + serviceID)
    if not service:
        currentService = None
        return
    currentService = service['UserDefinedName']
    def testFunctions(self):
        ref = SystemConfiguration.SCPreferencesCreate(None, "pyobjc.test",
                                                      "pyobjc.test")
        self.assertIsInstance(ref, SystemConfiguration.SCPreferencesRef)

        v = SystemConfiguration.SCPreferencesSetComputerName(
            ref, "my host", SystemConfiguration.kCFStringEncodingUTF8)
        self.assertTrue(isinstance(v, bool))

        v = SystemConfiguration.SCPreferencesSetLocalHostName(
            ref, "my.host.private")
        self.assertTrue(isinstance(v, bool))
示例#9
0
    def testFunctions10_5(self):
        prefs = SystemConfiguration.SCPreferencesCreate(
            None, "SystemConfiguration", None)
        self.assertTrue(isinstance(prefs,
                                   SystemConfiguration.SCPreferencesRef))

        r = SystemConfiguration.SCNetworkServiceCopyAll(prefs)
        self.assertIsInstance(r, SystemConfiguration.CFArrayRef)
        serv = SystemConfiguration.SCNetworkServiceCopy(
            prefs, SystemConfiguration.SCNetworkServiceGetServiceID(r[0]))

        v = SystemConfiguration.SCNetworkServiceEstablishDefaultConfiguration(
            serv)
        self.assertIsInstance(v, bool)
    def testFunctions(self):

        r = SystemConfiguration.SCDynamicStoreKeyCreate(
            None, "Setup:/%s/%d", b"PyObjC", 9
        )
        self.assertTrue(isinstance(r, str))
        self.assertEqual(r, "Setup:/PyObjC/9")

        r = SystemConfiguration.SCDynamicStoreKeyCreateNetworkGlobalEntity(
            None,
            SystemConfiguration.kSCDynamicStoreDomainSetup,
            SystemConfiguration.kSCEntNetDNS,
        )
        self.assertTrue(isinstance(r, str))

        r = SystemConfiguration.SCDynamicStoreKeyCreateNetworkInterface(
            None, SystemConfiguration.kSCDynamicStoreDomainState
        )
        self.assertTrue(isinstance(r, str))

        r = SystemConfiguration.SCDynamicStoreKeyCreateNetworkInterfaceEntity(
            None,
            SystemConfiguration.kSCDynamicStoreDomainState,
            "en0",
            SystemConfiguration.kSCEntNetIPv4,
        )
        self.assertTrue(isinstance(r, str))

        r = SystemConfiguration.SCDynamicStoreKeyCreateNetworkServiceEntity(
            None,
            SystemConfiguration.kSCDynamicStoreDomainState,
            "ssh",
            SystemConfiguration.kSCEntNetDNS,
        )
        self.assertTrue(isinstance(r, str))

        r = SystemConfiguration.SCDynamicStoreKeyCreateComputerName(None)
        self.assertTrue(isinstance(r, str))

        r = SystemConfiguration.SCDynamicStoreKeyCreateConsoleUser(None)
        self.assertTrue(isinstance(r, str))

        r = SystemConfiguration.SCDynamicStoreKeyCreateHostNames(None)
        self.assertTrue(isinstance(r, str))

        r = SystemConfiguration.SCDynamicStoreKeyCreateLocation(None)
        self.assertTrue(isinstance(r, str))

        r = SystemConfiguration.SCDynamicStoreKeyCreateProxies(None)
        self.assertTrue(isinstance(r, str))
示例#11
0
    def testFunctions(self):
        v = SystemConfiguration.SCNetworkConnectionGetTypeID()
        self.assertIsInstance(v, int)

        self.assertResultIsBOOL(
            SystemConfiguration.SCNetworkConnectionCopyUserPreferences)
        self.assertArgIsOut(
            SystemConfiguration.SCNetworkConnectionCopyUserPreferences, 1)
        self.assertArgIsOut(
            SystemConfiguration.SCNetworkConnectionCopyUserPreferences, 2)
        (
            v,
            servId,
            userOpts,
        ) = SystemConfiguration.SCNetworkConnectionCopyUserPreferences(
            None, None, None)
        if v:
            self.assertIsInstance(servId, str)
            self.assertIsInstance(
                userOpts, (SystemConfiguration.CFDictionaryRef, type(None)))
        else:
            self.assertTrue(servId is None)
            self.assertTrue(userOpts is None)

        def callout(ref, status, info):
            pass

        ctx = object()
        v = SystemConfiguration.SCNetworkConnectionCreateWithServiceID(
            None, "pyobjc.test.id", callout, ctx)

        self.assertResultIsCFRetained(
            SystemConfiguration.SCNetworkConnectionCopyServiceID)

        SystemConfiguration.SCNetworkConnectionGetStatus

        self.assertResultIsCFRetained(
            SystemConfiguration.SCNetworkConnectionCopyExtendedStatus)
        self.assertResultIsCFRetained(
            SystemConfiguration.SCNetworkConnectionCopyStatistics)
        self.assertResultIsBOOL(SystemConfiguration.SCNetworkConnectionStart)
        self.assertResultIsBOOL(SystemConfiguration.SCNetworkConnectionStop)
        self.assertResultIsCFRetained(
            SystemConfiguration.SCNetworkConnectionCopyUserOptions)
        self.assertResultIsBOOL(
            SystemConfiguration.SCNetworkConnectionScheduleWithRunLoop)
        self.assertResultIsBOOL(
            SystemConfiguration.SCNetworkConnectionUnscheduleFromRunLoop)
示例#12
0
def list_events(*_):
  """Displays list of events which can be monitored on the current system."""

  print("On this system SystemConfiguration supports these events:")
  for event in sorted(
      SystemConfiguration.SCDynamicStoreCopyKeyList(get_sc_store(), ".*")):
    print("\t", event)

  print()
  print("Standard NSWorkspace Notification messages:\n\t", end=" ")
  print("\n\t".join("""
        NSWorkspaceDidLaunchApplicationNotification
        NSWorkspaceDidMountNotification
        NSWorkspaceDidPerformFileOperationNotification
        NSWorkspaceDidTerminateApplicationNotification
        NSWorkspaceDidUnmountNotification
        NSWorkspaceDidWakeNotification
        NSWorkspaceSessionDidBecomeActiveNotification
        NSWorkspaceSessionDidResignActiveNotification
        NSWorkspaceWillLaunchApplicationNotification
        NSWorkspaceWillPowerOffNotification
        NSWorkspaceWillSleepNotification
        NSWorkspaceWillUnmountNotification
    """.split()))

  sys.exit(0)
示例#13
0
def autoconfig_url_from_preferences():
    """
    Get the PAC ``AutoConfigURL`` value from the macOS System Preferences.
    This setting is visible as the "URL" field in
    System Preferences > Network > Advanced... > Proxies > Automatic Proxy Configuration.

    :return: The value from the registry, or None if the value isn't configured or available.
        Note that it may be local filesystem path instead of a URL.
    :rtype: str|None
    :raises NotDarwinError: If called on a non-macOS/OSX platform.
    """
    if not ON_DARWIN:
        raise NotDarwinError()

    try:
        config = SystemConfiguration.SCDynamicStoreCopyProxies(None)
    except AttributeError:
        return  # Key or value not found.

    if all((
            "ProxyAutoConfigEnable" in config,
            "ProxyAutoConfigURLString" in config,
            not config.get("ProxyAutoDiscoveryEnable", 0),
    )):
        # Only return a value if it is enabled, not empty, and auto discovery is disabled.
        return str(config["ProxyAutoConfigURLString"])
示例#14
0
 def testHardFunctions(self):
     b, flags = SystemConfiguration.SCNetworkCheckReachabilityByAddress(
         ("www.python.org", 80), objc._size_sockaddr_ip4, None
     )
     self.assertIsInstance(b, bool)
     self.assertIsInstance(flags, int)
     self.assertEqual(b, True)
     self.assertEqual(flags, SystemConfiguration.kSCNetworkFlagsReachable)
    def testFunctions(self):
        self.assertRaises(
            ValueError,
            SystemConfiguration.DHCPClientPreferencesSetApplicationOptions,
            "org.pyobjc.TestSuite",
            [9, 10, 0],
            4,
        )

        r = SystemConfiguration.DHCPClientPreferencesSetApplicationOptions(
            "org.pyobjc.TestSuite", [9, 10, 0, 9], 4)
        self.assertTrue(r is True or r is False)

        r, count = SystemConfiguration.DHCPClientPreferencesCopyApplicationOptions(
            "com.apple.SystemPreferences", None)
        self.assertTrue(r is objc.NULL)
        self.assertTrue(count == 0)
示例#16
0
def _GetHostname():
    """Returns the hostname from SystemConfiguration."""
    logging.warning('facter hostname empty; fetching from sys_config')
    if OBJC_OK:
        # this returns a tuple of (computer name, useless int)
        return sys_config.SCDynamicStoreCopyComputerName(None, None)[0]
    else:
        return None
示例#17
0
def _GetConsoleUser():
  """Returns the logged in console username, or None if nobody is logged in."""
  logging.warning('facter primary_user empty; fetching from sys_config')
  if OBJC_OK:
    # this returns a tuple of (username, uid, gid)
    # if no console user is logged in, it'll be (None, 0, 0)
    return sys_config.SCDynamicStoreCopyConsoleUser(None, None, None)[0] or ''
  else:
    return None
示例#18
0
def add_sc_notifications(sc_config):
  """Get SCDynamicStore session and register for events.

  This uses the SystemConfiguration framework to get a SCDynamicStore session
  and register for certain events. See the Apple SystemConfiguration
  documentation for details:

  <http://developer.apple.com/documentation/Networking/Reference/SysConfig/SCDynamicStore/CompositePage.html>

  TN1145 may also be of interest:
      <http://developer.apple.com/technotes/tn/tn1145.html>

  Inspired by the PyObjC SystemConfiguration callback demos:
  <https://svn.red-bean.com/pyobjc/trunk/pyobjc/pyobjc-framework-SystemConfiguration/Examples/CallbackDemo/>

  Args:
    sc_config: dict
  """

  keys = list(sc_config.keys())

  try:
    for key in keys:
      SC_HANDLERS[key] = get_callable_for_event(
          key, sc_config[key], context="SystemConfiguration: %s" % key)
  except AttributeError as exc:
    print(
        "Error configuring SystemConfiguration events: %s" % exc,
        file=sys.stderr)
    sys.exit(1)

  store = get_sc_store()

  SystemConfiguration.SCDynamicStoreSetNotificationKeys(store, None, keys)

  # Get a CFRunLoopSource and add it to the application's runloop:
  Cocoa.CFRunLoopAddSource(
      Cocoa.NSRunLoop.currentRunLoop().getCFRunLoop(),
      SystemConfiguration.SCDynamicStoreCreateRunLoopSource(None, store, 0),
      Cocoa.kCFRunLoopCommonModes)

  log_list("Listening for these SystemConfiguration events: %s", keys)
示例#19
0
    def testFunctions(self):
        def callback(st, keys, info):
            pass

        st = SystemConfiguration.SCDynamicStoreCreate(
            None, "pyobjc.test", callback, None
        )
        self.assertTrue(isinstance(st, SystemConfiguration.SCDynamicStoreRef))

        nm, encoding = SystemConfiguration.SCDynamicStoreCopyComputerName(st, None)
        self.assertTrue(isinstance(nm, str))
        self.assertTrue(isinstance(encoding, int))

        nm, uid, gid = SystemConfiguration.SCDynamicStoreCopyConsoleUser(st, None, None)
        self.assertTrue(isinstance(nm, str))
        self.assertTrue(isinstance(uid, int))
        self.assertTrue(isinstance(gid, int))

        nm = SystemConfiguration.SCDynamicStoreCopyLocalHostName(st)
        self.assertTrue(isinstance(nm, str))

        nm = SystemConfiguration.SCDynamicStoreCopyLocation(st)
        self.assertTrue(isinstance(nm, str))

        r = SystemConfiguration.SCDynamicStoreCopyProxies(st)
        self.assertTrue(r is None or isinstance(r, SystemConfiguration.CFDictionaryRef))
示例#20
0
 def GetHostname(self):
   host = None
   if SystemConfiguration:
     # NOTE: SCDynamicStoreCopyComputerName returns a unicode object, which
     #   may contain non-utf-8 characters.  We attempt to encode to UTF-8.
     host, _ = SystemConfiguration.SCDynamicStoreCopyComputerName(None, None)
     try:
       host = host.encode('utf-8')
     except (UnicodeError, AttributeError):
       host = None
   if not host:
     host = socket.gethostname()
   return host
示例#21
0
    def testFunctions(self):
        def callback(st, keys, info):
            pass

        st = SystemConfiguration.SCDynamicStoreCreate(None, "pyobjc.test",
                                                      callback, None)
        self.assertTrue(isinstance(st, SystemConfiguration.SCDynamicStoreRef))

        have_ip = False
        with os.popen("ifconfig en0 | grep inet", "r") as fp:
            ip = fp.read()
        if ip.strip():
            have_ip = True
        else:
            with os.popen("ifconfig en1 | grep inet", "r") as fp:
                ip = fp.read()
            if ip.strip():
                have_ip = True

        info = SystemConfiguration.SCDynamicStoreCopyDHCPInfo(st, None)
        if not have_ip:
            self.assertIs(info, None)
        else:
            self.assertIsInstance(info, SystemConfiguration.CFDictionaryRef)

            r = SystemConfiguration.DHCPInfoGetOptionData(info, 1)
            self.assertTrue(r is None
                            or isinstance(r, SystemConfiguration.NSData))

            r = SystemConfiguration.DHCPInfoGetLeaseStartTime(info)
            self.assertTrue(r is None
                            or isinstance(r, SystemConfiguration.NSDate))

        SystemConfiguration.DHCPInfoGetLeaseExpirationTime

        if info:
            r = SystemConfiguration.DHCPInfoGetLeaseExpirationTime(info)
            self.assertTrue(r is None or isinstance(r, NSDate))
示例#22
0
    def testFunctions(self):
        ref = SystemConfiguration.SCPreferencesCreate(None, "pyobjc.test",
                                                      "pyobjc.test")
        self.assertIsInstance(ref, SystemConfiguration.SCPreferencesRef)

        r = SystemConfiguration.SCPreferencesAddValue(
            ref,
            "use",
            SystemConfiguration.NSMutableDictionary.dictionaryWithDictionary_({
                "python2":
                True,
                "python3":
                False
            }),
        )
        self.assertTrue(r)

        v = SystemConfiguration.SCPreferencesPathCreateUniqueChild(ref, "/")
        self.assertIsInstance(v, str)

        v = SystemConfiguration.SCPreferencesPathGetValue(ref, "/use")
        self.assertIsInstance(v, SystemConfiguration.NSDictionary)

        v = SystemConfiguration.SCPreferencesPathSetValue(
            ref, "/use", {
                "python2": True,
                "python3": True
            })
        self.assertTrue(v is True)

        v = SystemConfiguration.SCPreferencesPathSetLink(
            ref, "/use_python", "/use")
        self.assertTrue(v is True)

        v = SystemConfiguration.SCPreferencesPathGetLink(ref, "/use_python")
        self.assertEqual(v, "/use")

        v = SystemConfiguration.SCPreferencesPathRemoveValue(ref, "/use")
        self.assertTrue(v is True)
示例#23
0
    def testCallbacks(self):
        if os.getuid() != 0:
            self.fail("WARNING: Need root privileges to test callback mechanism")
            return

        info = object()
        lst = []

        def callback(store, changedKeys, info):
            lst.append((store, changedKeys, info))

        st = SystemConfiguration.SCDynamicStoreCreate(
            None, b"pyobjc.test", callback, info
        )

        SystemConfiguration.SCDynamicStoreSetNotificationKeys(st, None, [".*"])
        src = SystemConfiguration.SCDynamicStoreCreateRunLoopSource(None, st, 0)
        self.assertTrue(isinstance(src, SystemConfiguration.CFRunLoopSourceRef))

        SystemConfiguration.SCDynamicStoreAddTemporaryValue(
            st, "pyobjc.test.key", "value"
        )

        SystemConfiguration.CFRunLoopAddSource(
            SystemConfiguration.CFRunLoopGetCurrent(),
            src,
            SystemConfiguration.kCFRunLoopCommonModes,
        )
        SystemConfiguration.CFRunLoopRunInMode(
            SystemConfiguration.kCFRunLoopDefaultMode, 2.0, False
        )

        self.assertTrue(len(lst) > 1)
        self.assertTrue(lst[0][0] is st)
        self.assertIsInstance(lst[0][1], SystemConfiguration.CFArrayRef)
        self.assertTrue(lst[0][2] is info)
示例#24
0
import sys
import threading
import time
import traceback

try:
    import ctypes
except ImportError:
    has_windll = False
else:
    has_windll = hasattr(ctypes, 'windll')

# this MUST be imported for urllib to work on OSX
try:
    import SystemConfiguration as osxsc
    osxsc.SCNetworkInterfaceCopyAll()
    has_osxsc = True
except ImportError:
    has_osxsc = False

try:
    urllib_imports = [
        'ProxyHandler', 'Request', 'build_opener', 'install_opener', 'urlopen'
    ]
    if sys.version_info[0] < 3:
        urllib = __import__('urllib2', fromlist=urllib_imports)
    else:
        urllib = __import__('urllib.request', fromlist=urllib_imports)
except ImportError:
    has_urllib = False
else:
示例#25
0
    def testFunctions(self):
        self.assertIsInstance(SystemConfiguration.SCPreferencesGetTypeID(),
                              int)

        ref = SystemConfiguration.SCPreferencesCreate(None, "pyobjc.test",
                                                      "pyobjc.test")
        self.assertIsInstance(ref, SystemConfiguration.SCPreferencesRef)

        self.assertResultIsBOOL(SystemConfiguration.SCPreferencesLock)
        self.assertArgIsBOOL(SystemConfiguration.SCPreferencesLock, 1)
        v = SystemConfiguration.SCPreferencesLock(ref, False)
        self.assertIsInstance(v, bool)

        self.assertResultIsBOOL(SystemConfiguration.SCPreferencesUnlock)
        v = SystemConfiguration.SCPreferencesUnlock(ref)
        self.assertIsInstance(v, bool)

        self.assertResultIsBOOL(SystemConfiguration.SCPreferencesCommitChanges)
        v = SystemConfiguration.SCPreferencesCommitChanges(ref)
        self.assertIsInstance(v, bool)

        self.assertResultIsBOOL(SystemConfiguration.SCPreferencesApplyChanges)
        v = SystemConfiguration.SCPreferencesApplyChanges(ref)
        self.assertIsInstance(v, bool)

        r = SystemConfiguration.SCPreferencesGetSignature(ref)
        self.assertIsInstance(r, SystemConfiguration.CFDataRef)

        r = SystemConfiguration.SCPreferencesCopyKeyList(ref)
        self.assertIsInstance(r, SystemConfiguration.CFArrayRef)

        lst = []

        def callback(ref, key, ctx):
            lst.append([ref, key, ctx])

        ctx = object()

        v = SystemConfiguration.SCPreferencesSetCallback(ref, callback, ctx)
        self.assertTrue(v is True)

        self.assertResultIsBOOL(SystemConfiguration.SCPreferencesAddValue)
        r = SystemConfiguration.SCPreferencesAddValue(ref, "use_python3",
                                                      False)
        self.assertTrue(r is True)

        v = SystemConfiguration.SCPreferencesGetValue(ref, "use_python3")
        self.assertTrue(v is False)

        v = SystemConfiguration.SCPreferencesGetValue(ref, "use_python4")
        self.assertTrue(v is None)

        self.assertResultIsBOOL(SystemConfiguration.SCPreferencesSetValue)
        r = SystemConfiguration.SCPreferencesSetValue(ref, "use_python3",
                                                      "on newyearsday")
        self.assertTrue(r is True)

        self.assertResultIsBOOL(SystemConfiguration.SCPreferencesRemoveValue)
        r = SystemConfiguration.SCPreferencesRemoveValue(ref, "use_python3")

        self.assertResultIsBOOL(
            SystemConfiguration.SCPreferencesScheduleWithRunLoop)
        rl = SystemConfiguration.CFRunLoopGetCurrent()
        r = SystemConfiguration.SCPreferencesScheduleWithRunLoop(
            ref, rl, SystemConfiguration.kCFRunLoopCommonModes)
        SystemConfiguration.CFRunLoopRunInMode(
            SystemConfiguration.kCFRunLoopDefaultMode, 1.0, False)

        self.assertResultIsBOOL(
            SystemConfiguration.SCPreferencesUnscheduleFromRunLoop)
        r = SystemConfiguration.SCPreferencesUnscheduleFromRunLoop(
            ref, rl, SystemConfiguration.kCFRunLoopCommonModes)

        SystemConfiguration.SCPreferencesSynchronize(ref)
示例#26
0
    def testFunctions(self):
        n = SystemConfiguration.SCDynamicStoreGetTypeID()
        self.assertTrue(isinstance(n, int))

        lst = []
        info = object()

        def callback(store, changedKeys, info):
            lst.append((store, changedKeys, info))

        st = SystemConfiguration.SCDynamicStoreCreate(
            None, "pyobjc.test", callback, info
        )
        self.assertTrue(isinstance(st, SystemConfiguration.SCDynamicStoreRef))

        st = SystemConfiguration.SCDynamicStoreCreateWithOptions(
            None, "pyobjc.test", {}, callback, info
        )
        self.assertTrue(isinstance(st, SystemConfiguration.SCDynamicStoreRef))

        src = SystemConfiguration.SCDynamicStoreCreateRunLoopSource(None, st, 0)
        self.assertTrue(isinstance(src, SystemConfiguration.CFRunLoopSourceRef))
        del src

        v = SystemConfiguration.SCDynamicStoreCopyKeyList(st, ".*")
        self.assertTrue(isinstance(v, SystemConfiguration.CFArrayRef))
        self.assertTrue(len(v) > 0)
        self.assertTrue(isinstance(v[0], str))

        r = SystemConfiguration.SCDynamicStoreAddValue(st, "Setup:/PyObjC", {"key": 42})
        self.assertTrue(r is True or r is False)

        r = SystemConfiguration.SCDynamicStoreAddTemporaryValue(
            st, "Setup:/PyObjC", {"key": 42}
        )
        self.assertTrue(r is True or r is False)

        v = SystemConfiguration.SCDynamicStoreCopyValue(st, "Setup:/")
        self.assertTrue(isinstance(v, SystemConfiguration.CFDictionaryRef))

        v = SystemConfiguration.SCDynamicStoreCopyMultiple(st, None, [".*"])
        self.assertTrue(isinstance(v, SystemConfiguration.CFDictionaryRef))

        r = SystemConfiguration.SCDynamicStoreSetValue(st, "Setup:/PyObjC", {"key": 42})
        self.assertTrue(r is True or r is False)

        r = SystemConfiguration.SCDynamicStoreSetMultiple(
            st, {"Setup:/PyObjC2": {"key": 42}}, ["Setup:/PyObjC"], ["System:/"]
        )
        self.assertTrue(r is True or r is False)

        r = SystemConfiguration.SCDynamicStoreRemoveValue(st, "Setup:/PyObjC")
        self.assertTrue(r is True or r is False)

        r = SystemConfiguration.SCDynamicStoreNotifyValue(st, "Setup:/")
        self.assertTrue(r is True or r is False)

        r = SystemConfiguration.SCDynamicStoreSetNotificationKeys(st, ["Setup:/"], None)
        self.assertTrue(r is True)

        r = SystemConfiguration.SCDynamicStoreCopyNotifiedKeys(st)
        self.assertTrue(isinstance(r, SystemConfiguration.CFArrayRef))
示例#27
0
    def testFunctions(self):
        r = SystemConfiguration.SCNetworkInterfaceGetTypeID()
        self.assertTrue(isinstance(r, int))

        r = SystemConfiguration.SCNetworkInterfaceCopyAll()
        self.assertTrue(isinstance(r, SystemConfiguration.CFArrayRef))
        self.assertTrue(len(r) > 0)

        for iface in r:
            if SystemConfiguration.SCNetworkInterfaceGetBSDName(
                    iface).startswith("en"):
                break

        r = SystemConfiguration.SCNetworkInterfaceGetSupportedInterfaceTypes(
            iface)
        self.assertTrue(isinstance(r, SystemConfiguration.CFArrayRef))
        self.assertTrue(isinstance(r[0], str))

        r = SystemConfiguration.SCNetworkInterfaceGetSupportedProtocolTypes(
            iface)
        self.assertTrue(isinstance(r, SystemConfiguration.CFArrayRef))
        self.assertTrue(isinstance(r[0], str))

        r = SystemConfiguration.SCNetworkInterfaceCreateWithInterface(
            iface, SystemConfiguration.kSCNetworkInterfaceTypeL2TP)
        self.assertTrue(
            r is None
            or isinstance(r, SystemConfiguration.SCNetworkInterfaceRef))

        r = SystemConfiguration.SCNetworkInterfaceGetBSDName(iface)
        self.assertTrue(isinstance(r, str))

        r = SystemConfiguration.SCNetworkInterfaceGetConfiguration(iface)
        self.assertTrue(r is None
                        or isinstance(r, SystemConfiguration.CFDictionaryRef))

        r = SystemConfiguration.SCNetworkInterfaceGetExtendedConfiguration(
            iface, "EAPOL")
        self.assertTrue(r is None
                        or isinstance(r, SystemConfiguration.CFDictionaryRef))

        r = SystemConfiguration.SCNetworkInterfaceGetHardwareAddressString(
            iface)
        self.assertTrue(isinstance(r, str))

        r = SystemConfiguration.SCNetworkInterfaceGetInterface(iface)
        self.assertTrue(r is None)

        r = SystemConfiguration.SCNetworkInterfaceGetInterfaceType(iface)
        self.assertTrue(isinstance(r, str))

        r = SystemConfiguration.SCNetworkInterfaceGetLocalizedDisplayName(
            iface)
        self.assertTrue(isinstance(r, str))

        r = SystemConfiguration.SCNetworkInterfaceSetConfiguration(iface, {})
        self.assertTrue(r is True or r is False)

        r = SystemConfiguration.SCNetworkInterfaceSetExtendedConfiguration(
            iface, "OC", {})
        self.assertTrue(r is True or r is False)

        (
            r,
            current,
            active,
            available,
        ) = SystemConfiguration.SCNetworkInterfaceCopyMediaOptions(
            iface, None, None, None, False)
        self.assertTrue(r is True)
        self.assertTrue(
            isinstance(current, SystemConfiguration.CFDictionaryRef))
        self.assertTrue(isinstance(active,
                                   SystemConfiguration.CFDictionaryRef))
        self.assertTrue(isinstance(available, SystemConfiguration.CFArrayRef))

        r = SystemConfiguration.SCNetworkInterfaceCopyMediaSubTypes(available)
        self.assertTrue(isinstance(r, SystemConfiguration.CFArrayRef))
        for item in r:
            self.assertTrue(isinstance(item, str))

        r = SystemConfiguration.SCNetworkInterfaceCopyMediaSubTypeOptions(
            available, r[0])
        self.assertTrue(isinstance(r, SystemConfiguration.CFArrayRef))

        r, mtu_cur, mtu_min, mtu_max = SystemConfiguration.SCNetworkInterfaceCopyMTU(
            iface, None, None, None)
        self.assertTrue(r is True)
        self.assertTrue(isinstance(mtu_cur, int))
        self.assertTrue(isinstance(mtu_min, int))
        self.assertTrue(isinstance(mtu_max, int))
        r = SystemConfiguration.SCNetworkInterfaceSetMediaOptions(
            iface, current["MediaSubType"], current["MediaOptions"])
        self.assertTrue(r is True or r is False)

        r = SystemConfiguration.SCNetworkInterfaceSetMTU(iface, mtu_cur)
        self.assertTrue(r is True or r is False)

        r = SystemConfiguration.SCNetworkInterfaceForceConfigurationRefresh(
            iface)
        self.assertTrue(r is True or r is False)

        prefs = SystemConfiguration.SCPreferencesCreate(
            None, "SystemConfiguration", None)
        self.assertTrue(isinstance(prefs,
                                   SystemConfiguration.SCPreferencesRef))

        a = SystemConfiguration.SCBondInterfaceCopyAll(prefs)
        self.assertTrue(isinstance(a, SystemConfiguration.CFArrayRef))

        a = SystemConfiguration.SCBondInterfaceCopyAvailableMemberInterfaces(
            prefs)
        self.assertTrue(isinstance(a, SystemConfiguration.CFArrayRef))

        self.assertResultIsCFRetained(
            SystemConfiguration.SCBondInterfaceCreate)
        iface = SystemConfiguration.SCBondInterfaceCreate(prefs)
        self.assertTrue(
            iface is None
            or isinstance(iface, SystemConfiguration.SCBondInterfaceRef))

        if iface is not None:
            a = SystemConfiguration.SCBondInterfaceGetMemberInterfaces(iface)
            self.assertTrue(isinstance(a, SystemConfiguration.CFArrayRef))

            o = SystemConfiguration.SCBondInterfaceGetOptions(iface)
            self.assertTrue(
                o is None
                or isinstance(o, SystemConfiguration.CFDictionaryRef))

            r = SystemConfiguration.SCBondInterfaceSetMemberInterfaces(
                iface, SystemConfiguration.SCNetworkInterfaceCopyAll())
            self.assertTrue(r is True or r is False)

            r = SystemConfiguration.SCBondInterfaceSetLocalizedDisplayName(
                iface, "pyobjc.bond")
            self.assertTrue(r is True or r is False)

            r = SystemConfiguration.SCBondInterfaceSetOptions(iface, {})
            self.assertTrue(r is True or r is False)

            st = SystemConfiguration.SCBondInterfaceCopyStatus(iface)
            self.assertTrue(
                st is None
                or isinstance(st, SystemConfiguration.SCBondStatusRef))

            a = SystemConfiguration.SCBondStatusGetMemberInterfaces(iface)
            self.assertTrue(a is None
                            or isinstance(a, SystemConfiguration.CFArrayRef))

            st = SystemConfiguration.SCBondStatusGetInterfaceStatus(
                iface, None)
            self.assertTrue(
                a is None
                or isinstance(a, SystemConfiguration.CFDictionaryRef))

            r = SystemConfiguration.SCBondInterfaceRemove(iface)
            self.assertTrue(r is True)

        r = SystemConfiguration.SCBondStatusGetTypeID()
        self.assertTrue(isinstance(r, int))

        a = SystemConfiguration.SCVLANInterfaceCopyAll(prefs)
        self.assertTrue(isinstance(a, SystemConfiguration.CFArrayRef))

        a = SystemConfiguration.SCVLANInterfaceCopyAvailablePhysicalInterfaces(
        )
        self.assertTrue(isinstance(a, SystemConfiguration.CFArrayRef))

        if len(a) != 0:
            iface = SystemConfiguration.SCVLANInterfaceCreate(prefs, a[0], 99)
            self.assertTrue(
                isinstance(iface, SystemConfiguration.SCVLANInterfaceRef))

            r = SystemConfiguration.SCVLANInterfaceGetPhysicalInterface(iface)
            self.assertEqual(r, a[0])

            t = SystemConfiguration.SCVLANInterfaceGetTag(iface)
            self.assertEqual(t, 99)

            t = SystemConfiguration.SCVLANInterfaceGetOptions(iface)
            self.assertTrue(
                t is None
                or isinstance(t, SystemConfiguration.CFDictionaryRef))

            r = SystemConfiguration.SCVLANInterfaceSetPhysicalInterfaceAndTag(
                iface, a[0], 42)
            self.assertIs(r, True)

            r = SystemConfiguration.SCVLANInterfaceSetLocalizedDisplayName(
                iface, "octest")
            self.assertIs(r, True)

            r = SystemConfiguration.SCVLANInterfaceSetOptions(
                iface, {"name": "foo"})
            self.assertIs(r, True)

            t = SystemConfiguration.SCVLANInterfaceGetOptions(iface)
            self.assertIsInstance(t,
                                  (dict, SystemConfiguration.CFDictionaryRef))

            r = SystemConfiguration.SCVLANInterfaceRemove(iface)
            self.assertTrue(r is True)

        self.assertResultIsCFRetained(
            SystemConfiguration.SCVLANInterfaceCreate)
        SystemConfiguration.SCVLANInterfaceRemove
        SystemConfiguration.SCVLANInterfaceGetPhysicalInterface
        SystemConfiguration.SCVLANInterfaceGetTag
        SystemConfiguration.SCVLANInterfaceGetOptions
        SystemConfiguration.SCVLANInterfaceSetPhysicalInterfaceAndTag
        SystemConfiguration.SCVLANInterfaceSetLocalizedDisplayName
        SystemConfiguration.SCVLANInterfaceSetOptions

        r = SystemConfiguration.SCNetworkProtocolGetTypeID()
        self.assertTrue(isinstance(r, int))

        r = SystemConfiguration.SCNetworkServiceGetTypeID()
        self.assertTrue(isinstance(r, int))

        r = SystemConfiguration.SCNetworkSetGetTypeID()
        self.assertTrue(isinstance(r, int))

        r = SystemConfiguration.SCNetworkServiceCopyAll(prefs)
        self.assertIsInstance(r, SystemConfiguration.CFArrayRef)

        serv = r[0]
        self.assertIsInstance(serv, SystemConfiguration.SCNetworkServiceRef)
        prot = SystemConfiguration.SCNetworkServiceCopyProtocol(
            serv, SystemConfiguration.kSCNetworkProtocolTypeIPv4)
        self.assertIsInstance(prot, SystemConfiguration.SCNetworkProtocolRef)

        conf = SystemConfiguration.SCNetworkProtocolGetConfiguration(prot)
        self.assertIsInstance(conf, SystemConfiguration.CFDictionaryRef)

        enabled = SystemConfiguration.SCNetworkProtocolGetEnabled(prot)
        self.assertIsInstance(enabled, bool)

        pr = SystemConfiguration.SCNetworkProtocolGetProtocolType(prot)
        self.assertIsInstance(pr, str)

        v = SystemConfiguration.SCNetworkProtocolSetConfiguration(prot, conf)
        self.assertIsInstance(v, bool)

        v = SystemConfiguration.SCNetworkProtocolSetEnabled(prot, enabled)
        self.assertIsInstance(v, bool)

        v = SystemConfiguration.SCNetworkServiceAddProtocolType(serv, pr)
        self.assertIsInstance(v, bool)

        v = SystemConfiguration.SCNetworkServiceCopyProtocols(serv)
        self.assertIsInstance(v, SystemConfiguration.CFArrayRef)
        if v:
            self.assertIsInstance(v[0],
                                  SystemConfiguration.SCNetworkProtocolRef)

        iface = SystemConfiguration.SCNetworkServiceGetInterface(serv)
        self.assertIsInstance(iface, SystemConfiguration.SCNetworkInterfaceRef)

        v = SystemConfiguration.SCNetworkServiceCreate(prefs, iface)
        self.assertIsInstance(v, SystemConfiguration.SCNetworkServiceRef)

        v = s2 = SystemConfiguration.SCNetworkServiceCopy(
            prefs, SystemConfiguration.SCNetworkServiceGetServiceID(serv))
        self.assertIsInstance(v, SystemConfiguration.SCNetworkServiceRef)

        v = SystemConfiguration.SCNetworkServiceGetEnabled(serv)
        self.assertIsInstance(v, bool)

        v = SystemConfiguration.SCNetworkServiceGetName(serv)
        self.assertIsInstance(v, str)

        self.assertResultIsCFRetained(
            SystemConfiguration.SCNetworkServiceCopyProtocol)

        v = SystemConfiguration.SCNetworkServiceRemoveProtocolType(
            s2, SystemConfiguration.kSCNetworkProtocolTypeIPv4)
        self.assertIsInstance(v, bool)

        v = SystemConfiguration.SCNetworkServiceRemove(s2)
        self.assertIsInstance(v, bool)

        v = SystemConfiguration.SCNetworkServiceSetEnabled(
            serv, SystemConfiguration.SCNetworkServiceGetEnabled(serv))
        self.assertIsInstance(v, bool)

        v = SystemConfiguration.SCNetworkServiceSetName(
            serv, SystemConfiguration.SCNetworkServiceGetName(serv))
        self.assertIsInstance(v, bool)

        a_set = SystemConfiguration.SCNetworkSetCopyCurrent(prefs)
        self.assertIsInstance(a_set, SystemConfiguration.SCNetworkSetRef)

        s2 = SystemConfiguration.SCNetworkServiceCopy(
            prefs, SystemConfiguration.SCNetworkServiceGetServiceID(serv))

        v = SystemConfiguration.SCNetworkSetAddService(set, s2)
        self.assertIsInstance(v, bool)

        v = SystemConfiguration.SCNetworkSetContainsInterface(set, iface)
        self.assertIsInstance(v, bool)

        v = SystemConfiguration.SCNetworkSetCopyAll(prefs)
        self.assertIsInstance(v, SystemConfiguration.CFArrayRef)

        v = SystemConfiguration.SCNetworkSetCopyServices(a_set)
        self.assertIsInstance(v, SystemConfiguration.CFArrayRef)

        v = SystemConfiguration.SCNetworkSetCreate(prefs)
        self.assertIsInstance(v, SystemConfiguration.SCNetworkSetRef)

        v = SystemConfiguration.SCNetworkSetCopy(
            prefs, SystemConfiguration.SCNetworkSetGetSetID(a_set))
        self.assertIsInstance(v, SystemConfiguration.SCNetworkSetRef)

        v = SystemConfiguration.SCNetworkSetRemove(v)
        self.assertIsInstance(v, bool)

        v = SystemConfiguration.SCNetworkSetGetName(a_set)
        self.assertIsInstance(v, str)

        v = SystemConfiguration.SCNetworkSetGetSetID(a_set)
        self.assertIsInstance(v, str)

        v = SystemConfiguration.SCNetworkSetGetServiceOrder(a_set)
        self.assertIsInstance(v, SystemConfiguration.CFArrayRef)

        v = SystemConfiguration.SCNetworkSetSetName(
            a_set, SystemConfiguration.SCNetworkSetGetName(a_set))
        self.assertIsInstance(v, bool)

        v = SystemConfiguration.SCNetworkSetSetServiceOrder(
            a_set, SystemConfiguration.SCNetworkSetGetServiceOrder(a_set))
        self.assertIsInstance(v, bool)

        v = SystemConfiguration.SCNetworkSetSetCurrent(
            SystemConfiguration.SCNetworkSetCopyCurrent(prefs))
        self.assertIsInstance(v, bool)

        self.assertResultIsBOOL(SystemConfiguration.SCNetworkSetRemoveService)
示例#28
0
 def testFunctions10_5(self):
     err = SystemConfiguration.SCCopyLastError()
     self.assertTrue(isinstance(err, SystemConfiguration.CFErrorRef))
示例#29
0
def _get_consoleuser():
    return SystemConfiguration.SCDynamicStoreCopyConsoleUser(None, None,
                                                             None)[0]
    def testFunctions(self):
        self.assertResultIsCFRetained(
            SystemConfiguration.SCNetworkReachabilityCreateWithAddressPair)
        v = SystemConfiguration.SCNetworkReachabilityCreateWithAddressPair(
            None, ("0.0.0.0", 20990), ("www.python.org", 80))

        with contextlib.closing(
                socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sd:
            sd.listen(5)

            self.assertResultIsCFRetained(
                SystemConfiguration.SCNetworkReachabilityCreateWithAddress)
            ref = v = SystemConfiguration.SCNetworkReachabilityCreateWithAddress(
                None, sd.getsockname())
            self.assertIsInstance(v,
                                  SystemConfiguration.SCNetworkReachabilityRef)

            self.assertResultIsCFRetained(
                SystemConfiguration.SCNetworkReachabilityCreateWithName)
            v = SystemConfiguration.SCNetworkReachabilityCreateWithName(
                None, b"www.python.org")
            self.assertIsInstance(v,
                                  SystemConfiguration.SCNetworkReachabilityRef)

            v = SystemConfiguration.SCNetworkReachabilityGetTypeID()
            self.assertIsInstance(v, int)

            self.assertResultIsBOOL(
                SystemConfiguration.SCNetworkReachabilityGetFlags)
            v, fl = SystemConfiguration.SCNetworkReachabilityGetFlags(
                ref, None)
            self.assertTrue(v)
            self.assertIsInstance(fl, int)

            lst = []

            def callout(ref, flags, ctx):
                lst.append([ref, flags, ctx])

            ctx = object()
            v = SystemConfiguration.SCNetworkReachabilitySetCallback(
                ref, callout, ctx)
            self.assertTrue(v is True)

            rl = SystemConfiguration.CFRunLoopGetCurrent()
            self.assertResultIsBOOL(
                SystemConfiguration.SCNetworkReachabilityScheduleWithRunLoop)
            SystemConfiguration.SCNetworkReachabilityScheduleWithRunLoop(
                ref, rl, SystemConfiguration.kCFRunLoopCommonModes)

            SystemConfiguration.CFRunLoopRunInMode(
                SystemConfiguration.kCFRunLoopDefaultMode, 1.0, False)

            self.assertResultIsBOOL(
                SystemConfiguration.SCNetworkReachabilityUnscheduleFromRunLoop)
            SystemConfiguration.SCNetworkReachabilityUnscheduleFromRunLoop(
                ref, rl, SystemConfiguration.kCFRunLoopCommonModes)

        @min_os_level("10.6")
        def testFunctions10_6(self):
            self.assertResultIsBOOL(
                SystemConfiguration.SCNetworkReachabilitySetDispatchQueue)

        def testConstants(self):
            self.assertEqual(
                SystemConfiguration.
                kSCNetworkReachabilityFlagsTransientConnection,
                1 << 0,
            )
            self.assertEqual(
                SystemConfiguration.kSCNetworkReachabilityFlagsReachable,
                1 << 1)
            self.assertEqual(
                SystemConfiguration.
                kSCNetworkReachabilityFlagsConnectionRequired,
                1 << 2,
            )
            self.assertEqual(
                SystemConfiguration.
                kSCNetworkReachabilityFlagsConnectionOnTraffic,
                1 << 3,
            )
            self.assertEqual(
                SystemConfiguration.
                kSCNetworkReachabilityFlagsInterventionRequired,
                1 << 4,
            )
            self.assertEqual(
                SystemConfiguration.
                kSCNetworkReachabilityFlagsConnectionOnDemand,
                1 << 5,
            )
            self.assertEqual(
                SystemConfiguration.kSCNetworkReachabilityFlagsIsLocalAddress,
                1 << 16)
            self.assertEqual(
                SystemConfiguration.kSCNetworkReachabilityFlagsIsDirect,
                1 << 17)

            self.assertEqual(
                SystemConfiguration.
                kSCNetworkReachabilityFlagsConnectionAutomatic,
                SystemConfiguration.
                kSCNetworkReachabilityFlagsConnectionOnTraffic,
            )