def _InitPlatformIfNeeded(self): if self._platform: return self._platform = platform_module.GetHostPlatform() # pylint: disable=W0212 self._platform_backend = self._platform._platform_backend
def testIsApplicationRunning(self): platform = platform_module.GetHostPlatform() self.assertFalse(platform.IsApplicationRunning('This_Is_A_Bad___App__Name')) sys_exe = os.path.basename(sys.executable) self.assertTrue(platform.IsApplicationRunning(sys_exe)) self.assertFalse( platform.IsApplicationRunning('%s append_bad_after_space' % sys_exe))
def _InitPlatformIfNeeded(self): if self._platform: return self._platform = platform_module.GetHostPlatform() # pylint: disable=protected-access self._platform_backend = self._platform._platform_backend
def CreateChromeBrowserOptions(br_options): browser_type = br_options.browser_type if (platform.GetHostPlatform().GetOSName() == 'chromeos' or (browser_type and browser_type.startswith('cros'))): return CrosBrowserOptions(br_options) return br_options
def _FramesFromMp4(self, mp4_file): host_platform = platform.GetHostPlatform() if not host_platform.CanLaunchApplication('avconv'): host_platform.InstallApplication('avconv') def GetDimensions(video): proc = subprocess.Popen(['avconv', '-i', video], stderr=subprocess.PIPE) dimensions = None output = '' for line in proc.stderr.readlines(): output += line if 'Video:' in line: dimensions = line.split(',')[2] dimensions = map(int, dimensions.split()[0].split('x')) break proc.communicate() assert dimensions, ( 'Failed to determine video dimensions. output=%s' % output) return dimensions def GetFrameTimestampMs(stderr): """Returns the frame timestamp in integer milliseconds from the dump log. The expected line format is: ' dts=1.715 pts=1.715\n' We have to be careful to only read a single timestamp per call to avoid deadlock because avconv interleaves its writes to stdout and stderr. """ while True: line = '' next_char = '' while next_char != '\n': next_char = stderr.read(1) line += next_char if 'pts=' in line: return int(1000 * float(line.split('=')[-1])) dimensions = GetDimensions(mp4_file) frame_length = dimensions[0] * dimensions[1] * 3 frame_data = bytearray(frame_length) # Use rawvideo so that we don't need any external library to parse frames. proc = subprocess.Popen([ 'avconv', '-i', mp4_file, '-vcodec', 'rawvideo', '-pix_fmt', 'rgb24', '-dump', '-loglevel', 'debug', '-f', 'rawvideo', '-' ], stderr=subprocess.PIPE, stdout=subprocess.PIPE) while True: num_read = proc.stdout.readinto(frame_data) if not num_read: raise StopIteration assert num_read == len( frame_data), 'Unexpected frame size: %d' % num_read yield (GetFrameTimestampMs(proc.stderr), bitmap.Bitmap(3, dimensions[0], dimensions[1], frame_data))
def __init__(self, test, finder_options, story_set, possible_browser): super(SharedPageState, self).__init__(test, finder_options, story_set, possible_browser) self._page_test = None if issubclass(type(test), legacy_page_test.LegacyPageTest): # We only need a page_test for legacy measurements that involve running # some commands before/after starting the browser or navigating to a page. # This is not needed for newer timeline (tracing) based benchmarks which # just collect a trace, then measurements are done after the fact by # analysing the trace itself. self._page_test = test self._page_test_results = None if (self._device_type == 'desktop' and platform_module.GetHostPlatform().GetOSName() == 'chromeos'): self._device_type = 'chromeos' browser_options = finder_options.browser_options browser_options.browser_user_agent_type = self._device_type if self._page_test: self._page_test.CustomizeBrowserOptions(browser_options) self._browser = None self._finder_options = finder_options self._first_browser = True self._current_page = None self._current_tab = None if self._page_test: self._page_test.SetOptions(self._finder_options) self._extra_wpr_args = browser_options.extra_wpr_args if (hasattr(finder_options, 'use_local_wpr') and finder_options.use_local_wpr): self._extra_wpr_args.append('--use-local-wpr') if (hasattr(finder_options, 'disable_fuzzy_url_matching') and finder_options.disable_fuzzy_url_matching): self._extra_wpr_args.append('--disable-fuzzy-url-matching') profiling_mod = browser_interval_profiling_controller self._interval_profiling_controller = ( profiling_mod.BrowserIntervalProfilingController( possible_browser=self._possible_browser, process_name=finder_options.interval_profiling_target, periods=finder_options.interval_profiling_periods, frequency=finder_options.interval_profiling_frequency, profiler_options=finder_options.interval_profiler_options)) self.platform.SetPerformanceMode(finder_options.performance_mode) self._perf_mode_set = (finder_options.performance_mode != android_device.KEEP_PERFORMANCE_MODE) self.platform.network_controller.Open(self.wpr_mode) self.platform.Initialize() self._video_recording_enabled = ( self._finder_options.capture_screen_video and self.platform.CanRecordVideo())
def FindAllAvailableBrowsers(finder_options, device): """Finds all available CrOS browsers, locally and remotely.""" if not isinstance(device, cros_device.CrOSDevice): return [] if cros_device.IsRunningOnCrOS(): return [ PossibleCrOSBrowser('system', finder_options, platform_module.GetHostPlatform(), is_guest=False), PossibleCrOSBrowser('system-guest', finder_options, platform_module.GetHostPlatform(), is_guest=True) ] # Check ssh try: platform = platform_module.GetPlatformForDevice(device, finder_options) except cros_interface.LoginException, ex: if isinstance(ex, cros_interface.KeylessLoginRequiredException): logging.warn( 'Could not ssh into %s. Your device must be configured', finder_options.cros_remote) logging.warn('to allow passwordless login as root.') logging.warn('For a test-build device, pass this to your script:') logging.warn(' --identity $(CHROMITE)/ssh_keys/testing_rsa') logging.warn('') logging.warn('For a developer-mode device, the steps are:') logging.warn( ' - Ensure you have an id_rsa.pub (etc) on this computer') logging.warn(' - On the chromebook:') logging.warn(' - Control-Alt-T; shell; sudo -s') logging.warn(' - openssh-server start') logging.warn(' - scp <this machine>:.ssh/id_rsa.pub /tmp/') logging.warn(' - mkdir /root/.ssh') logging.warn(' - chown go-rx /root/.ssh') logging.warn( ' - cat /tmp/id_rsa.pub >> /root/.ssh/authorized_keys') logging.warn(' - chown 0600 /root/.ssh/authorized_keys') logging.warn('There, that was easy!') logging.warn('') logging.warn('P.S. Please, tell your manager how INANE this is.') raise browser_finder_exceptions.BrowserFinderException(str(ex))
def __init__(self, device, finder_options): assert device, ( 'AndroidPlatformBackend can only be initialized from remote device' ) super(AndroidPlatformBackend, self).__init__(device) self._device = device_utils.DeviceUtils(device.device_id) installed_prebuilt_tools = _SetupPrebuiltTools(self._device) if not installed_prebuilt_tools: logging.error( '%s detected, however prebuilt android tools could not ' 'be used. To run on Android you must build them first:\n' ' $ ninja -C out/Release android_tools' % device.name) raise exceptions.PlatformError() # Trying to root the device, if possible. if not self._device.HasRoot(): try: self._device.EnableRoot() except device_errors.CommandFailedError: logging.warning('Unable to root %s', str(self._device)) self._battery = battery_utils.BatteryUtils(self._device) self._enable_performance_mode = device.enable_performance_mode self._surface_stats_collector = None self._perf_tests_setup = perf_control.PerfControl(self._device) self._thermal_throttle = thermal_throttle.ThermalThrottle(self._device) self._raw_display_frame_rate_measurements = [] try: self._can_access_protected_file_contents = (self._device.HasRoot() or self._device.NeedsSU()) except Exception: logging.exception('New exception caused by DeviceUtils conversion') raise self._device_copy_script = None self._power_monitor = ( android_power_monitor_controller.AndroidPowerMonitorController([ android_temperature_monitor.AndroidTemperatureMonitor( self._device), monsoon_power_monitor.MonsoonPowerMonitor(self._device, self), android_dumpsys_power_monitor.DumpsysPowerMonitor( self._battery, self), sysfs_power_monitor.SysfsPowerMonitor(self, standalone=True), android_fuelgauge_power_monitor.FuelGaugePowerMonitor( self._battery, self), ], self._battery)) self._video_recorder = None self._installed_applications = None self._wpr_ca_cert_path = None self._device_cert_util = None self._is_test_ca_installed = False self._use_rndis_forwarder = ( finder_options.android_rndis or finder_options.browser_options.netsim or platform.GetHostPlatform().GetOSName() != 'linux') _FixPossibleAdbInstability()
def FetchExampleDomainArchive(): ''' Return the path to wpr go archive of example.com page. This may involve fetching the archives from cloud storage if it doesn't exist on local file system. ''' p = platform.GetHostPlatform() return binary_manager.FetchPath('example_domain_wpr_go_archive', p.GetArchName(), p.GetOSName())
def SetUp(): logging.getLogger().setLevel(logging.INFO) if not platform.GetHostPlatform().CanMonitorPower(): print >> sys.stderr, "Can't monitor power." sys.exit(1) with open(RESULTS_FILE_NAME, 'w') as results_file: csv.DictWriter(results_file, fieldnames=FIELD_NAMES).writeheader()
def __init__(self, dimensions, pixels): binary = support_binaries.FindPath( 'bitmaptools', platform.GetHostPlatform().GetArchName(), platform.GetHostPlatform().GetOSName()) assert binary, 'You must build bitmaptools first!' self._popen = subprocess.Popen([binary], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # dimensions are: bpp, width, height, boxleft, boxtop, boxwidth, boxheight packed_dims = struct.pack('iiiiiii', *dimensions) self._popen.stdin.write(packed_dims) # If we got a list of ints, we need to convert it into a byte buffer. if type(pixels) is not bytearray: pixels = bytearray(pixels) self._popen.stdin.write(pixels)
def testGetCPUStats(self): platform = platform_module.GetHostPlatform() backend = platform._platform_backend # pylint: disable=protected-access cpu_stats = backend.GetCpuStats(os.getpid()) self.assertGreater(cpu_stats['CpuProcessTime'], 0) self.assertTrue(cpu_stats.has_key('ContextSwitches')) if backend.GetOSVersionName() >= os_version.MAVERICKS: self.assertTrue(cpu_stats.has_key('IdleWakeupCount'))
def CollectProfile(self): self._timer.cancel() self._DumpJavaHeap(True) self._browser_backend.device.PullFile(self._DEFAULT_DEVICE_DIR, self._output_path) self._browser_backend.device.RunShellCommand( 'rm ' + os.path.join(self._DEFAULT_DEVICE_DIR, '*')) output_files = [] for f in os.listdir(self._output_path): if os.path.splitext(f)[1] == '.aprof': input_file = os.path.join(self._output_path, f) output_file = input_file.replace('.aprof', '.hprof') hprof_conv = binary_manager.FetchPath( 'hprof-conv', platform.GetHostPlatform().GetArchName(), platform.GetHostPlatform().GetOSName()) subprocess.call([hprof_conv, input_file, output_file]) output_files.append(output_file) return output_files
def FetchTelemetryDependencies( platform=None, client_configs=None, chrome_reference_browser=False): if not platform: platform = platform_module.GetHostPlatform() if binary_manager.NeedsInit(): binary_manager.InitDependencyManager(client_configs) else: raise Exception('Binary manager already initialized with other configs.') binary_manager.FetchBinaryDependencies( platform, client_configs, chrome_reference_browser)
def MonitorAndRecordPower(label): logging.debug('Monitoring %s for %d seconds...', label, MONITORING_DURATION_SECONDS) results = [] for _ in xrange(int(MONITORING_DURATION_SECONDS / SAMPLE_INTERVAL_SECONDS)): platform.GetHostPlatform().StartMonitoringPower(None) time.sleep(SAMPLE_INTERVAL_SECONDS) result = platform.GetHostPlatform().StopMonitoringPower() result = { 'label': label, 'Power (W)': result['energy_consumption_mwh'] * 3.6 / SAMPLE_INTERVAL_SECONDS, 'Temperature (C)': result['component_utilization']['whole_package']['average_temperature_c'], } results.append(result) with open(RESULTS_FILE_NAME, 'a') as results_file: for result in results: csv.DictWriter(results_file, fieldnames=FIELD_NAMES).writerow(result)
def __init__(self, device): self._device = device try: self._device.EnableRoot() except device_errors.CommandFailedError: logging.error('RNDIS forwarding requires a rooted device.') raise self._device_ip = None self._host_iface = None self._host_ip = None self.device_iface = None if platform.GetHostPlatform().GetOSName() == 'mac': self._InstallHorndis(platform.GetHostPlatform().GetArchName()) assert self._IsRndisSupported(), 'Device does not support RNDIS.' self._CheckConfigureNetwork()
def __init__(self, test, finder_options, story_set): super(SharedPageState, self).__init__(test, finder_options, story_set) if isinstance(test, timeline_based_measurement.TimelineBasedMeasurement): if finder_options.profiler: assert not 'trace' in finder_options.profiler, ( 'This is a Timeline Based Measurement benchmark. You cannot run it ' 'with trace profiler enabled. If you need trace data, tracing is ' 'always enabled in Timeline Based Measurement benchmarks and you ' 'can get the trace data with the default --output-format=html.' ) # This is to avoid the cyclic-import caused by timeline_based_page_test. from telemetry.web_perf import timeline_based_page_test self._test = timeline_based_page_test.TimelineBasedPageTest(test) else: self._test = test if (self._device_type == 'desktop' and platform_module.GetHostPlatform().GetOSName() == 'chromeos'): self._device_type = 'chromeos' _PrepareFinderOptions(finder_options, self._test, self._device_type) self._browser = None self._finder_options = finder_options self._possible_browser = self._GetPossibleBrowser( self._test, finder_options) self._first_browser = True self._previous_page = None self._current_page = None self._current_tab = None self._test.SetOptions(self._finder_options) # TODO(crbug/404771): Move network controller options out of # browser_options and into finder_options. browser_options = self._finder_options.browser_options if self._finder_options.use_live_sites: wpr_mode = wpr_modes.WPR_OFF elif browser_options.wpr_mode == wpr_modes.WPR_RECORD: wpr_mode = wpr_modes.WPR_RECORD else: wpr_mode = wpr_modes.WPR_REPLAY self._extra_wpr_args = browser_options.extra_wpr_args self._simpleperf_controller = ( browser_simpleperf_controller.BrowserSimpleperfController( process_name=finder_options.simpleperf_target, periods=finder_options.simpleperf_periods, frequency=finder_options.simpleperf_frequency)) self.platform.SetFullPerformanceModeEnabled( finder_options.full_performance_mode) self.platform.network_controller.Open(wpr_mode) self.platform.Initialize()
def FetchBinaryDepdencies(platform, client_configs, fetch_reference_chrome_binary): """ Fetch all binary dependenencies for the given |platform|. Note: we don't fetch browser binaries by default because the size of the binary is about 2Gb, and it requires cloud storage permission to chrome-telemetry bucket. Args: platform: an instance of telemetry.core.platform client_configs: A list of paths (string) to dependencies json files. fetch_reference_chrome_binary: whether to fetch reference chrome binary for the given platform. """ configs = [dependency_manager.BaseConfig(TELEMETRY_PROJECT_CONFIG)] dep_manager = dependency_manager.DependencyManager(configs) target_platform = '%s_%s' % (platform.GetOSName(), platform.GetArchName()) dep_manager.PrefetchPaths(target_platform) if platform.GetOSName() == 'android': host_platform = '%s_%s' % (platform_module.GetHostPlatform().GetOSName( ), platform_module.GetHostPlatform().GetArchName()) dep_manager.PrefetchPaths(host_platform) if fetch_reference_chrome_binary: _FetchReferenceBrowserBinary(platform) # For now, handle client config separately because the BUILD.gn & .isolate of # telemetry tests in chromium src failed to include the files specified in its # client config. # (https://github.com/catapult-project/catapult/issues/2192) # For now this is ok because the client configs usually don't include cloud # storage infos. # TODO(nednguyen): remove the logic of swallowing exception once the issue is # fixed on Chromium side. if client_configs: manager = dependency_manager.DependencyManager( list(dependency_manager.BaseConfig(c) for c in client_configs)) try: manager.PrefetchPaths(target_platform) except Exception: exception_formatter.PrintFormattedException()
def __init__(self, test, finder_options, story_set, possible_browser): super(SharedPageState, self).__init__(test, finder_options, story_set, possible_browser) self._page_test = None if issubclass(type(test), legacy_page_test.LegacyPageTest): # We only need a page_test for legacy measurements that involve running # some commands before/after starting the browser or navigating to a page. # This is not needed for newer timeline (tracing) based benchmarks which # just collect a trace, then measurements are done after the fact by # analysing the trace itself. self._page_test = test if (self._device_type == 'desktop' and platform_module.GetHostPlatform().GetOSName() == 'chromeos'): self._device_type = 'chromeos' browser_options = finder_options.browser_options browser_options.browser_user_agent_type = self._device_type if self._page_test: self._page_test.CustomizeBrowserOptions(browser_options) self._browser = None self._finder_options = finder_options self._first_browser = True self._current_page = None self._current_tab = None if self._page_test: self._page_test.SetOptions(self._finder_options) self._extra_wpr_args = browser_options.extra_wpr_args profiling_mod = browser_interval_profiling_controller self._interval_profiling_controller = ( profiling_mod.BrowserIntervalProfilingController( possible_browser=self._possible_browser, process_name=finder_options.interval_profiling_target, periods=finder_options.interval_profiling_periods, frequency=finder_options.interval_profiling_frequency, profiler_options=finder_options.interval_profiler_options)) self.platform.SetFullPerformanceModeEnabled( finder_options.full_performance_mode) self.platform.network_controller.Open(self.wpr_mode) self.platform.Initialize() self._video_recording_enabled = ( self._finder_options.capture_screen_video and self.platform.CanRecordVideo()) if finder_options.experimental_system_tracing: perfetto_tracing_agent.PerfettoTracingAgent.SetUpAgent( self.platform._platform_backend)
def FindAllAvailableDevices(_): """Returns a list of available devices. """ # TODO(baxley): Add support for all platforms possible. Probably Linux, # probably not Windows. if platform.GetHostPlatform().GetOSName() != 'mac': return [] if not _IsIosDeviceAttached() and not _IsIosSimulatorAvailable(): return [] return [IOSDevice()]
def _GetConfigInstructions(gsutil_path): if SupportsProdaccess(gsutil_path) and _FindExecutableInPath( 'prodaccess'): return 'Run prodaccess to authenticate.' else: if platform.GetHostPlatform().GetOSName() == 'chromeos': gsutil_path = ('HOME=%s %s' % (_CROS_GSUTIL_HOME_WAR, gsutil_path)) return ( 'To configure your credentials:\n' ' 1. Run "%s config" and follow its instructions.\n' ' 2. If you have a @google.com account, use that account.\n' ' 3. For the project-id, just enter 0.' % gsutil_path)
def Create(self): self._InitPlatformIfNeeded() use_rndis_forwarder = (self.finder_options.android_rndis or self.finder_options.browser_options.netsim or platform.GetHostPlatform().GetOSName() != 'linux') backend = android_browser_backend.AndroidBrowserBackend( self.finder_options.browser_options, self._backend_settings, use_rndis_forwarder, output_profile_path=self.finder_options.output_profile_path, extensions_to_load=self.finder_options.extensions_to_load, target_arch=self.finder_options.target_arch) b = browser.Browser(backend, self._platform_backend) return b
def __init__(self, test, finder_options, story_set): super(SharedPageState, self).__init__(test, finder_options, story_set) if isinstance(test, timeline_based_measurement.TimelineBasedMeasurement): # This is to avoid the cyclic-import caused by timeline_based_page_test. from telemetry.web_perf import timeline_based_page_test self._test = timeline_based_page_test.TimelineBasedPageTest() else: self._test = test if (self._device_type == 'desktop' and platform_module.GetHostPlatform().GetOSName() == 'chromeos'): self._device_type = 'chromeos' _PrepareFinderOptions(finder_options, self._test, self._device_type) self._browser = None self._finder_options = finder_options self._possible_browser = self._GetPossibleBrowser( self._test, finder_options) self._first_browser = True self._previous_page = None self._current_page = None self._current_tab = None self._test.SetOptions(self._finder_options) # TODO(crbug/404771): Move network controller options out of # browser_options and into finder_options. browser_options = self._finder_options.browser_options if self._finder_options.use_live_sites: wpr_mode = wpr_modes.WPR_OFF elif browser_options.wpr_mode == wpr_modes.WPR_RECORD: wpr_mode = wpr_modes.WPR_RECORD else: wpr_mode = wpr_modes.WPR_REPLAY self._extra_wpr_args = browser_options.extra_wpr_args profiling_mod = browser_interval_profiling_controller self._interval_profiling_controller = ( profiling_mod.BrowserIntervalProfilingController( possible_browser=self._possible_browser, process_name=finder_options.interval_profiling_target, periods=finder_options.interval_profiling_periods, frequency=finder_options.interval_profiling_frequency)) self.platform.SetFullPerformanceModeEnabled( finder_options.full_performance_mode) self.platform.network_controller.Open(wpr_mode) self.platform.Initialize()
def __init__(self, device, finder_options): assert device, ( 'AndroidPlatformBackend can only be initialized from remote device' ) super(AndroidPlatformBackend, self).__init__(device) self._adb = adb_commands.AdbCommands(device=device.device_id) installed_prebuilt_tools = adb_commands.SetupPrebuiltTools(self._adb) if not installed_prebuilt_tools: logging.error( '%s detected, however prebuilt android tools could not ' 'be used. To run on Android you must build them first:\n' ' $ ninja -C out/Release android_tools' % device.name) raise exceptions.PlatformError() # Trying to root the device, if possible. if not self._adb.IsRootEnabled(): # Ignore result. self._adb.EnableAdbRoot() self._device = self._adb.device() self._battery = battery_utils.BatteryUtils(self._device) self._enable_performance_mode = device.enable_performance_mode self._surface_stats_collector = None self._perf_tests_setup = perf_control.PerfControl(self._device) self._thermal_throttle = thermal_throttle.ThermalThrottle(self._device) self._raw_display_frame_rate_measurements = [] self._can_access_protected_file_contents = (self._device.HasRoot() or self._device.NeedsSU()) self._device_copy_script = None power_controller = power_monitor_controller.PowerMonitorController([ monsoon_power_monitor.MonsoonPowerMonitor(self._device, self), android_ds2784_power_monitor.DS2784PowerMonitor( self._device, self), android_dumpsys_power_monitor.DumpsysPowerMonitor( self._battery, self), ]) self._power_monitor = android_temperature_monitor.AndroidTemperatureMonitor( power_controller, self._device) self._video_recorder = None self._installed_applications = None self._wpr_ca_cert_path = None self._device_cert_util = None self._is_test_ca_installed = False self._use_rndis_forwarder = ( finder_options.android_rndis or finder_options.browser_options.netsim or platform.GetHostPlatform().GetOSName() != 'linux') _FixPossibleAdbInstability()
def LaunchApplication(self, application, parameters=None, elevate_privilege=False): if application in _HOST_APPLICATIONS: platform.GetHostPlatform().LaunchApplication( application, parameters, elevate_privilege=elevate_privilege) return if elevate_privilege: raise NotImplementedError( "elevate_privilege isn't supported on android.") if not parameters: parameters = '' self._device.RunShellCommand('am start ' + parameters + ' ' + application)
def testPageStatesUserAgentType(self): self.assertUserAgentSetCorrectly( shared_page_state.SharedMobilePageState, 'mobile') if platform_module.GetHostPlatform().GetOSName() == 'chromeos': self.assertUserAgentSetCorrectly( shared_page_state.SharedDesktopPageState, 'chromeos') else: self.assertUserAgentSetCorrectly( shared_page_state.SharedDesktopPageState, 'desktop') self.assertUserAgentSetCorrectly( shared_page_state.SharedTabletPageState, 'tablet') self.assertUserAgentSetCorrectly( shared_page_state.Shared10InchTabletPageState, 'tablet_10_inch') self.assertUserAgentSetCorrectly( shared_page_state.SharedPageState, None)
def FindAllAvailableBrowsers(finder_options, device): """Find all running iOS browsers on connected devices.""" if not isinstance(device, ios_device.IOSDevice): return [] if not CanFindAvailableBrowsers(): return [] options = finder_options.browser_options options.browser_type = 'ios-chrome' host = platform.GetHostPlatform() backend = ios_browser_backend.IosBrowserBackend(host, options) # TODO(baxley): Use idevice to wake up device or log debug statement. if not host.IsApplicationRunning(IOS_WEBKIT_DEBUG_PROXY): host.LaunchApplication(IOS_WEBKIT_DEBUG_PROXY) if not host.IsApplicationRunning(IOS_WEBKIT_DEBUG_PROXY): return [] device_urls = backend.GetDeviceUrls() if not device_urls: logging.debug('Could not find any devices over %s.' % IOS_WEBKIT_DEBUG_PROXY) return [] debug_urls = backend.GetWebSocketDebuggerUrls(device_urls) # Get the userAgent for each UIWebView to find the browsers. browser_pattern = (r'\)\s(%s)\/(\d+[\.\d]*)\sMobile' % '|'.join(IOS_BROWSERS.keys())) browser_types = set() for url in debug_urls: context = {'webSocketDebuggerUrl': url, 'id': 1} try: inspector = inspector_backend.InspectorBackend( backend.app, backend.devtools_client, context) res = inspector.EvaluateJavaScript("navigator.userAgent") finally: inspector.Disconnect() match_browsers = re.search(browser_pattern, res) if match_browsers: browser_types.add(match_browsers.group(1)) browsers = [] for browser_type in browser_types: browsers.append(PossibleIOSBrowser(IOS_BROWSERS[browser_type], finder_options)) return list(browsers)
def __init__(self, adb): self._device = adb.device() is_root_enabled = self._device.old_interface.EnableAdbRoot() assert is_root_enabled, 'RNDIS forwarding requires a rooted device.' self._device_ip = None self._host_iface = None self._host_ip = None self.device_iface = None if platform.GetHostPlatform().GetOSName() == 'mac': self._InstallHorndis() assert self._IsRndisSupported(), 'Device does not support RNDIS.' self._CheckConfigureNetwork()
def FindAllAvailableDevices(options): """Returns a list of available devices. """ # TODO(baxley): Add support for all platforms possible. Probably Linux, # probably not Windows. if platform.GetHostPlatform().GetOSName() != 'mac': return [] if options.chrome_root is None: logging.warning('--chrome-root is not specified, skip iOS simulator tests.') return [] if (not _IsIosDeviceAttached() and not _IsIosSimulatorAvailable(options.chrome_root)): return [] return [IOSDevice()]
def _IsKeychainConfiguredForBots(service_name, account_name): """ Returns True if the keychain entry associated with |service_name| and |account_name| is correctly configured for running telemetry tests on bots. This method will trigger a blocking, modal dialog if the keychain is locked. """ # The executable requires OSX 10.7+ APIs. if (platform.GetHostPlatform().GetOSVersionName() < os_version.LION): return False path = _PathForExecutable('determine_if_keychain_entry_is_decryptable') command = (path, service_name, account_name) child = subprocess.Popen(command) child.communicate() return child.returncode == 0