Title: [212741] trunk/Tools
Revision
212741
Author
[email protected]
Date
2017-02-21 13:03:55 -0800 (Tue, 21 Feb 2017)

Log Message

webkitpy: Refactor Device class
https://bugs.webkit.org/show_bug.cgi?id=168332

Reviewed by Alexey Proskuryakov.

Separate the more specific SimulatedDevice from the abstract
idea of a device.

* Scripts/webkitpy/xcode/device.py: Added.
(Device):  Base device class.
(Device.__init__): Initialize _host, name and udid.
(Device.install_app): Function declaration.
(Device.launch_app): Ditto.
(Device.__eq__): Compare two devices by udid.
(Device.__ne__): Ditto.
(Device.__repr__): Return device name and udid in formatted string.
* Scripts/webkitpy/xcode/simulated_device.py: Copied from Tools/Scripts/webkitpy/xcode/simulator.py.
(SimulatedDevice):
(SimulatedDevice.__init__): Call Device.__init__ first.
(SimulatedDevice.delete): Device -> SimulatedDevice.
(SimulatedDevice.reset): Ditto.
(SimulatedDevice.__eq__): Moved to device.py.
(SimulatedDevice.__ne__): Ditto.
(SimulatedDevice.__repr__): Call Device __repr__ first.
(DeviceType): Kept in Scripts/webkitpy/xcode/simulator.py.
(Runtime): Kept in Scripts/webkitpy/xcode/simulator.py.
(Device): Renamed SimulatedDevice.
(Simulator): Kept in Scripts/webkitpy/xcode/simulator.py.
* Scripts/webkitpy/xcode/simulator.py:
(Simulator): Define Simulator.Device class as None.
(Simulator.__init__): Import SimulatedDevice as Simulator.Device.
(Simulator.delete_device): Use Simulator.Device.
(Simulator.reset_device): Ditto.
(Simulator._parse_devices): Ditto.
(Simulator.lookup_or_create_device): Make
(Device): Moved to simulated_device as SimulatedDevice.

Modified Paths

Added Paths

Diff

Modified: trunk/Tools/ChangeLog (212740 => 212741)


--- trunk/Tools/ChangeLog	2017-02-21 20:57:03 UTC (rev 212740)
+++ trunk/Tools/ChangeLog	2017-02-21 21:03:55 UTC (rev 212741)
@@ -1,3 +1,42 @@
+2017-02-21  Jonathan Bedard  <[email protected]>
+
+        webkitpy: Refactor Device class
+        https://bugs.webkit.org/show_bug.cgi?id=168332
+
+        Reviewed by Alexey Proskuryakov.
+
+        Separate the more specific SimulatedDevice from the abstract
+        idea of a device.
+
+        * Scripts/webkitpy/xcode/device.py: Added.
+        (Device):  Base device class.
+        (Device.__init__): Initialize _host, name and udid.
+        (Device.install_app): Function declaration.
+        (Device.launch_app): Ditto.
+        (Device.__eq__): Compare two devices by udid.
+        (Device.__ne__): Ditto.
+        (Device.__repr__): Return device name and udid in formatted string.
+        * Scripts/webkitpy/xcode/simulated_device.py: Copied from Tools/Scripts/webkitpy/xcode/simulator.py.
+        (SimulatedDevice):
+        (SimulatedDevice.__init__): Call Device.__init__ first.
+        (SimulatedDevice.delete): Device -> SimulatedDevice.
+        (SimulatedDevice.reset): Ditto.
+        (SimulatedDevice.__eq__): Moved to device.py.
+        (SimulatedDevice.__ne__): Ditto.
+        (SimulatedDevice.__repr__): Call Device __repr__ first.
+        (DeviceType): Kept in Scripts/webkitpy/xcode/simulator.py.
+        (Runtime): Kept in Scripts/webkitpy/xcode/simulator.py.
+        (Device): Renamed SimulatedDevice.
+        (Simulator): Kept in Scripts/webkitpy/xcode/simulator.py.
+        * Scripts/webkitpy/xcode/simulator.py:
+        (Simulator): Define Simulator.Device class as None.
+        (Simulator.__init__): Import SimulatedDevice as Simulator.Device.
+        (Simulator.delete_device): Use Simulator.Device.
+        (Simulator.reset_device): Ditto.
+        (Simulator._parse_devices): Ditto.
+        (Simulator.lookup_or_create_device): Make 
+        (Device): Moved to simulated_device as SimulatedDevice.
+
 2017-02-21  JF Bastien  <[email protected]>
 
         Fix cmake build

Added: trunk/Tools/Scripts/webkitpy/xcode/device.py (0 => 212741)


--- trunk/Tools/Scripts/webkitpy/xcode/device.py	                        (rev 0)
+++ trunk/Tools/Scripts/webkitpy/xcode/device.py	2017-02-21 21:03:55 UTC (rev 212741)
@@ -0,0 +1,45 @@
+# Copyright (C) 2017 Apple Inc. All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+# 1.  Redistributions of source code must retain the above copyright
+#     notice, this list of conditions and the following disclaimer.
+# 2.  Redistributions in binary form must reproduce the above copyright
+#     notice, this list of conditions and the following disclaimer in the
+#     documentation and/or other materials provided with the distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+# DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+
+class Device(object):
+    def __init__(self, name, udid, host):
+        self._host = host
+        self.name = name
+        self.udid = udid
+
+    def install_app(self, app_path, env=None):
+        raise NotImplementedError
+
+    def launch_app(self, bundle_id, args, env=None):
+        raise NotImplementedError
+
+    def __eq__(self, other):
+        return self.udid == other.udid
+
+    def __ne__(self, other):
+        return not self.__eq__(other)
+
+    def __repr__(self):
+        return 'Device "{name}": {udid}.'.format(
+            name=self.name,
+            udid=self.udid)

Added: trunk/Tools/Scripts/webkitpy/xcode/simulated_device.py (0 => 212741)


--- trunk/Tools/Scripts/webkitpy/xcode/simulated_device.py	                        (rev 0)
+++ trunk/Tools/Scripts/webkitpy/xcode/simulated_device.py	2017-02-21 21:03:55 UTC (rev 212741)
@@ -0,0 +1,184 @@
+# Copyright (C) 2014-2017 Apple Inc. All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+# 1.  Redistributions of source code must retain the above copyright
+#     notice, this list of conditions and the following disclaimer.
+# 2.  Redistributions in binary form must reproduce the above copyright
+#     notice, this list of conditions and the following disclaimer in the
+#     documentation and/or other materials provided with the distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+# DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+import logging
+import re
+import subprocess
+
+from webkitpy.xcode.device import Device
+from webkitpy.xcode.simulator import Simulator
+from webkitpy.common.host import Host
+
+_log = logging.getLogger(__name__)
+
+
+class SimulatedDevice(Device):
+    """
+    Represents a CoreSimulator device underneath a runtime
+    """
+
+    def __init__(self, name, udid, available, runtime, host):
+        """
+        :param name: The device name
+        :type name: str
+        :param udid: The device UDID (a UUID string)
+        :type udid: str
+        :param available: Whether the device is available for use.
+        :type available: bool
+        :param runtime: The iOS Simulator runtime that hosts this device
+        :type runtime: Runtime
+        :param host: The host which can run command line commands
+        :type host: Host
+        """
+        super(SimulatedDevice, self).__init__(name, udid, host)
+        self.available = available
+        self.runtime = runtime
+
+    @property
+    def state(self):
+        """
+        :returns: The current state of the device.
+        :rtype: Simulator.DeviceState
+        """
+        return Simulator.device_state(self.udid)
+
+    @property
+    def path(self):
+        """
+        :returns: The filesystem path that contains the simulator device's data.
+        :rtype: str
+        """
+        return Simulator.device_directory(self.udid)
+
+    @classmethod
+    def create(cls, name, device_type, runtime):
+        """
+        Create a new CoreSimulator device.
+        :param name: The name of the device.
+        :type name: str
+        :param device_type: The CoreSimulatort device type.
+        :type device_type: DeviceType
+        :param runtime:  The CoreSimualtor runtime.
+        :type runtime: Runtime
+        :return: The new device or raises a CalledProcessError if ``simctl create`` failed.
+        :rtype: Device
+        """
+        device_udid = subprocess.check_output(['xcrun', 'simctl', 'create', name, device_type.identifier, runtime.identifier]).rstrip()
+        _log.debug('"xcrun simctl create %s %s %s" returned %s', name, device_type.identifier, runtime.identifier, device_udid)
+        Simulator.wait_until_device_is_in_state(device_udid, Simulator.DeviceState.SHUTDOWN)
+        return Simulator().find_device_by_udid(device_udid)
+
+    @classmethod
+    def shutdown(cls, udid):
+        """
+        Shut down the given CoreSimulator device.
+        :param udid: The udid of the device.
+        :type udid: str
+        """
+        device_state = Simulator.device_state(udid)
+        if device_state == Simulator.DeviceState.BOOTING or device_state == Simulator.DeviceState.BOOTED:
+            _log.debug('xcrun simctl shutdown %s', udid)
+            # Don't throw on error. Device shutdown seems to be racy with Simulator app killing.
+            subprocess.call(['xcrun', 'simctl', 'shutdown', udid])
+
+        Simulator.wait_until_device_is_in_state(udid, Simulator.DeviceState.SHUTDOWN)
+
+    @classmethod
+    def delete(cls, udid):
+        """
+        Delete the given CoreSimulator device.
+        :param udid: The udid of the device.
+        :type udid: str
+        """
+        SimulatedDevice.shutdown(udid)
+        try:
+            _log.debug('xcrun simctl delete %s', udid)
+            subprocess.check_call(['xcrun', 'simctl', 'delete', udid])
+        except subprocess.CalledProcessError:
+            raise RuntimeError('"xcrun simctl delete" failed: device state is {}'.format(Simulator.device_state(udid)))
+
+    @classmethod
+    def reset(cls, udid):
+        """
+        Reset the given CoreSimulator device.
+        :param udid: The udid of the device.
+        :type udid: str
+        """
+        SimulatedDevice.shutdown(udid)
+        try:
+            _log.debug('xcrun simctl erase %s', udid)
+            subprocess.check_call(['xcrun', 'simctl', 'erase', udid])
+        except subprocess.CalledProcessError:
+            raise RuntimeError('"xcrun simctl erase" failed: device state is {}'.format(Simulator.device_state(udid)))
+
+    def install_app(self, app_path, env=None):
+        # FIXME: This is a workaround for <rdar://problem/30273973>, Racey failure of simctl install.
+        for x in xrange(3):
+            if self._host.executive.run_command(['xcrun', 'simctl', 'install', self.udid, app_path], return_exit_code=True):
+                return False
+            try:
+                bundle_id = self._host.executive.run_command([
+                    '/usr/libexec/PlistBuddy',
+                    '-c',
+                    'Print CFBundleIdentifier',
+                    self._host.filesystem.join(app_path, 'Info.plist'),
+                ]).rstrip()
+                self._host.executive.kill_process(self.launch_app(bundle_id, [], env=env, attempts=1))
+                return True
+            except RuntimeError:
+                pass
+        return False
+
+    def launch_app(self, bundle_id, args, env=None, attempts=3):
+        environment_to_use = {}
+        SIMCTL_ENV_PREFIX = 'SIMCTL_CHILD_'
+        for value in (env or {}):
+            if not value.startswith(SIMCTL_ENV_PREFIX):
+                environment_to_use[SIMCTL_ENV_PREFIX + value] = env[value]
+            else:
+                environment_to_use[value] = env[value]
+
+        # FIXME: This is a workaround for <rdar://problem/30172453>.
+        def _log_debug_error(error):
+            _log.debug(error.message_with_output())
+
+        output = None
+        for x in xrange(attempts):
+            output = self._host.executive.run_command(
+                ['xcrun', 'simctl', 'launch', self.udid, bundle_id] + args,
+                env=environment_to_use,
+                error_handler=_log_debug_error,
+            )
+            match = re.match(r'(?P<bundle>[^:]+): (?P<pid>\d+)\n', output)
+            if match:
+                break
+
+        if not match or match.group('bundle') != bundle_id:
+            raise RuntimeError('Failed to find process id for {}: {}'.format(bundle_id, output))
+        return int(match.group('pid'))
+
+    def __repr__(self):
+        return '<{device_info} State: {state}. Runtime: {runtime}, Available: {available}>'.format(
+            device_info=super(SimulatedDevice, self).__repr__(),
+            state=self.state,
+            available=self.available,
+            runtime=self.runtime.identifier)

Modified: trunk/Tools/Scripts/webkitpy/xcode/simulator.py (212740 => 212741)


--- trunk/Tools/Scripts/webkitpy/xcode/simulator.py	2017-02-21 20:57:03 UTC (rev 212740)
+++ trunk/Tools/Scripts/webkitpy/xcode/simulator.py	2017-02-21 21:03:55 UTC (rev 212741)
@@ -1,4 +1,4 @@
-# Copyright (C) 2014, 2015 Apple Inc. All rights reserved.
+# Copyright (C) 2014-2017 Apple Inc. All rights reserved.
 #
 # Redistribution and use in source and binary forms, with or without
 # modification, are permitted provided that the following conditions
@@ -162,168 +162,6 @@
             num_devices=len(self.devices))
 
 
-class Device(object):
-    """
-    Represents a CoreSimulator device underneath a runtime
-    """
-
-    def __init__(self, name, udid, available, runtime, host):
-        """
-        :param name: The device name
-        :type name: str
-        :param udid: The device UDID (a UUID string)
-        :type udid: str
-        :param available: Whether the device is available for use.
-        :type available: bool
-        :param runtime: The iOS Simulator runtime that hosts this device
-        :type runtime: Runtime
-        :param host: The host which can run command line commands
-        :type host: Host
-        """
-        self._host = host
-        self.name = name
-        self.udid = udid
-        self.available = available
-        self.runtime = runtime
-
-    @property
-    def state(self):
-        """
-        :returns: The current state of the device.
-        :rtype: Simulator.DeviceState
-        """
-        return Simulator.device_state(self.udid)
-
-    @property
-    def path(self):
-        """
-        :returns: The filesystem path that contains the simulator device's data.
-        :rtype: str
-        """
-        return Simulator.device_directory(self.udid)
-
-    @classmethod
-    def create(cls, name, device_type, runtime):
-        """
-        Create a new CoreSimulator device.
-        :param name: The name of the device.
-        :type name: str
-        :param device_type: The CoreSimulatort device type.
-        :type device_type: DeviceType
-        :param runtime:  The CoreSimualtor runtime.
-        :type runtime: Runtime
-        :return: The new device or raises a CalledProcessError if ``simctl create`` failed.
-        :rtype: Device
-        """
-        device_udid = subprocess.check_output(['xcrun', 'simctl', 'create', name, device_type.identifier, runtime.identifier]).rstrip()
-        _log.debug('"xcrun simctl create %s %s %s" returned %s', name, device_type.identifier, runtime.identifier, device_udid)
-        Simulator.wait_until_device_is_in_state(device_udid, Simulator.DeviceState.SHUTDOWN)
-        return Simulator().find_device_by_udid(device_udid)
-
-    @classmethod
-    def shutdown(cls, udid):
-        """
-        Shut down the given CoreSimulator device.
-        :param udid: The udid of the device.
-        :type udid: str
-        """
-        device_state = Simulator.device_state(udid)
-        if device_state == Simulator.DeviceState.BOOTING or device_state == Simulator.DeviceState.BOOTED:
-            _log.debug('xcrun simctl shutdown %s', udid)
-            # Don't throw on error. Device shutdown seems to be racy with Simulator app killing.
-            subprocess.call(['xcrun', 'simctl', 'shutdown', udid])
-
-        Simulator.wait_until_device_is_in_state(udid, Simulator.DeviceState.SHUTDOWN)
-
-    @classmethod
-    def delete(cls, udid):
-        """
-        Delete the given CoreSimulator device.
-        :param udid: The udid of the device.
-        :type udid: str
-        """
-        Device.shutdown(udid)
-        try:
-            _log.debug('xcrun simctl delete %s', udid)
-            subprocess.check_call(['xcrun', 'simctl', 'delete', udid])
-        except subprocess.CalledProcessError:
-            raise RuntimeError('"xcrun simctl delete" failed: device state is {}'.format(Simulator.device_state(udid)))
-
-    @classmethod
-    def reset(cls, udid):
-        """
-        Reset the given CoreSimulator device.
-        :param udid: The udid of the device.
-        :type udid: str
-        """
-        Device.shutdown(udid)
-        try:
-            _log.debug('xcrun simctl erase %s', udid)
-            subprocess.check_call(['xcrun', 'simctl', 'erase', udid])
-        except subprocess.CalledProcessError:
-            raise RuntimeError('"xcrun simctl erase" failed: device state is {}'.format(Simulator.device_state(udid)))
-
-    def install_app(self, app_path, env=None):
-        # FIXME: This is a workaround for <rdar://problem/30273973>, Racey failure of simctl install.
-        for x in xrange(3):
-            if self._host.executive.run_command(['xcrun', 'simctl', 'install', self.udid, app_path], return_exit_code=True):
-                return False
-            try:
-                bundle_id = self._host.executive.run_command([
-                    '/usr/libexec/PlistBuddy',
-                    '-c',
-                    'Print CFBundleIdentifier',
-                    self._host.filesystem.join(app_path, 'Info.plist'),
-                ]).rstrip()
-                self._host.executive.kill_process(self.launch_app(bundle_id, [], env=env, attempts=1))
-                return True
-            except RuntimeError:
-                pass
-        return False
-
-    def launch_app(self, bundle_id, args, env=None, attempts=3):
-        environment_to_use = {}
-        SIMCTL_ENV_PREFIX = 'SIMCTL_CHILD_'
-        for value in (env or {}):
-            if not value.startswith(SIMCTL_ENV_PREFIX):
-                environment_to_use[SIMCTL_ENV_PREFIX + value] = env[value]
-            else:
-                environment_to_use[value] = env[value]
-
-        # FIXME: This is a workaround for <rdar://problem/30172453>.
-        def _log_debug_error(error):
-            _log.debug(error.message_with_output())
-
-        output = None
-        for x in xrange(attempts):
-            output = self._host.executive.run_command(
-                ['xcrun', 'simctl', 'launch', self.udid, bundle_id] + args,
-                env=environment_to_use,
-                error_handler=_log_debug_error,
-            )
-            match = re.match(r'(?P<bundle>[^:]+): (?P<pid>\d+)\n', output)
-            if match:
-                break
-
-        if not match or match.group('bundle') != bundle_id:
-            raise RuntimeError('Failed to find process id for {}: {}'.format(bundle_id, output))
-        return int(match.group('pid'))
-
-    def __eq__(self, other):
-        return self.udid == other.udid
-
-    def __ne__(self, other):
-        return not self.__eq__(other)
-
-    def __repr__(self):
-        return '<Device "{name}": {udid}. State: {state}. Runtime: {runtime}, Available: {available}>'.format(
-            name=self.name,
-            udid=self.udid,
-            state=self.state,
-            available=self.available,
-            runtime=self.runtime.identifier)
-
-
 # FIXME: This class is fragile because it parses the output of the simctl command line utility, which may change.
 #        We should find a better way to query for simulator device state and capabilities. Maybe take a similiar
 #        approach as in webkitdirs.pm and utilize the parsed output from the device.plist files in the sub-
@@ -344,8 +182,14 @@
         '\s*(?P<name>[^(]+ )\((?P<udid>[^)]+)\) \((?P<state>[^)]+)\)( \((?P<availability>[^)]+)\))?')
 
     _managed_devices = {}
+    Device = None
 
     def __init__(self, host=None):
+        # FIXME: This circular import should be resolved.
+        if not Simulator.Device:
+            from webkitpy.xcode.simulated_device import SimulatedDevice
+            Simulator.Device = SimulatedDevice
+
         self._host = host or Host()
         self.runtimes = []
         self.device_types = []
@@ -438,11 +282,11 @@
 
     @staticmethod
     def delete_device(udid):
-        Device.delete(udid)
+        Simulator.Device.delete(udid)
 
     @staticmethod
     def reset_device(udid):
-        Device.reset(udid)
+        Simulator.Device.reset(udid)
 
     def refresh(self):
         """
@@ -523,7 +367,7 @@
                     raise RuntimeError('Expected == Device Pairs == header but got: "{}"'.format(line))
                 break
             if current_runtime:
-                device = Device(name=device_match.group('name').rstrip(),
+                device = Simulator.Device(name=device_match.group('name').rstrip(),
                                 udid=device_match.group('udid'),
                                 available=device_match.group('availability') is None,
                                 runtime=current_runtime,
@@ -659,7 +503,7 @@
         if testing_device:
             _log.debug('lookup_or_create_device %s %s %s found %s', name, device_type, runtime, testing_device.name)
             return testing_device
-        testing_device = Device.create(name, device_type, runtime)
+        testing_device = Simulator.Device.create(name, device_type, runtime)
         _log.debug('lookup_or_create_device %s %s %s created %s', name, device_type, runtime, testing_device.name)
         assert(testing_device.available)
         return testing_device
_______________________________________________
webkit-changes mailing list
[email protected]
https://lists.webkit.org/mailman/listinfo/webkit-changes

Reply via email to