diff options
author | jbudorick@chromium.org <jbudorick@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2014-06-25 05:09:06 +0000 |
---|---|---|
committer | jbudorick@chromium.org <jbudorick@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2014-06-25 05:09:06 +0000 |
commit | 402e54cdd29cdb022edaebcbe4e0ba44662647c6 (patch) | |
tree | 3804b88c2b65692f27df8a4f92cba6dc37110f41 | |
parent | acbb5366e5b2299fe1868938ec5e9876baa10f98 (diff) | |
download | chromium_src-402e54cdd29cdb022edaebcbe4e0ba44662647c6.zip chromium_src-402e54cdd29cdb022edaebcbe4e0ba44662647c6.tar.gz chromium_src-402e54cdd29cdb022edaebcbe4e0ba44662647c6.tar.bz2 |
[Android] Switch KillAll, StartActivity, and BroadcastIntent to DeviceUtils.
BUG=267773
Review URL: https://codereview.chromium.org/338353004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@279599 0039d316-1c4b-4281-b951-d872f2087c98
27 files changed, 575 insertions, 110 deletions
diff --git a/build/android/provision_devices.py b/build/android/provision_devices.py index 4104425..f80eea2 100755 --- a/build/android/provision_devices.py +++ b/build/android/provision_devices.py @@ -21,6 +21,7 @@ import time from pylib import android_commands from pylib import constants from pylib import device_settings +from pylib.device import device_errors from pylib.device import device_utils sys.path.append(os.path.join(constants.DIR_SOURCE_ROOT, @@ -59,7 +60,14 @@ def PushAndLaunchAdbReboot(devices, target): print 'Will push and launch adb_reboot on %s' % device_serial device = device_utils.DeviceUtils(device_serial) # Kill if adb_reboot is already running. - device.old_interface.KillAllBlocking('adb_reboot', 2) + try: + # Don't try to kill adb_reboot more than once. We don't expect it to be + # running at all. + device.KillAll('adb_reboot', blocking=True, timeout=2, retries=0) + except device_errors.CommandFailedError: + # We can safely ignore the exception because we don't expect adb_reboot + # to be running. + pass # Push adb_reboot print ' Pushing adb_reboot ...' adb_reboot = os.path.join(constants.DIR_SOURCE_ROOT, @@ -89,7 +97,7 @@ def _ConfigureLocalProperties(device, is_perf): # Android will not respect the local props file if it is world writable. device.RunShellCommand( 'chmod 644 %s' % constants.DEVICE_LOCAL_PROPERTIES_PATH, - root=True) + as_root=True) # LOCAL_PROPERTIES_PATH = '/data/local.prop' @@ -110,12 +118,12 @@ def WipeDeviceData(device): constants.ADB_KEYS_FILE) if device_authorized: adb_keys = device.RunShellCommand('cat %s' % constants.ADB_KEYS_FILE, - root=True) - device.RunShellCommand('wipe data', root=True) + as_root=True) + device.RunShellCommand('wipe data', as_root=True) if device_authorized: path_list = constants.ADB_KEYS_FILE.split('/') dir_path = '/'.join(path_list[:len(path_list)-1]) - device.RunShellCommand('mkdir -p %s' % dir_path, root=True) + device.RunShellCommand('mkdir -p %s' % dir_path, as_root=True) device.RunShellCommand('echo %s > %s' % (adb_keys[0], constants.ADB_KEYS_FILE)) for adb_key in adb_keys[1:]: @@ -182,7 +190,7 @@ def ProvisionDevices(options): battery_info.get('level', 0)) time.sleep(60) battery_info = device.old_interface.GetBatteryInfo() - device.RunShellCommand('date -u %f' % time.time(), root=True) + device.RunShellCommand('date -u %f' % time.time(), as_root=True) try: device_utils.DeviceUtils.parallel(devices).Reboot(True) except errors.DeviceUnresponsiveError: diff --git a/build/android/pylib/android_commands.py b/build/android/pylib/android_commands.py index 253dc2b..af3ec10 100644 --- a/build/android/pylib/android_commands.py +++ b/build/android/pylib/android_commands.py @@ -757,7 +757,7 @@ class AndroidCommands(object): self.RunShellCommand(cmd) return len(pids) - def KillAllBlocking(self, process, timeout_sec): + def KillAllBlocking(self, process, timeout_sec, signum=9, with_su=False): """Blocking version of killall, connected via adb. This waits until no process matching the corresponding name appears in ps' @@ -766,11 +766,12 @@ class AndroidCommands(object): Args: process: name of the process to kill off timeout_sec: the timeout in seconds - + signum: same as |KillAll| + with_su: same as |KillAll| Returns: the number of processes killed """ - processes_killed = self.KillAll(process) + processes_killed = self.KillAll(process, signum=signum, with_su=with_su) if processes_killed: elapsed = 0 wait_period = 0.1 @@ -779,7 +780,7 @@ class AndroidCommands(object): time.sleep(wait_period) elapsed += wait_period if elapsed >= timeout_sec: - return 0 + return processes_killed - self.ExtractPid(process) return processes_killed @staticmethod @@ -842,11 +843,13 @@ class AndroidCommands(object): trace_file_name: If used, turns on and saves the trace to this file name. force_stop: force stop the target app before starting the activity (-S flag). + Returns: + The output of the underlying command as a list of lines. """ cmd = self._GetActivityCommand(package, activity, wait_for_completion, action, category, data, extras, trace_file_name, force_stop, flags) - self.RunShellCommand(cmd) + return self.RunShellCommand(cmd) def StartActivityTimed(self, package, activity, wait_for_completion=False, action='android.intent.action.VIEW', @@ -858,18 +861,20 @@ class AndroidCommands(object): Args - as for StartActivity Returns: - a timestamp string for the time at which the activity started + A tuple containing: + - the output of the underlying command as a list of lines, and + - a timestamp string for the time at which the activity started """ cmd = self._GetActivityCommand(package, activity, wait_for_completion, action, category, data, extras, trace_file_name, force_stop, flags) self.StartMonitoringLogcat() - self.RunShellCommand('log starting activity; ' + cmd) + out = self.RunShellCommand('log starting activity; ' + cmd) activity_started_re = re.compile('.*starting activity.*') m = self.WaitForLogMatch(activity_started_re, None) assert m start_line = m.group(0) - return GetLogTimestamp(start_line, self.GetDeviceYear()) + return (out, GetLogTimestamp(start_line, self.GetDeviceYear())) def StartCrashUploadService(self, package): # TODO(frankf): We really need a python wrapper around Intent diff --git a/build/android/pylib/content_settings.py b/build/android/pylib/content_settings.py index 54cedfe..172eedb 100644 --- a/build/android/pylib/content_settings.py +++ b/build/android/pylib/content_settings.py @@ -41,7 +41,7 @@ class ContentSettings(dict): # Example row: # 'Row: 0 _id=13, name=logging_id2, value=-1fccbaa546705b05' for row in self._device.RunShellCommand( - 'content query --uri content://%s' % self._table, root=True): + 'content query --uri content://%s' % self._table, as_root=True): fields = row.split(', ') key = None value = None @@ -57,7 +57,7 @@ class ContentSettings(dict): def __getitem__(self, key): return self._device.RunShellCommand( 'content query --uri content://%s --where "name=\'%s\'" ' - '--projection value' % (self._table, key), root=True).strip() + '--projection value' % (self._table, key), as_root=True).strip() def __setitem__(self, key, value): if key in self: @@ -66,7 +66,7 @@ class ContentSettings(dict): '--bind value:%s:%s --where "name=\'%s\'"' % ( self._table, self._GetTypeBinding(value), value, key), - root=True) + as_root=True) else: self._device.RunShellCommand( 'content insert --uri content://%s ' @@ -74,7 +74,7 @@ class ContentSettings(dict): self._table, self._GetTypeBinding(key), key, self._GetTypeBinding(value), value), - root=True) + as_root=True) def __delitem__(self, key): self._device.RunShellCommand( @@ -82,4 +82,4 @@ class ContentSettings(dict): '--bind name:%s:%s' % ( self._table, self._GetTypeBinding(key), key), - root=True) + as_root=True) diff --git a/build/android/pylib/device/adb_wrapper.py b/build/android/pylib/device/adb_wrapper.py index e3fb897..f4a5931 100644 --- a/build/android/pylib/device/adb_wrapper.py +++ b/build/android/pylib/device/adb_wrapper.py @@ -51,14 +51,14 @@ class AdbWrapper(object): cmd = ['adb'] + arg_list exit_code, output = cmd_helper.GetCmdStatusAndOutput(cmd) if exit_code != 0: - raise device_errors.CommandFailedError( + raise device_errors.AdbCommandFailedError( cmd, 'returned non-zero exit code %s, output: %s' % (exit_code, output)) # This catches some errors, including when the device drops offline; # unfortunately adb is very inconsistent with error reporting so many # command failures present differently. if check_error and output[:len('error:')] == 'error:': - raise device_errors.CommandFailedError(arg_list, output) + raise device_errors.AdbCommandFailedError(arg_list, output) return output # pylint: enable=W0613 @@ -165,7 +165,7 @@ class AdbWrapper(object): The output of the shell command as a string. Raises: - device_errors.CommandFailedError: If the return code doesn't match + device_errors.AdbCommandFailedError: If the return code doesn't match |expect_rc|. """ if expect_rc is None: @@ -179,7 +179,7 @@ class AdbWrapper(object): rc = output[output_end:].strip() output = output[:output_end] if int(rc) != expect_rc: - raise device_errors.CommandFailedError( + raise device_errors.AdbCommandFailedError( ['shell', command], 'shell command exited with code: %s' % rc, self._device_serial) @@ -258,7 +258,7 @@ class AdbWrapper(object): cmd.append(apk_path) output = self._DeviceAdbCmd(cmd, timeout, retries) if 'Success' not in output: - raise device_errors.CommandFailedError(cmd, output) + raise device_errors.AdbCommandFailedError(cmd, output) def Uninstall(self, package, keep_data=False, timeout=_DEFAULT_TIMEOUT, retries=_DEFAULT_RETRIES): @@ -276,7 +276,7 @@ class AdbWrapper(object): cmd.append(package) output = self._DeviceAdbCmd(cmd, timeout, retries) if 'Failure' in output: - raise device_errors.CommandFailedError(cmd, output) + raise device_errors.AdbCommandFailedError(cmd, output) def Backup(self, path, packages=None, apk=False, shared=False, nosystem=True, include_all=False, timeout=_DEFAULT_TIMEOUT, @@ -383,5 +383,5 @@ class AdbWrapper(object): """ output = self._DeviceAdbCmd(['root'], timeout, retries) if 'cannot' in output: - raise device_errors.CommandFailedError(['root'], output) + raise device_errors.AdbCommandFailedError(['root'], output) diff --git a/build/android/pylib/device/adb_wrapper_test.py b/build/android/pylib/device/adb_wrapper_test.py index 6325404..08b7fcc 100644 --- a/build/android/pylib/device/adb_wrapper_test.py +++ b/build/android/pylib/device/adb_wrapper_test.py @@ -41,7 +41,7 @@ class TestAdbWrapper(unittest.TestCase): self.assertEqual(output.strip(), 'test') output = self._adb.Shell('echo test') self.assertEqual(output.strip(), 'test') - self.assertRaises(device_errors.CommandFailedError, self._adb.Shell, + self.assertRaises(device_errors.AdbCommandFailedError, self._adb.Shell, 'echo test', expect_rc=1) def testPushPull(self): @@ -56,13 +56,15 @@ class TestAdbWrapper(unittest.TestCase): def testInstall(self): path = self._MakeTempFile('foo') - self.assertRaises(device_errors.CommandFailedError, self._adb.Install, path) + self.assertRaises(device_errors.AdbCommandFailedError, self._adb.Install, + path) def testForward(self): - self.assertRaises(device_errors.CommandFailedError, self._adb.Forward, 0, 0) + self.assertRaises(device_errors.AdbCommandFailedError, self._adb.Forward, + 0, 0) def testUninstall(self): - self.assertRaises(device_errors.CommandFailedError, self._adb.Uninstall, + self.assertRaises(device_errors.AdbCommandFailedError, self._adb.Uninstall, 'some.nonexistant.package') def testRebootWaitForDevice(self): @@ -82,7 +84,7 @@ class TestAdbWrapper(unittest.TestCase): try: self._adb.Shell('start') break - except device_errors.CommandFailedError: + except device_errors.AdbCommandFailedError: time.sleep(1) self._adb.Remount() diff --git a/build/android/pylib/device/decorators_test.py b/build/android/pylib/device/decorators_test.py index 0869413..1ae8cb9 100644 --- a/build/android/pylib/device/decorators_test.py +++ b/build/android/pylib/device/decorators_test.py @@ -52,8 +52,7 @@ class DecoratorsTest(unittest.TestCase): @decorators.WithTimeoutAndRetries def alwaysRaisesCommandFailedError(timeout=None, retries=None): DecoratorsTest._decorated_function_called_count += 1 - raise device_errors.CommandFailedError(['testCommand'], - 'testCommand failed') + raise device_errors.CommandFailedError('testCommand failed') with self.assertRaises(device_errors.CommandFailedError): alwaysRaisesCommandFailedError(timeout=30, retries=10) @@ -140,8 +139,7 @@ class DecoratorsTest(unittest.TestCase): @decorators.WithTimeoutAndRetriesDefaults(30, 10) def alwaysRaisesCommandFailedError(timeout=None, retries=None): DecoratorsTest._decorated_function_called_count += 1 - raise device_errors.CommandFailedError(['testCommand'], - 'testCommand failed') + raise device_errors.CommandFailedError('testCommand failed') with self.assertRaises(device_errors.CommandFailedError): alwaysRaisesCommandFailedError() @@ -219,8 +217,7 @@ class DecoratorsTest(unittest.TestCase): @decorators.WithExplicitTimeoutAndRetries(30, 10) def alwaysRaisesCommandFailedError(): DecoratorsTest._decorated_function_called_count += 1 - raise device_errors.CommandFailedError(['testCommand'], - 'testCommand failed') + raise device_errors.CommandFailedError('testCommand failed') with self.assertRaises(device_errors.CommandFailedError): alwaysRaisesCommandFailedError() @@ -281,8 +278,7 @@ class DecoratorsTest(unittest.TestCase): 'default_timeout', 'default_retries') def alwaysRaisesCommandFailedError(self, timeout=None, retries=None): self.function_call_counters['alwaysRaisesCommandFailedError'] += 1 - raise device_errors.CommandFailedError(['testCommand'], - 'testCommand failed') + raise device_errors.CommandFailedError('testCommand failed') # pylint: disable=R0201 diff --git a/build/android/pylib/device/device_errors.py b/build/android/pylib/device/device_errors.py index 1db7c1b..7cfc873 100644 --- a/build/android/pylib/device/device_errors.py +++ b/build/android/pylib/device/device_errors.py @@ -14,10 +14,18 @@ class BaseError(Exception): class CommandFailedError(BaseError): """Exception for command failures.""" - def __init__(self, cmd, msg, device=None): + def __init__(self, msg, device=None): super(CommandFailedError, self).__init__( - (('device %s: ' % device) if device else '') + - 'adb command \'%s\' failed with message: \'%s\'' % (' '.join(cmd), msg)) + '%s%s' % ('(device: %s) ' % device if device else '', msg)) + + +class AdbCommandFailedError(CommandFailedError): + """Exception for adb command failures.""" + + def __init__(self, cmd, msg, device=None): + super(AdbCommandFailedError, self).__init__( + 'adb command \'%s\' failed with message: \'%s\'' % (' '.join(cmd), msg), + device=device) class CommandTimeoutError(BaseError): diff --git a/build/android/pylib/device/device_utils.py b/build/android/pylib/device/device_utils.py index 27e3d41..e4c66525 100644 --- a/build/android/pylib/device/device_utils.py +++ b/build/android/pylib/device/device_utils.py @@ -8,6 +8,7 @@ Eventually, this will be based on adb_wrapper. """ # pylint: disable=W0613 +import sys import time import pylib.android_commands @@ -124,7 +125,7 @@ class DeviceUtils(object): """ if not self.old_interface.EnableAdbRoot(): raise device_errors.CommandFailedError( - ['adb', 'root'], 'Could not enable root.') + 'Could not enable root.', device=str(self)) @decorators.WithTimeoutAndRetriesFromInstance() def GetExternalStoragePath(self, timeout=None, retries=None): @@ -140,7 +141,7 @@ class DeviceUtils(object): return self.old_interface.GetExternalStorage() except AssertionError as e: raise device_errors.CommandFailedError( - ['adb', 'shell', 'echo', '$EXTERNAL_STORAGE'], str(e)) + str(e), device=str(self)), None, sys.exc_info()[2] @decorators.WithTimeoutAndRetriesFromInstance() def WaitUntilFullyBooted(self, wifi=False, timeout=None, retries=None): @@ -235,7 +236,7 @@ class DeviceUtils(object): for line in out.splitlines(): if 'Failure' in line: raise device_errors.CommandFailedError( - ['adb', 'uninstall', package_name], line.strip()) + line.strip(), device=str(self)) else: should_install = False else: @@ -246,14 +247,14 @@ class DeviceUtils(object): for line in out.splitlines(): if 'Failure' in line: raise device_errors.CommandFailedError( - ['adb', 'install', apk_path], line.strip()) + line.strip(), device=str(self)) except AssertionError as e: raise device_errors.CommandFailedError( - ['adb', 'install', apk_path], str(e)) + str(e), device=str(self)), None, sys.exc_info()[2] @decorators.WithTimeoutAndRetriesFromInstance() - def RunShellCommand(self, cmd, check_return=False, root=False, timeout=None, - retries=None): + def RunShellCommand(self, cmd, check_return=False, as_root=False, + timeout=None, retries=None): """Run an ADB shell command. TODO(jbudorick) Switch the default value of check_return to True after @@ -263,6 +264,8 @@ class DeviceUtils(object): cmd: A list containing the command to run on the device and any arguments. check_return: A boolean indicating whether or not the return code should be checked. + as_root: A boolean indicating whether the shell command should be run + with root privileges. timeout: Same as for |IsOnline|. retries: Same as for |IsOnline|. Raises: @@ -270,10 +273,10 @@ class DeviceUtils(object): Returns: The output of the command. """ - return self._RunShellCommandImpl(cmd, check_return=check_return, root=root, - timeout=timeout) + return self._RunShellCommandImpl(cmd, check_return=check_return, + as_root=as_root, timeout=timeout) - def _RunShellCommandImpl(self, cmd, check_return=False, root=False, + def _RunShellCommandImpl(self, cmd, check_return=False, as_root=False, timeout=None): """Implementation of RunShellCommand. @@ -286,6 +289,7 @@ class DeviceUtils(object): Args: cmd: Same as for |RunShellCommand|. check_return: Same as for |RunShellCommand|. + as_root: Same as for |RunShellCommand|. timeout: Same as for |IsOnline|. Raises: Same as for |RunShellCommand|. @@ -294,18 +298,98 @@ class DeviceUtils(object): """ if isinstance(cmd, list): cmd = ' '.join(cmd) - if root and not self.HasRoot(): + if as_root and not self.HasRoot(): cmd = 'su -c %s' % cmd if check_return: code, output = self.old_interface.GetShellCommandStatusAndOutput( cmd, timeout_time=timeout) if int(code) != 0: - raise device_errors.CommandFailedError( - cmd.split(), 'Nonzero exit code (%d)' % code) + raise device_errors.AdbCommandFailedError( + cmd.split(), 'Nonzero exit code (%d)' % code, device=str(self)) else: output = self.old_interface.RunShellCommand(cmd, timeout_time=timeout) return output + @decorators.WithTimeoutAndRetriesFromInstance() + def KillAll(self, process_name, signum=9, as_root=False, blocking=False, + timeout=None, retries=None): + """Kill all processes with the given name on the device. + + Args: + process_name: A string containing the name of the process to kill. + signum: An integer containing the signal number to send to kill. Defaults + to 9 (SIGKILL). + as_root: A boolean indicating whether the kill should be executed with + root priveleges. + blocking: A boolean indicating whether we should wait until all processes + with the given |process_name| are dead. + timeout: Same as for |IsOnline|. + retries: Same as for |IsOnline|. + Raises: + CommandFailedError if no process was killed. + """ + pids = self.old_interface.ExtractPid(process_name) + if len(pids) == 0: + raise device_errors.CommandFailedError( + 'No process "%s"' % process_name, device=str(self)) + + if blocking: + total_killed = self.old_interface.KillAllBlocking( + process_name, signum=signum, with_su=as_root, timeout_sec=timeout) + else: + total_killed = self.old_interface.KillAll( + process_name, signum=signum, with_su=as_root) + if total_killed == 0: + raise device_errors.CommandFailedError( + 'Failed to kill "%s"' % process_name, device=str(self)) + + @decorators.WithTimeoutAndRetriesFromInstance() + def StartActivity(self, intent, blocking=False, trace_file_name=None, + force_stop=False, timeout=None, retries=None): + """Start package's activity on the device. + + Args: + intent: An Intent to send. + blocking: A boolean indicating whether we should wait for the activity to + finish launching. + trace_file_name: If present, a string that both indicates that we want to + profile the activity and contains the path to which the + trace should be saved. + force_stop: A boolean indicating whether we should stop the activity + before starting it. + timeout: Same as for |IsOnline|. + retries: Same as for |IsOnline|. + Raises: + CommandFailedError if the activity could not be started. + """ + single_category = (intent.category[0] if isinstance(intent.category, list) + else intent.category) + output = self.old_interface.StartActivity( + intent.package, intent.activity, wait_for_completion=blocking, + action=intent.action, category=single_category, data=intent.data, + extras=intent.extras, trace_file_name=trace_file_name, + force_stop=force_stop, flags=intent.flags) + for l in output: + if l.startswith('Error:'): + raise device_errors.CommandFailedError(l, device=str(self)) + + @decorators.WithTimeoutAndRetriesFromInstance() + def BroadcastIntent(self, intent, timeout=None, retries=None): + """Send a broadcast intent. + + Args: + intent: An Intent to broadcast. + timeout: Same as for |IsOnline|. + retries: Same as for |IsOnline|. + """ + package, old_intent = intent.action.rsplit('.', 1) + if intent.extras is None: + args = [] + else: + args = ['-e %s%s' % (k, ' "%s"' % v if v else '') + for k, v in intent.extras.items() if len(k) > 0] + self.old_interface.BroadcastIntent(package, old_intent, *args) + def __str__(self): """Returns the device serial.""" return self.old_interface.GetDevice() diff --git a/build/android/pylib/device/device_utils_test.py b/build/android/pylib/device/device_utils_test.py index 0682ae2..5b34673 100644 --- a/build/android/pylib/device/device_utils_test.py +++ b/build/android/pylib/device/device_utils_test.py @@ -11,6 +11,7 @@ Unit tests for the contents of device_utils.py (mostly DeviceUtils). # pylint: disable=W0613 import os +import signal import sys import unittest @@ -19,6 +20,7 @@ from pylib import constants from pylib.device import adb_wrapper from pylib.device import device_errors from pylib.device import device_utils +from pylib.device import intent sys.path.append(os.path.join( constants.DIR_SOURCE_ROOT, 'third_party', 'android_testrunner')) @@ -403,13 +405,13 @@ class DeviceUtilsOldImplTest(unittest.TestCase): ("adb -s 0123456789abcdef shell 'ls /root'", 'Permission denied\r\n'), ("adb -s 0123456789abcdef shell 'su -c setprop service.adb.root 0'", '')]): - self.device.RunShellCommand('setprop service.adb.root 0', root=True) + self.device.RunShellCommand('setprop service.adb.root 0', as_root=True) def testRunShellCommand_withRoot(self): with self.assertOldImplCallsSequence([ ("adb -s 0123456789abcdef shell 'ls /root'", 'hello\r\nworld\r\n'), ("adb -s 0123456789abcdef shell 'setprop service.adb.root 0'", '')]): - self.device.RunShellCommand('setprop service.adb.root 0', root=True) + self.device.RunShellCommand('setprop service.adb.root 0', as_root=True) def testRunShellCommand_checkReturn_success(self): with self.assertOldImplCalls( @@ -424,6 +426,263 @@ class DeviceUtilsOldImplTest(unittest.TestCase): with self.assertRaises(device_errors.CommandFailedError): self.device.RunShellCommand('echo $ANDROID_DATA', check_return=True) + def testKillAll_noMatchingProcesses(self): + with self.assertOldImplCalls( + "adb -s 0123456789abcdef shell 'ps'", + 'USER PID PPID VSIZE RSS WCHAN PC NAME\r\n'): + with self.assertRaises(device_errors.CommandFailedError): + self.device.KillAll('test_process') + + def testKillAll_nonblocking(self): + with self.assertOldImplCallsSequence([ + ("adb -s 0123456789abcdef shell 'ps'", + 'USER PID PPID VSIZE RSS WCHAN PC NAME\r\n' + 'u0_a1 1234 174 123456 54321 ffffffff 456789ab ' + 'this.is.a.test.process\r\n'), + ("adb -s 0123456789abcdef shell 'ps'", + 'USER PID PPID VSIZE RSS WCHAN PC NAME\r\n' + 'u0_a1 1234 174 123456 54321 ffffffff 456789ab ' + 'this.is.a.test.process\r\n'), + ("adb -s 0123456789abcdef shell 'kill -9 1234'", '')]): + self.device.KillAll('this.is.a.test.process', blocking=False) + + def testKillAll_blocking(self): + with mock.patch('time.sleep'): + with self.assertOldImplCallsSequence([ + ("adb -s 0123456789abcdef shell 'ps'", + 'USER PID PPID VSIZE RSS WCHAN PC NAME\r\n' + 'u0_a1 1234 174 123456 54321 ffffffff 456789ab ' + 'this.is.a.test.process\r\n'), + ("adb -s 0123456789abcdef shell 'ps'", + 'USER PID PPID VSIZE RSS WCHAN PC NAME\r\n' + 'u0_a1 1234 174 123456 54321 ffffffff 456789ab ' + 'this.is.a.test.process\r\n'), + ("adb -s 0123456789abcdef shell 'kill -9 1234'", ''), + ("adb -s 0123456789abcdef shell 'ps'", + 'USER PID PPID VSIZE RSS WCHAN PC NAME\r\n' + 'u0_a1 1234 174 123456 54321 ffffffff 456789ab ' + 'this.is.a.test.process\r\n'), + ("adb -s 0123456789abcdef shell 'ps'", + 'USER PID PPID VSIZE RSS WCHAN PC NAME\r\n')]): + self.device.KillAll('this.is.a.test.process', blocking=True) + + def testKillAll_root(self): + with self.assertOldImplCallsSequence([ + ("adb -s 0123456789abcdef shell 'ps'", + 'USER PID PPID VSIZE RSS WCHAN PC NAME\r\n' + 'u0_a1 1234 174 123456 54321 ffffffff 456789ab ' + 'this.is.a.test.process\r\n'), + ("adb -s 0123456789abcdef shell 'ps'", + 'USER PID PPID VSIZE RSS WCHAN PC NAME\r\n' + 'u0_a1 1234 174 123456 54321 ffffffff 456789ab ' + 'this.is.a.test.process\r\n'), + ("adb -s 0123456789abcdef shell 'su -c kill -9 1234'", '')]): + self.device.KillAll('this.is.a.test.process', as_root=True) + + def testKillAll_sigterm(self): + with self.assertOldImplCallsSequence([ + ("adb -s 0123456789abcdef shell 'ps'", + 'USER PID PPID VSIZE RSS WCHAN PC NAME\r\n' + 'u0_a1 1234 174 123456 54321 ffffffff 456789ab ' + 'this.is.a.test.process\r\n'), + ("adb -s 0123456789abcdef shell 'ps'", + 'USER PID PPID VSIZE RSS WCHAN PC NAME\r\n' + 'u0_a1 1234 174 123456 54321 ffffffff 456789ab ' + 'this.is.a.test.process\r\n'), + ("adb -s 0123456789abcdef shell 'kill -15 1234'", '')]): + self.device.KillAll('this.is.a.test.process', signum=signal.SIGTERM) + + def testStartActivity_actionOnly(self): + test_intent = intent.Intent(action='android.intent.action.VIEW') + with self.assertOldImplCalls( + "adb -s 0123456789abcdef shell 'am start " + "-a android.intent.action.VIEW'", + 'Starting: Intent { act=android.intent.action.VIEW }'): + self.device.StartActivity(test_intent) + + def testStartActivity_success(self): + test_intent = intent.Intent(action='android.intent.action.VIEW', + package='this.is.a.test.package', + activity='.Main') + with self.assertOldImplCalls( + "adb -s 0123456789abcdef shell 'am start " + "-a android.intent.action.VIEW " + "-n this.is.a.test.package/.Main'", + 'Starting: Intent { act=android.intent.action.VIEW }'): + self.device.StartActivity(test_intent) + + def testStartActivity_failure(self): + test_intent = intent.Intent(action='android.intent.action.VIEW', + package='this.is.a.test.package', + activity='.Main') + with self.assertOldImplCalls( + "adb -s 0123456789abcdef shell 'am start " + "-a android.intent.action.VIEW " + "-n this.is.a.test.package/.Main'", + 'Error: Failed to start test activity'): + with self.assertRaises(device_errors.CommandFailedError): + self.device.StartActivity(test_intent) + + def testStartActivity_blocking(self): + test_intent = intent.Intent(action='android.intent.action.VIEW', + package='this.is.a.test.package', + activity='.Main') + with self.assertOldImplCalls( + "adb -s 0123456789abcdef shell 'am start " + "-a android.intent.action.VIEW " + "-W " + "-n this.is.a.test.package/.Main'", + 'Starting: Intent { act=android.intent.action.VIEW }'): + self.device.StartActivity(test_intent, blocking=True) + + def testStartActivity_withCategory(self): + test_intent = intent.Intent(action='android.intent.action.VIEW', + package='this.is.a.test.package', + activity='.Main', + category='android.intent.category.HOME') + with self.assertOldImplCalls( + "adb -s 0123456789abcdef shell 'am start " + "-a android.intent.action.VIEW " + "-c android.intent.category.HOME " + "-n this.is.a.test.package/.Main'", + 'Starting: Intent { act=android.intent.action.VIEW }'): + self.device.StartActivity(test_intent) + + def testStartActivity_withMultipleCategories(self): + # The new implementation will start the activity with all provided + # categories. The old one only uses the first category. + test_intent = intent.Intent(action='android.intent.action.VIEW', + package='this.is.a.test.package', + activity='.Main', + category=['android.intent.category.HOME', + 'android.intent.category.BROWSABLE']) + with self.assertOldImplCalls( + "adb -s 0123456789abcdef shell 'am start " + "-a android.intent.action.VIEW " + "-c android.intent.category.HOME " + "-n this.is.a.test.package/.Main'", + 'Starting: Intent { act=android.intent.action.VIEW }'): + self.device.StartActivity(test_intent) + + def testStartActivity_withData(self): + test_intent = intent.Intent(action='android.intent.action.VIEW', + package='this.is.a.test.package', + activity='.Main', + data='http://www.google.com/') + with self.assertOldImplCalls( + "adb -s 0123456789abcdef shell 'am start " + "-a android.intent.action.VIEW " + "-n this.is.a.test.package/.Main " + "-d \"http://www.google.com/\"'", + 'Starting: Intent { act=android.intent.action.VIEW }'): + self.device.StartActivity(test_intent) + + def testStartActivity_withStringExtra(self): + test_intent = intent.Intent(action='android.intent.action.VIEW', + package='this.is.a.test.package', + activity='.Main', + extras={'foo': 'test'}) + with self.assertOldImplCalls( + "adb -s 0123456789abcdef shell 'am start " + "-a android.intent.action.VIEW " + "-n this.is.a.test.package/.Main " + "--es foo test'", + 'Starting: Intent { act=android.intent.action.VIEW }'): + self.device.StartActivity(test_intent) + + def testStartActivity_withBoolExtra(self): + test_intent = intent.Intent(action='android.intent.action.VIEW', + package='this.is.a.test.package', + activity='.Main', + extras={'foo': True}) + with self.assertOldImplCalls( + "adb -s 0123456789abcdef shell 'am start " + "-a android.intent.action.VIEW " + "-n this.is.a.test.package/.Main " + "--ez foo True'", + 'Starting: Intent { act=android.intent.action.VIEW }'): + self.device.StartActivity(test_intent) + + def testStartActivity_withIntExtra(self): + test_intent = intent.Intent(action='android.intent.action.VIEW', + package='this.is.a.test.package', + activity='.Main', + extras={'foo': 123}) + with self.assertOldImplCalls( + "adb -s 0123456789abcdef shell 'am start " + "-a android.intent.action.VIEW " + "-n this.is.a.test.package/.Main " + "--ei foo 123'", + 'Starting: Intent { act=android.intent.action.VIEW }'): + self.device.StartActivity(test_intent) + + def testStartActivity_withTraceFile(self): + test_intent = intent.Intent(action='android.intent.action.VIEW', + package='this.is.a.test.package', + activity='.Main') + with self.assertOldImplCalls( + "adb -s 0123456789abcdef shell 'am start " + "-a android.intent.action.VIEW " + "-n this.is.a.test.package/.Main " + "--start-profiler test_trace_file.out'", + 'Starting: Intent { act=android.intent.action.VIEW }'): + self.device.StartActivity(test_intent, + trace_file_name='test_trace_file.out') + + def testStartActivity_withForceStop(self): + test_intent = intent.Intent(action='android.intent.action.VIEW', + package='this.is.a.test.package', + activity='.Main') + with self.assertOldImplCalls( + "adb -s 0123456789abcdef shell 'am start " + "-a android.intent.action.VIEW " + "-S " + "-n this.is.a.test.package/.Main'", + 'Starting: Intent { act=android.intent.action.VIEW }'): + self.device.StartActivity(test_intent, force_stop=True) + + def testStartActivity_withFlags(self): + test_intent = intent.Intent(action='android.intent.action.VIEW', + package='this.is.a.test.package', + activity='.Main', + flags='0x10000000') + with self.assertOldImplCalls( + "adb -s 0123456789abcdef shell 'am start " + "-a android.intent.action.VIEW " + "-n this.is.a.test.package/.Main " + "-f 0x10000000'", + 'Starting: Intent { act=android.intent.action.VIEW }'): + self.device.StartActivity(test_intent) + + def testBroadcastIntent_noExtras(self): + test_intent = intent.Intent(action='test.package.with.an.INTENT') + with self.assertOldImplCalls( + "adb -s 0123456789abcdef shell 'am broadcast " + "-a test.package.with.an.INTENT '", + 'Broadcasting: Intent { act=test.package.with.an.INTENT } '): + self.device.BroadcastIntent(test_intent) + + def testBroadcastIntent_withExtra(self): + test_intent = intent.Intent(action='test.package.with.an.INTENT', + extras={'foo': 'bar'}) + with self.assertOldImplCalls( + "adb -s 0123456789abcdef shell 'am broadcast " + "-a test.package.with.an.INTENT " + "-e foo \"bar\"'", + 'Broadcasting: Intent { act=test.package.with.an.INTENT } '): + self.device.BroadcastIntent(test_intent) + + def testBroadcastIntent_withExtra_noValue(self): + test_intent = intent.Intent(action='test.package.with.an.INTENT', + extras={'foo': None}) + with self.assertOldImplCalls( + "adb -s 0123456789abcdef shell 'am broadcast " + "-a test.package.with.an.INTENT " + "-e foo'", + 'Broadcasting: Intent { act=test.package.with.an.INTENT } '): + self.device.BroadcastIntent(test_intent) + + if __name__ == '__main__': unittest.main(verbosity=2) diff --git a/build/android/pylib/device/intent.py b/build/android/pylib/device/intent.py new file mode 100644 index 0000000..3e34f79 --- /dev/null +++ b/build/android/pylib/device/intent.py @@ -0,0 +1,79 @@ +# Copyright 2014 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Manages intents and associated information. + +This is generally intended to be used with functions that calls Android's +Am command. +""" + +class Intent(object): + + def __init__(self, action='android.intent.action.VIEW', activity=None, + category=None, component=None, data=None, extras=None, + flags=None, package=None): + """Creates an Intent. + + Args: + action: A string containing the action. + activity: A string that, with |package|, can be used to specify the + component. + category: A string or list containing any categories. + component: A string that specifies the component to send the intent to. + data: A string containing a data URI. + extras: A dict containing extra parameters to be passed along with the + intent. + flags: A string containing flags to pass. + package: A string that, with activity, can be used to specify the + component. + """ + self._action = action + self._activity = activity + if isinstance(category, list) or category is None: + self._category = category + else: + self._category = [category] + self._component = component + self._data = data + self._extras = extras + self._flags = flags + self._package = package + + if self._component and '/' in component: + self._package, self._activity = component.split('/', 1) + elif self._package and self._activity: + self._component = '%s/%s' % (package, activity) + + @property + def action(self): + return self._action + + @property + def activity(self): + return self._activity + + @property + def category(self): + return self._category + + @property + def component(self): + return self._component + + @property + def data(self): + return self._data + + @property + def extras(self): + return self._extras + + @property + def flags(self): + return self._flags + + @property + def package(self): + return self._package + diff --git a/build/android/pylib/flag_changer.py b/build/android/pylib/flag_changer.py index 9ccdc1e..c1ce16a 100644 --- a/build/android/pylib/flag_changer.py +++ b/build/android/pylib/flag_changer.py @@ -114,7 +114,8 @@ class FlagChanger(object): assert len(file_contents) == 1 and file_contents[0] == cmd_line, ( 'Failed to set the command line file at %s' % self._cmdline_file) else: - self._device.RunShellCommand('rm ' + self._cmdline_file, root=use_root) + self._device.RunShellCommand('rm ' + self._cmdline_file, + as_root=use_root) assert ( not self._device.old_interface.FileExistsOnDevice( self._cmdline_file)), ( diff --git a/build/android/pylib/forwarder.py b/build/android/pylib/forwarder.py index aec572c..f0ddb2e 100644 --- a/build/android/pylib/forwarder.py +++ b/build/android/pylib/forwarder.py @@ -12,6 +12,7 @@ import psutil from pylib import cmd_helper from pylib import constants from pylib import valgrind_tools +from pylib.device import device_errors # TODO(jbudorick) Remove once telemetry gets switched over. import pylib.android_commands @@ -340,9 +341,10 @@ class Forwarder(object): # sure that the old version of device_forwarder (not supporting # 'kill-server') is not running on the bots anymore. timeout_sec = 5 - processes_killed = device.old_interface.KillAllBlocking( - 'device_forwarder', timeout_sec) - if not processes_killed: + try: + device.KillAll( + 'device_forwarder', blocking=True, timeout=timeout_sec) + except device_errors.CommandFailedError: pids = device.old_interface.ExtractPid('device_forwarder') if pids: - raise Exception('Timed out while killing device_forwarder') + raise diff --git a/build/android/pylib/gtest/test_package_apk.py b/build/android/pylib/gtest/test_package_apk.py index f431526..9824c8a 100644 --- a/build/android/pylib/gtest/test_package_apk.py +++ b/build/android/pylib/gtest/test_package_apk.py @@ -16,6 +16,7 @@ from pylib import android_commands from pylib import constants from pylib import pexpect from pylib.device import device_errors +from pylib.device import intent from pylib.gtest.test_package import TestPackage @@ -71,12 +72,12 @@ class TestPackageApk(TestPackage): return pexpect.spawn('adb', args, timeout=timeout, logfile=logfile) def _StartActivity(self, device): - device.old_interface.StartActivity( - self._package_info.package, - self._package_info.activity, + device.StartActivity( + intent.Intent(package=self._package_info.package, + activity=self._package_info.activity, + action='android.intent.action.MAIN'), # No wait since the runner waits for FIFO creation anyway. - wait_for_completion=False, - action='android.intent.action.MAIN', + blocking=False, force_stop=True) #override diff --git a/build/android/pylib/gtest/test_package_exe.py b/build/android/pylib/gtest/test_package_exe.py index 252c4a4..a7f6030 100644 --- a/build/android/pylib/gtest/test_package_exe.py +++ b/build/android/pylib/gtest/test_package_exe.py @@ -77,7 +77,15 @@ class TestPackageExecutable(TestPackage): #override def ClearApplicationState(self, device): - device.old_interface.KillAllBlocking(self.suite_name, 30) + try: + # We don't expect the executable to be running, so we don't attempt + # to retry on failure. + device.KillAll(self.suite_name, blocking=True, timeout=30, retries=0) + except device_errors.CommandFailedError: + # KillAll raises an exception if it can't find a process with the given + # name. We only care that there is no process with the given name, so + # we can safely eat the exception. + pass #override def CreateCommandLineFileOnDevice(self, device, test_filter, test_arguments): diff --git a/build/android/pylib/linker/test_case.py b/build/android/pylib/linker/test_case.py index e8b2ffe..446bc84 100644 --- a/build/android/pylib/linker/test_case.py +++ b/build/android/pylib/linker/test_case.py @@ -42,6 +42,7 @@ import time from pylib import constants from pylib.base import base_test_result +from pylib.device import intent ResultType = base_test_result.ResultType @@ -164,8 +165,9 @@ def _StartActivityAndWaitForLinkerTestStatus(device, timeout): try: # 2. Force-start activity. - device.old_interface.StartActivity( - package=_PACKAGE_NAME, activity=_ACTIVITY_NAME, force_stop=True) + device.StartActivity( + intent.Intent(package=_PACKAGE_NAME, activity=_ACTIVITY_NAME), + force_stop=True) # 3. Wait up to |timeout| seconds until the test status is in the logcat. num_tries = 0 diff --git a/build/android/pylib/monkey/test_runner.py b/build/android/pylib/monkey/test_runner.py index 5f0cc5d..42b7d41 100644 --- a/build/android/pylib/monkey/test_runner.py +++ b/build/android/pylib/monkey/test_runner.py @@ -10,7 +10,7 @@ import random from pylib import constants from pylib.base import base_test_result from pylib.base import base_test_runner - +from pylib.device import intent class TestRunner(base_test_runner.BaseTestRunner): """A TestRunner instance runs a monkey test on a single device.""" @@ -51,9 +51,10 @@ class TestRunner(base_test_runner.BaseTestRunner): Returns: A tuple of (TestRunResults, retry). """ - self.device.old_interface.StartActivity( - self._package, self._activity, wait_for_completion=True, - action='android.intent.action.MAIN', force_stop=True) + self.device.StartActivity( + intent.Intent(package=self._package, activity=self._activity, + action='android.intent.action.MAIN'), + blocking=True, force_stop=True) # Chrome crashes are not always caught by Monkey test runner. # Verify Chrome has the same PID before and after the test. diff --git a/build/android/pylib/perf/cache_control.py b/build/android/pylib/perf/cache_control.py index 09107db..a065dcb 100644 --- a/build/android/pylib/perf/cache_control.py +++ b/build/android/pylib/perf/cache_control.py @@ -16,7 +16,7 @@ class CacheControl(object): def DropRamCaches(self): """Drops the filesystem ram caches for performance testing.""" - self._device.RunShellCommand('sync', root=True) + self._device.RunShellCommand('sync', as_root=True) self._device.old_interface.SetProtectedFileContents( CacheControl._DROP_CACHES, '3') diff --git a/build/android/pylib/perf/perf_control.py b/build/android/pylib/perf/perf_control.py index 6a636e7..0b32dd8 100644 --- a/build/android/pylib/perf/perf_control.py +++ b/build/android/pylib/perf/perf_control.py @@ -90,7 +90,7 @@ class PerfControl(object): """ if self._have_mpdecision: script = 'stop mpdecision' if force_online else 'start mpdecision' - self._device.RunShellCommand(script, root=True) + self._device.RunShellCommand(script, as_root=True) if not self._have_mpdecision and not self._AllCpusAreOnline(): logging.warning('Unexpected cpu hot plugging detected.') diff --git a/build/android/pylib/uiautomator/test_runner.py b/build/android/pylib/uiautomator/test_runner.py index fc7e9cc..52726d5 100644 --- a/build/android/pylib/uiautomator/test_runner.py +++ b/build/android/pylib/uiautomator/test_runner.py @@ -6,6 +6,7 @@ from pylib import constants from pylib import flag_changer +from pylib.device import intent from pylib.instrumentation import test_options as instr_test_options from pylib.instrumentation import test_runner as instr_test_runner @@ -65,10 +66,11 @@ class TestRunner(instr_test_runner.TestRunner): self.flags.RemoveFlags(['--disable-fre']) else: self.flags.AddFlags(['--disable-fre']) - self.device.old_interface.StartActivity(self._package, - self._activity, - wait_for_completion=True, - action='android.intent.action.MAIN', - force_stop=True) + self.device.StartActivity( + intent.Intent(action='android.intent.action.MAIN', + activity=self._activity, + package=self._package), + blocking=True, + force_stop=True) return self.device.old_interface.RunUIAutomatorTest( test, self.test_pkg.GetPackageName(), timeout) diff --git a/build/android/tombstones.py b/build/android/tombstones.py index 76dab15..1112a97 100755 --- a/build/android/tombstones.py +++ b/build/android/tombstones.py @@ -74,7 +74,7 @@ def _EraseTombstone(device, tombstone_file): tombstone_file: the tombstone to delete. """ return device.RunShellCommand( - 'rm /data/tombstones/' + tombstone_file, root=True) + 'rm /data/tombstones/' + tombstone_file, as_root=True) def _ResolveSymbols(tombstone_data, include_stack): diff --git a/tools/android/adb_profile_chrome/chrome_controller.py b/tools/android/adb_profile_chrome/chrome_controller.py index 5457e93..3dc8855 100644 --- a/tools/android/adb_profile_chrome/chrome_controller.py +++ b/tools/android/adb_profile_chrome/chrome_controller.py @@ -10,6 +10,7 @@ import time from adb_profile_chrome import controllers from pylib import pexpect +from pylib.device import intent _HEAP_PROFILE_MMAP_PROPERTY = 'heapprof.mmap' @@ -35,8 +36,8 @@ class ChromeTracingController(controllers.BaseController): @staticmethod def GetCategories(device, package_info): - device.old_interface.BroadcastIntent( - package_info.package, 'GPU_PROFILER_LIST_CATEGORIES') + device.BroadcastIntent(intent.Intent( + action='%s.GPU_PROFILER_LIST_CATEGORIES' % self._package_info.package)) try: json_category_list = device.old_interface.WaitForLogMatch( re.compile(r'{"traceCategoriesList(.*)'), None, timeout=5).group(0) @@ -58,10 +59,12 @@ class ChromeTracingController(controllers.BaseController): def StartTracing(self, interval): self._trace_interval = interval self._device.old_interface.SyncLogCat() - self._device.old_interface.BroadcastIntent( - self._package_info.package, 'GPU_PROFILER_START', - '-e categories "%s"' % ','.join(self._categories), - '-e continuous' if self._ring_buffer else '') + start_extras = {'categories': ','.join(self._categories)} + if self._ring_buffer: + start_extras['continuous'] = None + self._device.BroadcastIntent(intent.Intent( + action='%s.GPU_PROFILER_START' % self._package_info.package, + extras=start_extras)) if self._trace_memory: self._device.old_interface.EnableAdbRoot() @@ -83,9 +86,8 @@ class ChromeTracingController(controllers.BaseController): 'of the browser running?') def StopTracing(self): - self._device.old_interface.BroadcastIntent( - self._package_info.package, - 'GPU_PROFILER_STOP') + self._device.BroadcastIntent(intent.Intent( + action='%s.GPU_PROFILER_STOP' % self._package_info.package)) self._trace_file = self._device.old_interface.WaitForLogMatch( self._trace_finish_re, None, timeout=120).group(1) if self._trace_memory: diff --git a/tools/android/adb_profile_chrome/controllers_unittest.py b/tools/android/adb_profile_chrome/controllers_unittest.py index 6702c38..5df7bea 100644 --- a/tools/android/adb_profile_chrome/controllers_unittest.py +++ b/tools/android/adb_profile_chrome/controllers_unittest.py @@ -17,7 +17,7 @@ class BaseControllerTest(unittest.TestCase): self.package_info = profiler.GetSupportedBrowsers()[self.browser] self.device = device_utils.DeviceUtils(devices[0]) - adb = android_commands.AndroidCommands(devices[0]) - adb.StartActivity(self.package_info.package, - self.package_info.activity, - wait_for_completion=True) + self.device.StartActivity( + intent.Intent(activity=self.package_info.activity, + package=self.package_info.package), + blocking=True) diff --git a/tools/android/mempressure.py b/tools/android/mempressure.py index 77f45a9..bd606f1 100755 --- a/tools/android/mempressure.py +++ b/tools/android/mempressure.py @@ -98,7 +98,8 @@ def main(argv): if ENABLE_TEST_INTENTS_FLAG not in flags.Get(): flags.AddFlags([ENABLE_TEST_INTENTS_FLAG]) - device.old_interface.StartActivity(package, activity, action=action) + device.StartActivity(intent.Intent(package=package, activity=activity, + action=action)) if __name__ == '__main__': sys.exit(main(sys.argv)) diff --git a/tools/telemetry/telemetry/core/backends/chrome/android_browser_backend.py b/tools/telemetry/telemetry/core/backends/chrome/android_browser_backend.py index 3ead0bf..e2bd23c 100644 --- a/tools/telemetry/telemetry/core/backends/chrome/android_browser_backend.py +++ b/tools/telemetry/telemetry/core/backends/chrome/android_browser_backend.py @@ -17,6 +17,8 @@ from telemetry.core.backends import browser_backend from telemetry.core.backends.chrome import chrome_browser_backend from telemetry.core.forwarders import android_forwarder +from pylib.device import intent + class AndroidBrowserBackendSettings(object): @@ -34,10 +36,11 @@ class AndroidBrowserBackendSettings(object): def RemoveProfile(self): files = self.adb.device().RunShellCommand( - 'ls "%s"' % self.profile_dir, root=True) + 'ls "%s"' % self.profile_dir, as_root=True) # Don't delete lib, since it is created by the installer. paths = ['"%s/%s"' % (self.profile_dir, f) for f in files if f != 'lib'] - self.adb.device().RunShellCommand('rm -r %s' % ' '.join(paths), root=True) + self.adb.device().RunShellCommand('rm -r %s' % ' '.join(paths), + as_root=True) def PushProfile(self, _): logging.critical('Profiles cannot be overriden with current configuration') @@ -97,7 +100,7 @@ class ChromeBackendSettings(AndroidBrowserBackendSettings): id_line = next(line for line in dumpsys if 'userId=' in line) uid = re.search('\d+', id_line).group() files = self.adb.device().RunShellCommand( - 'ls "%s"' % self.profile_dir, root=True) + 'ls "%s"' % self.profile_dir, as_root=True) files.remove('lib') paths = ['%s/%s' % (self.profile_dir, f) for f in files] for path in paths: @@ -285,12 +288,11 @@ class AndroidBrowserBackend(chrome_browser_backend.ChromeBrowserBackend): # startup with the NTP can lead to race conditions with Telemetry url = 'about:blank' self._adb.device().old_interface.DismissCrashDialogIfNeeded() - self._adb.StartActivity(self._backend_settings.package, - self._backend_settings.activity, - True, - None, - None, - url) + self._adb.device().StartActivity( + intent.Intent(package=self._backend_settings.package, + activity=self._backend_settings.activity, + action=None, data=url, category=None), + blocking=True) self._adb.Forward('tcp:%d' % self._port, self._backend_settings.GetDevtoolsRemotePort()) diff --git a/tools/telemetry/telemetry/core/platform/android_platform_backend.py b/tools/telemetry/telemetry/core/platform/android_platform_backend.py index 5242cb4..f2238ed 100644 --- a/tools/telemetry/telemetry/core/platform/android_platform_backend.py +++ b/tools/telemetry/telemetry/core/platform/android_platform_backend.py @@ -184,7 +184,7 @@ class AndroidPlatformBackend( raise NotImplementedError() def FlushDnsCache(self): - self._device.RunShellCommand('ndc resolver flushdefaultif', root=True) + self._device.RunShellCommand('ndc resolver flushdefaultif', as_root=True) def LaunchApplication( self, application, parameters=None, elevate_privilege=False): diff --git a/tools/telemetry/telemetry/core/platform/profiler/android_profiling_helper.py b/tools/telemetry/telemetry/core/platform/profiler/android_profiling_helper.py index ca3a08b..1b7d578 100644 --- a/tools/telemetry/telemetry/core/platform/profiler/android_profiling_helper.py +++ b/tools/telemetry/telemetry/core/platform/profiler/android_profiling_helper.py @@ -41,7 +41,7 @@ def _ElfSectionMd5Sum(elf_file, section): def _FindMatchingUnstrippedLibraryOnHost(device, lib): lib_base = os.path.basename(lib) - device_md5 = device.RunShellCommand('md5 "%s"' % lib, root=True)[0] + device_md5 = device.RunShellCommand('md5 "%s"' % lib, as_root=True)[0] device_md5 = device_md5.split(' ', 1)[0] def FindMatchingStrippedLibrary(out_path): diff --git a/tools/telemetry/telemetry/core/platform/profiler/oomkiller_profiler.py b/tools/telemetry/telemetry/core/platform/profiler/oomkiller_profiler.py index e73eac1..1dd5e6e 100644 --- a/tools/telemetry/telemetry/core/platform/profiler/oomkiller_profiler.py +++ b/tools/telemetry/telemetry/core/platform/profiler/oomkiller_profiler.py @@ -8,6 +8,7 @@ from telemetry.core.backends.chrome import android_browser_finder from telemetry.core.platform import profiler from telemetry.util import support_binaries +from pylib.device import intent class UnableToFindApplicationException(Exception): """Exception when unable to find a launched application""" @@ -39,9 +40,10 @@ class OOMKillerProfiler(profiler.Profiler): 'org.chromium.memconsumer/.MemConsumer', '--ei memory 20') # Bring the browser to the foreground after launching the mem consumer - self._browser_backend.adb.StartActivity(browser_backend.package, - browser_backend.activity, - True) + self._browser_backend.adb.device().StartActivity( + intent.Intent(package=browser_backend.package, + activity=browser_backend.activity), + blocking=True) @classmethod def name(cls): |