def SetProperties(device, options): try: device.EnableRoot() except device_errors.CommandFailedError as e: logging.warning(str(e)) _ConfigureLocalProperties(device, options.enable_java_debug) device_settings.ConfigureContentSettings( device, device_settings.DETERMINISTIC_DEVICE_SETTINGS) if options.disable_location: device_settings.ConfigureContentSettings( device, device_settings.DISABLE_LOCATION_SETTINGS) else: device_settings.ConfigureContentSettings( device, device_settings.ENABLE_LOCATION_SETTINGS) device_settings.SetLockScreenSettings(device) if options.disable_network: device_settings.ConfigureContentSettings( device, device_settings.NETWORK_DISABLED_SETTINGS) if options.min_battery_level is not None: try: battery = battery_utils.BatteryUtils(device) battery.ChargeDeviceToLevel(options.min_battery_level) except device_errors.CommandFailedError as e: logging.exception('Unable to charge device to specified level.') if options.max_battery_temp is not None: try: battery = battery_utils.BatteryUtils(device) battery.LetBatteryCoolToTemperature(options.max_battery_temp) except device_errors.CommandFailedError as e: logging.exception( 'Unable to let battery cool to specified temperature.')
def FinishProvisioning(device, options): if options.min_battery_level is not None: try: battery = battery_utils.BatteryUtils(device) battery.ChargeDeviceToLevel(options.min_battery_level) except device_errors.CommandFailedError: logging.exception('Unable to charge device to specified level.') if options.max_battery_temp is not None: try: battery = battery_utils.BatteryUtils(device) battery.LetBatteryCoolToTemperature(options.max_battery_temp) except device_errors.CommandFailedError: logging.exception( 'Unable to let battery cool to specified temperature.') device.RunShellCommand( ['date', '-s', time.strftime('%Y%m%d.%H%M%S', time.gmtime())], as_root=True, check_return=True) props = device.RunShellCommand('getprop', check_return=True) for prop in props: logging.info(' %s' % prop) if options.auto_reconnect: _PushAndLaunchAdbReboot(device, options.target)
def FinishProvisioning(device, options): if options.min_battery_level is not None: try: battery = battery_utils.BatteryUtils(device) battery.ChargeDeviceToLevel(options.min_battery_level) except device_errors.CommandFailedError: logging.exception('Unable to charge device to specified level.') if options.max_battery_temp is not None: try: battery = battery_utils.BatteryUtils(device) battery.LetBatteryCoolToTemperature(options.max_battery_temp) except device_errors.CommandFailedError: logging.exception( 'Unable to let battery cool to specified temperature.') def _set_and_verify_date(): if (device.build_version_sdk >= constants.ANDROID_SDK_VERSION_CODES.MARSHMALLOW): date_format = '%m%d%H%M%Y.%S' set_date_command = ['date'] else: date_format = '%Y%m%d.%H%M%S' set_date_command = ['date', '-s'] strgmtime = time.strftime(date_format, time.gmtime()) set_date_command.append(strgmtime) device.RunShellCommand(set_date_command, as_root=True, check_return=True) device_time = device.RunShellCommand(['date', '+"%Y%m%d.%H%M%S"'], as_root=True, single_line=True).replace( '"', '') device_time = datetime.datetime.strptime(device_time, "%Y%m%d.%H%M%S") correct_time = datetime.datetime.strptime(strgmtime, date_format) tdelta = (correct_time - device_time).seconds if tdelta <= 1: logging.info('Date/time successfully set on %s', device) return True else: return False # Sometimes the date is not set correctly on the devices. Retry on failure. if not timeout_retry.WaitFor( _set_and_verify_date, wait_period=1, max_tries=2): raise device_errors.CommandFailedError('Failed to set date & time.', device_serial=str(device)) props = device.RunShellCommand('getprop', check_return=True) for prop in props: logging.info(' %s' % prop) if options.auto_reconnect: _PushAndLaunchAdbReboot(device, options.target)
def setUp(self): self.adb = device_utils_test._AdbWrapperMock('0123456789abcdef') self.device = device_utils.DeviceUtils( self.adb, default_timeout=10, default_retries=0) self.watchMethodCalls(self.call.adb, ignore=['GetDeviceSerial']) self.battery = battery_utils.BatteryUtils( self.device, default_timeout=10, default_retries=0)
def __init__(self, device, platform_backend): super(DS2784PowerMonitor, self).__init__(platform_backend) self._device = device self._device_battery = battery_utils.BatteryUtils(self._device) self._powermonitor_process_port = None self._file_poller_binary = android_prebuilt_profiler_helper.GetDevicePath( 'file_poller')
def testComposition(self, _): class P1(power_monitor.PowerMonitor): def StartMonitoringPower(self, browser): raise NotImplementedError() def StopMonitoringPower(self): raise NotImplementedError() class P2(power_monitor.PowerMonitor): def __init__(self, value): self._value = value def CanMonitorPower(self): return True def StartMonitoringPower(self, browser): pass def StopMonitoringPower(self): return self._value battery = battery_utils.BatteryUtils(None) controller = power_monitor_controller.PowerMonitorController( [P1(), P2(1), P2(2)], battery) self.assertEqual(controller.CanMonitorPower(), True) controller.StartMonitoringPower(None) self.assertEqual(controller.StopMonitoringPower(), 1)
def ProvisionDevice(device, options): if options.reboot_timeout: reboot_timeout = options.reboot_timeout elif (device.build_version_sdk >= constants.ANDROID_SDK_VERSION_CODES.LOLLIPOP): reboot_timeout = _DEFAULT_TIMEOUTS.LOLLIPOP else: reboot_timeout = _DEFAULT_TIMEOUTS.PRE_LOLLIPOP try: if not options.skip_wipe: WipeDeviceIfPossible(device, reboot_timeout, options) try: device.EnableRoot() except device_errors.CommandFailedError as e: logging.warning(str(e)) _ConfigureLocalProperties(device, options.enable_java_debug) device_settings.ConfigureContentSettings( device, device_settings.DETERMINISTIC_DEVICE_SETTINGS) if options.disable_location: device_settings.ConfigureContentSettings( device, device_settings.DISABLE_LOCATION_SETTINGS) else: device_settings.ConfigureContentSettings( device, device_settings.ENABLE_LOCATION_SETTINGS) device_settings.SetLockScreenSettings(device) if options.disable_network: device_settings.ConfigureContentSettings( device, device_settings.NETWORK_DISABLED_SETTINGS) if options.min_battery_level is not None: try: battery = battery_utils.BatteryUtils(device) battery.ChargeDeviceToLevel(options.min_battery_level) except device_errors.CommandFailedError as e: logging.exception( 'Unable to charge device to specified level.') if not options.skip_wipe: device.Reboot(True, timeout=reboot_timeout, retries=0) device.RunShellCommand('date -s %s' % time.strftime('%Y%m%d.%H%M%S', time.gmtime()), as_root=True) props = device.RunShellCommand('getprop') for prop in props: logging.info(' %s' % prop) if options.auto_reconnect: PushAndLaunchAdbReboot(device, options.target) except (errors.WaitForResponseTimedOutError, device_errors.CommandTimeoutError): logging.info('Timed out waiting for device %s. Adding to blacklist.', str(device)) # Device black list is reset by bb_device_status_check.py per build. device_blacklist.ExtendBlacklist([str(device)]) except device_errors.CommandFailedError: logging.exception( 'Failed to provision device %s. Adding to blacklist.', str(device)) device_blacklist.ExtendBlacklist([str(device)])
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: logging.exception('New exception caused by DeviceUtils conversion') raise self._device_copy_script = None self._power_monitor = power_monitor_controller.PowerMonitorController([ 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 __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 __init__(self, test_options, device, shard_index, max_shard, tests, flaky_tests): """A TestRunner instance runs a perf test on a single device. Args: test_options: A PerfOptions object. device: Device to run the tests. shard_index: the index of this device. max_shards: the maximum shard index. tests: a dict mapping test_name to command. flaky_tests: a list of flaky test_name. """ super(TestRunner, self).__init__(device, None) self._options = test_options self._shard_index = shard_index self._max_shard = max_shard self._tests = tests self._flaky_tests = flaky_tests self._output_dir = None self._device_battery = battery_utils.BatteryUtils(self.device)
def testInitWithMissing_fails(self): with self.assertRaises(TypeError): battery_utils.BatteryUtils(None) with self.assertRaises(TypeError): battery_utils.BatteryUtils('')
def testInitWithDeviceUtil(self): serial = '0fedcba987654321' d = device_utils.DeviceUtils(serial) b = battery_utils.BatteryUtils(d) self.assertEqual(d, b._device)
def DeviceInfo(device, options): """Gathers info on a device via various adb calls. Args: device: A DeviceUtils instance for the device to construct info about. Returns: Tuple of device type, build id, report as a string, error messages, and boolean indicating whether or not device can be used for testing. """ battery = battery_utils.BatteryUtils(device) build_product = '' build_id = '' battery_level = 100 errors = [] dev_good = True json_data = {} try: build_product = device.build_product build_id = device.build_id json_data = { 'serial': device.adb.GetDeviceSerial(), 'type': build_product, 'build': build_id, 'build_detail': device.GetProp('ro.build.fingerprint'), 'battery': {}, 'imei_slice': 'Unknown', 'wifi_ip': device.GetProp('dhcp.wlan0.ipaddress'), } battery_info = {} try: battery_info = battery.GetBatteryInfo(timeout=5) battery_level = int(battery_info.get('level', battery_level)) json_data['battery'] = battery_info except device_errors.CommandFailedError: logging.exception('Failed to get battery information for %s', str(device)) try: for l in device.RunShellCommand(['dumpsys', 'iphonesubinfo'], check_return=True, timeout=5): m = _RE_DEVICE_ID.match(l) if m: json_data['imei_slice'] = m.group(1)[-6:] except device_errors.CommandFailedError: logging.exception('Failed to get IMEI slice for %s', str(device)) if battery_level < 15: errors += ['Device critically low in battery.'] dev_good = False if not battery.GetCharging(): battery.SetCharging(True) if not options.no_provisioning_check: setup_wizard_disabled = ( device.GetProp('ro.setupwizard.mode') == 'DISABLED') if not setup_wizard_disabled and device.build_type != 'user': errors += [ 'Setup wizard not disabled. Was it provisioned correctly?' ] if (device.product_name == 'mantaray' and battery_info.get('AC powered', None) != 'true'): errors += ['Mantaray device not connected to AC power.'] except device_errors.CommandFailedError: logging.exception('Failure while getting device status.') dev_good = False except device_errors.CommandTimeoutError: logging.exception('Timeout while getting device status.') dev_good = False return (build_product, build_id, battery_level, errors, dev_good, json_data)
def testReenableCharingIfNeeded(self, mock_battery): battery = battery_utils.BatteryUtils(None) battery.GetCharging.return_value = False power_monitor_controller._ReenableChargingIfNeeded(battery)
def testInitWithDeviceUtil(self): serial = '0fedcba987654321' a = android_commands.AndroidCommands(device=serial) d = device_utils.DeviceUtils(a) b = battery_utils.BatteryUtils(d) self.assertEqual(d, b._device)