mozdevice — Interact with remote devices

Mozdevice provides several interfaces to interact with a remote device such as an Android- or FirefoxOS-based phone. It allows you to push files to these types of devices, launch processes, and more. There are currently two available interfaces:

  • DeviceManager interface: Works either via ADB or a custom TCP protocol (the latter requires an agent application running on the device).
  • ADB Interface: Uses the Android Debugger Protocol explicitly

In general, new code should use the ADB abstraction where possible as it is simpler and more reliable.

DeviceManager interface

class mozdevice.DeviceManager(logLevel=None, deviceRoot=None)[source]

Represents a connection to a device. Once an implementation of this class is successfully instantiated, you may do things like list/copy files to the device, launch processes on the device, and install or remove applications from the device.

Never instantiate this class directly! Instead, instantiate an implementation of it like DeviceManagerADB or DeviceManagerSUT.

Here’s an example script which lists the files in ‘/mnt/sdcard’ and sees if a process called ‘org.mozilla.fennec’ is running. In this example, we’re instantiating the DeviceManagerADB implementation, but we could just as easily have used DeviceManagerSUT (assuming the device had an agent running speaking the SUT protocol).

import mozdevice

dm = mozdevice.DeviceManagerADB()
print dm.listFiles("/mnt/sdcard")
if dm.processExist("org.mozilla.fennec"):
    print "Fennec is running"

Informational methods

DeviceManager.getInfo(self, directive=None)[source]

Returns a dictionary of information strings about the device.

Parameters:directive

information you want to get. Options are:

  • os - name of the os
  • id - unique id of the device
  • uptime - uptime of the device
  • uptimemillis - uptime of the device in milliseconds (NOT supported on all implementations)
  • systime - system time of the device
  • screen - screen resolution
  • memory - memory stats
  • memtotal - total memory available on the device, for example 927208 kB
  • process - list of running processes (same as ps)
  • disk - total, free, available bytes on disk
  • power - power status (charge, battery temp)
  • temperature - device temperature

If directive is None, will return all available information

DeviceManager.getCurrentTime(self)[source]

Returns device time in milliseconds since the epoch.

DeviceManager.getIP(interfaces=['eth0', 'wlan0'])[source]

Returns the IP of the device, or None if no connection exists.

DeviceManager.saveScreenshot(filename)[source]

Takes a screenshot of what’s being display on the device. Uses “screencap” on newer (Android 3.0+) devices (and some older ones with the functionality backported). This function also works on B2G.

Throws an exception on failure. This will always fail on devices without the screencap utility.

DeviceManager.recordLogcat()[source]

Clears the logcat file making it easier to view specific events.

DeviceManager.getLogcat(filterSpecs=['dalvikvm:I', 'ConnectivityService:S', 'WifiMonitor:S', 'WifiStateTracker:S', 'wpa_supplicant:S', 'NetworkStateTracker:S'], format='time', filterOutRegexps=[])[source]
Returns the contents of the logcat file as a list of ‘

‘ terminated strings

File management methods

DeviceManager.deviceRoot

The device root on the device filesystem for putting temporary testing files.

DeviceManager.getDeviceRoot(self)[source]

Get the device root on the device filesystem for putting temporary testing files.

Deprecated since version 0.38: Use the deviceRoot property instead.

DeviceManager.pushFile(self, localFilename, remoteFilename, retryLimit=1)[source]

Copies localname from the host to destname on the device.

DeviceManager.pushDir(self, localDirname, remoteDirname, retryLimit=1)[source]

Push local directory from host to remote directory on the device,

DeviceManager.pullFile(self, remoteFilename)[source]

Returns contents of remoteFile using the “pull” command.

Parameters:
  • remoteFilename – Path to file to pull from remote device.
  • offset – Offset in bytes from which to begin reading (optional)
  • length – Number of bytes to read (optional)
DeviceManager.getFile(self, remoteFilename, localFilename)[source]

Copy file from remote device to local file on host.

DeviceManager.getDirectory(self, remoteDirname, localDirname, checkDir=True)[source]

Copy directory structure from device (remoteDirname) to host (localDirname).

DeviceManager.validateFile(self, remoteFilename, localFilename)[source]

Returns True if a file on the remote device has the same md5 hash as a local one.

DeviceManager.mkDir(self, remoteDirname)[source]

Creates a single directory on the device file system.

DeviceManager.mkDirs(self, filename)[source]

Make directory structure on the device.

WARNING: does not create last part of the path. For example, if asked to create /mnt/sdcard/foo/bar/baz, it will only create /mnt/sdcard/foo/bar

DeviceManager.dirExists(self, dirpath)[source]

Returns whether dirpath exists and is a directory on the device file system.

DeviceManager.fileExists(self, filepath)[source]

Return whether filepath exists on the device file system, regardless of file type.

DeviceManager.listFiles(self, rootdir)[source]

Lists files on the device rootdir.

Returns array of filenames, [‘file1’, ‘file2’, ...]

DeviceManager.removeFile(self, filename)[source]

Removes filename from the device.

DeviceManager.removeDir(self, remoteDirname)[source]

Does a recursive delete of directory on the device: rm -Rf remoteDirname.

DeviceManager.chmodDir(self, remoteDirname, mask="777")[source]

Recursively changes file permissions in a directory.

DeviceManager.getTempDir(self)[source]

Returns a temporary directory we can use on this device, ensuring also that it exists.

Process management methods

DeviceManager.shell(self, cmd, outputfile, env=None, cwd=None, timeout=None, root=False)[source]

Executes shell command on device and returns exit code.

Parameters:
  • cmd – Commandline list to execute
  • outputfile – File to store output
  • env – Environment to pass to exec command
  • cwd – Directory to execute command from
  • timeout – specified in seconds, defaults to ‘default_timeout’
  • root – Specifies whether command requires root privileges
DeviceManager.shellCheckOutput(self, cmd, env=None, cwd=None, timeout=None, root=False)[source]

Executes shell command on device and returns output as a string. Raises if the return code is non-zero.

Parameters:
  • cmd – Commandline list to execute
  • env – Environment to pass to exec command
  • cwd – Directory to execute command from
  • timeout – specified in seconds, defaults to ‘default_timeout’
  • root – Specifies whether command requires root privileges
Raises:

DMError

DeviceManager.getProcessList(self)[source]

Returns array of tuples representing running processes on the device.

Format of tuples is (processId, processName, userId)

DeviceManager.processExist(self, processName)[source]

Returns True if process with name processName is running on device.

DeviceManager.killProcess(self, processName)[source]

Kills the process named processName. If sig is not None, process is killed with the specified signal.

Parameters:
  • processName – path or name of the process to kill
  • sig – signal to pass into the kill command (optional)

System control methods

DeviceManager.reboot(self, ipAddr=None, port=30000)[source]

Reboots the device.

Parameters:
  • wait – block on device to come back up before returning
  • ipAddr – if specified, try to make the device connect to this specific IP address after rebooting (only works with SUT; if None, we try to determine a reasonable address ourselves)

Application management methods

DeviceManager.uninstallAppAndReboot(self, appName, installPath=None)[source]

Uninstalls the named application from device and causes a reboot.

Parameters:
  • appName – the name of the application (e.g org.mozilla.fennec)
  • installPath – the path to where the application was installed (optional)
DeviceManager.installApp(self, appBundlePath, destPath=None)[source]

Installs an application onto the device.

Parameters:
  • appBundlePath – path to the application bundle on the device
  • destPath – destination directory of where application should be installed to (optional)
DeviceManager.uninstallApp(self, appName, installPath=None)[source]

Uninstalls the named application from device and DOES NOT cause a reboot.

Parameters:
  • appName – the name of the application (e.g org.mozilla.fennec)
  • installPath – the path to where the application was installed (optional)
DeviceManager.updateApp(self, appBundlePath, processName=None, destPath=None, ipAddr=None, port=30000)[source]

Updates the application on the device and reboots.

Parameters:
  • appBundlePath – path to the application bundle on the device
  • processName – used to end the process if the applicaiton is currently running (optional)
  • destPath – Destination directory to where the application should be installed (optional)
  • wait – block on device to come back up before returning
  • ipAddr – if specified, try to make the device connect to this specific IP address after rebooting (only works with SUT; if None and wait is True, we try to determine a reasonable address ourselves)

DeviceManagerADB implementation

class mozdevice.DeviceManagerADB(host=None, port=5555, retryLimit=5, packageName='fennec', adbPath='adb', deviceSerial=None, deviceRoot=None, logLevel=40, autoconnect=True, runAdbAsRoot=False, serverHost=None, serverPort=None, **kwargs)[source]

Implementation of DeviceManager interface that uses the Android “adb” utility to communicate with the device. Normally used to communicate with a device that is directly connected with the host machine over a USB port.

DeviceManagerADB has several methods that are not present in all DeviceManager implementations. Please do not use them in code that is meant to be interoperable.

DeviceManagerADB.forward(local, remote)[source]

Forward socket connections.

Forward specs are one of:
tcp:<port> localabstract:<unix domain socket name> localreserved:<unix domain socket name> localfilesystem:<unix domain socket name> dev:<character device name> jdwp:<process pid> (remote only)
DeviceManagerADB.remount()[source]

Remounts the /system partition on the device read-write.

DeviceManagerADB.devices()[source]

Return a list of connected devices as (serial, status) tuples.

DeviceManagerSUT implementation

class mozdevice.DeviceManagerSUT(host, port=20701, retryLimit=5, deviceRoot=None, logLevel=40, **kwargs)[source]

Implementation of DeviceManager interface that speaks to a device over TCP/IP using the “system under test” protocol. A software agent such as Negatus (http://github.com/mozilla/Negatus) or the Mozilla Android SUTAgent app must be present and listening for connections for this to work.

DeviceManagerSUT has several methods that are only used in specific tests and are not present in all DeviceManager implementations. Please do not use them in code that is meant to be interoperable.

DeviceManagerSUT.unpackFile(filePath, destDir=None)[source]

Unzips a bundle to a location on the device

If destDir is not specified, the bundle is extracted in the same directory

DeviceManagerSUT.adjustResolution(width=1680, height=1050, type='hdmi')[source]

Adjust the screen resolution on the device, REBOOT REQUIRED

NOTE: this only works on a tegra ATM

supported resolutions: 640x480, 800x600, 1024x768, 1152x864, 1200x1024, 1440x900, 1680x1050, 1920x1080

Android extensions

For Android, we provide two variants of the DeviceManager interface with extensions useful for that platform. These classes are called DroidADB and DroidSUT. They inherit all methods from DeviceManagerADB and DeviceManagerSUT. Here is the interface for DroidADB:

DroidADB.launchApplication(appName, activityName, intent, url=None, extras=None, wait=True, failIfRunning=True)

Launches an Android application

Parameters:
  • appName – Name of application (e.g. com.android.chrome)
  • activityName – Name of activity to launch (e.g. .Main)
  • intent – Intent to launch application with
  • url – URL to open
  • extras – Dictionary of extra arguments to launch application with
  • wait – If True, wait for application to start before returning
  • failIfRunning – Raise an exception if instance of application is already running
DroidADB.launchFennec(appName, intent='android.intent.action.VIEW', mozEnv=None, extraArgs=None, url=None, wait=True, failIfRunning=True)

Convenience method to launch Fennec on Android with various debugging arguments

Parameters:
  • appName – Name of fennec application (e.g. org.mozilla.fennec)
  • intent – Intent to launch application with
  • mozEnv – Mozilla specific environment to pass into application
  • extraArgs – Extra arguments to be parsed by fennec
  • url – URL to open
  • wait – If True, wait for application to start before returning
  • failIfRunning – Raise an exception if instance of application is already running
DroidADB.getInstalledApps()

Lists applications installed on this Android device

Returns a list of application names in the form [ ‘org.mozilla.fennec’, ... ]

DroidADB.getAppRoot(packageName)[source]

Returns the root directory for the specified android application

These methods are also found in the DroidSUT class.

ADB Interface

The following classes provide a basic interface to interact with the Android Debug Tool (adb) and Android-based devices. It is intended to provide the basis for a replacement for DeviceManager and DeviceManagerADB.

ADBCommand

class mozdevice.ADBCommand(adb='adb', adb_host=None, adb_port=None, logger_name='adb', timeout=300, verbose=False)[source]

ADBCommand provides a basic interface to adb commands which is used to provide the ‘command’ methods for the classes ADBHost and ADBDevice.

ADBCommand should only be used as the base class for other classes and should not be instantiated directly. To enforce this restriction calling ADBCommand’s constructor will raise a NonImplementedError exception.

from mozdevice import ADBCommand

try:
    adbcommand = ADBCommand()
except NotImplementedError:
    print "ADBCommand can not be instantiated."
ADBCommand.command(self, cmds, timeout=None)[source]

Executes an adb command on the host.

Parameters:
  • cmds – list containing the command and its arguments to be executed.
  • device_serial – optional string specifying the device’s serial number if the adb command is to be executed against a specific device.
  • timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBCommand constructor is used.
Returns:

mozdevice.ADBProcess

command() provides a low level interface for executing commands on the host via adb.

command() executes on the host in such a fashion that stdout and stderr of the adb process are file handles on the host and the exit code is available as the exit code of the adb process.

The caller provides a list containing commands, as well as a timeout period in seconds.

A subprocess is spawned to execute adb with stdout and stderr directed to temporary files. If the process takes longer than the specified timeout, the process is terminated.

It is the caller’s responsibilty to clean up by closing the stdout and stderr temporary files.

ADBCommand.command_output(self, cmds, timeout=None)[source]

Executes an adb command on the host returning stdout.

Parameters:
  • cmds – list containing the command and its arguments to be executed.
  • device_serial – optional string specifying the device’s serial number if the adb command is to be executed against a specific device.
  • timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBCommand constructor is used.
Returns:

string - content of stdout.

Raises:
  • ADBTimeoutError
  • ADBError

ADBHost

class mozdevice.ADBHost(adb='adb', adb_host=None, adb_port=None, logger_name='adb', timeout=300, verbose=False)[source]

ADBHost provides a basic interface to adb host commands which do not target a specific device.

from mozdevice import ADBHost

adbhost = ADBHost()
adbhost.start_server()
ADBHost.command(self, cmds, timeout=None)[source]

Executes an adb command on the host.

Parameters:
  • cmds – list containing the command and its arguments to be executed.
  • timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBHost constructor is used.
Returns:

mozdevice.ADBProcess

command() provides a low level interface for executing commands on the host via adb.

command() executes on the host in such a fashion that stdout and stderr of the adb process are file handles on the host and the exit code is available as the exit code of the adb process.

The caller provides a list containing commands, as well as a timeout period in seconds.

A subprocess is spawned to execute adb with stdout and stderr directed to temporary files. If the process takes longer than the specified timeout, the process is terminated.

It is the caller’s responsibilty to clean up by closing the stdout and stderr temporary files.

ADBHost.command_output(self, cmds, timeout=None)[source]

Executes an adb command on the host returning stdout.

Parameters:
  • cmds – list containing the command and its arguments to be executed.
  • timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBHost constructor is used.
Returns:

string - content of stdout.

Raises:
  • ADBTimeoutError
  • ADBError
ADBHost.start_server(self, timeout=None)[source]

Starts the adb server.

Parameters:

timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBHost constructor is used.

Raises:
  • ADBTimeoutError
  • ADBError

Attempting to use start_server with any adb_host value other than None will fail with an ADBError exception.

You will need to start the server on the remote host via the command:

adb -a fork-server server

If you wish the remote adb server to restart automatically, you can enclose the command in a loop as in:

while true; do
  adb -a fork-server server
done
ADBHost.kill_server(self, timeout=None)[source]

Kills the adb server.

Parameters:

timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBHost constructor is used.

Raises:
  • ADBTimeoutError
  • ADBError
ADBHost.devices(self, timeout=None)[source]

Executes adb devices -l and returns a list of objects describing attached devices.

Parameters:

timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBHost constructor is used.

Returns:

an object contain

Raises:
  • ADBTimeoutError
  • ADBError

The output of adb devices -l

$ adb devices -l
List of devices attached
b313b945               device usb:1-7 product:d2vzw model:SCH_I535 device:d2vzw

is parsed and placed into an object as in

[{‘device_serial’: ‘b313b945’, ‘state’: ‘device’, ‘product’: ‘d2vzw’,
‘usb’: ‘1-7’, ‘device’: ‘d2vzw’, ‘model’: ‘SCH_I535’ }]

ADBDevice

class mozdevice.ADBDevice(device=None, adb='adb', adb_host=None, adb_port=None, test_root='', logger_name='adb', timeout=300, verbose=False, device_ready_retry_wait=20, device_ready_retry_attempts=3)[source]

ADBDevice provides methods which can be used to interact with the associated Android-based device.

Android specific features such as Application management are not included but are provided via the ADBAndroid interface.

from mozdevice import ADBDevice

adbdevice = ADBDevice()
print adbdevice.list_files("/mnt/sdcard")
if adbdevice.process_exist("org.mozilla.fennec"):
    print "Fennec is running"

Host Command methods

ADBDevice.command(self, cmds, timeout=None)[source]

Executes an adb command on the host against the device.

Parameters:
  • cmds – list containing the command and its arguments to be executed.
  • timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.
Returns:

mozdevice.ADBProcess

command() provides a low level interface for executing commands for a specific device on the host via adb.

command() executes on the host in such a fashion that stdout and stderr of the adb process are file handles on the host and the exit code is available as the exit code of the adb process.

For executing shell commands on the device, use ADBDevice.shell(). The caller provides a list containing commands, as well as a timeout period in seconds.

A subprocess is spawned to execute adb for the device with stdout and stderr directed to temporary files. If the process takes longer than the specified timeout, the process is terminated.

It is the caller’s responsibilty to clean up by closing the stdout and stderr temporary files.

ADBDevice.command_output(self, cmds, timeout=None)[source]

Executes an adb command on the host against the device returning stdout.

Parameters:
  • cmds – list containing the command and its arguments to be executed.
  • timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.
Returns:

string - content of stdout.

Raises:
  • ADBTimeoutError
  • ADBError

Device Shell methods

ADBDevice.shell(self, cmd, env=None, cwd=None, timeout=None, root=False)[source]

Executes a shell command on the device.

Parameters:
  • cmd – string containing the command to be executed.
  • env – optional dictionary of environment variables and their values.
  • cwd – optional string containing the directory from which to execute.
  • timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.
  • root – optional boolean specifying if the command should be executed as root.
Returns:

mozdevice.ADBProcess

Raises:

ADBRootError

shell() provides a low level interface for executing commands on the device via adb shell.

shell() executes on the host in such as fashion that stdout contains the stdout of the host abd process combined with the combined stdout/stderr of the shell command on the device while stderr is still the stderr of the adb process on the host. The exit code of shell() is the exit code of the adb command if it was non-zero or the extracted exit code from the stdout/stderr of the shell command executed on the device.

The caller provides a flag indicating if the command is to be executed as root, a string for any requested working directory, a hash defining the environment, a string containing shell commands, as well as a timeout period in seconds.

The command line to be executed is created to set the current directory, set the required environment variables, optionally execute the command using su and to output the return code of the command to stdout. The command list is created as a command sequence separated by && which will terminate the command sequence on the first command which returns a non-zero exit code.

A subprocess is spawned to execute adb shell for the device with stdout and stderr directed to temporary files. If the process takes longer than the specified timeout, the process is terminated. The return code is extracted from the stdout and is then removed from the file.

It is the caller’s responsibilty to clean up by closing the stdout and stderr temporary files.

ADBDevice.shell_bool(self, cmd, env=None, cwd=None, timeout=None, root=False)[source]

Executes a shell command on the device returning True on success and False on failure.

Parameters:
  • cmd – string containing the command to be executed.
  • env – optional dictionary of environment variables and their values.
  • cwd – optional string containing the directory from which to execute.
  • timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.
  • root – optional boolean specifying if the command should be executed as root.
Returns:

boolean

Raises:
  • ADBTimeoutError
  • ADBRootError
ADBDevice.shell_output(self, cmd, env=None, cwd=None, timeout=None, root=False)[source]

Executes an adb shell on the device returning stdout.

Parameters:
  • cmd – string containing the command to be executed.
  • env – optional dictionary of environment variables and their values.
  • cwd – optional string containing the directory from which to execute.
  • timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used. :param root: optional boolean specifying if the command should be executed as root.
Returns:

string - content of stdout.

Raises:
  • ADBTimeoutError
  • ADBRootError
  • ADBError

Informational methods

ADBDevice.clear_logcat(timeout=None, buffers=['main'])[source]

Clears logcat via adb logcat -c.

Parameters:
  • timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.
  • buffers – list of log buffers to clear. Valid buffers are “radio”, “events”, and “main”. Defaults to “main”.
Raises:
  • ADBTimeoutError
  • ADBError
ADBDevice.get_logcat(filter_specs=['dalvikvm:I', 'ConnectivityService:S', 'WifiMonitor:S', 'WifiStateTracker:S', 'wpa_supplicant:S', 'NetworkStateTracker:S'], format='time', filter_out_regexps=[], timeout=None, buffers=['main'])[source]

Returns the contents of the logcat file as a list of strings.

Parameters:
  • filter_specs – optional list containing logcat messages to be included.
  • format – optional logcat format.
  • filterOutRexps – optional list of logcat messages to be excluded.
  • timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.
  • buffers – list of log buffers to retrieve. Valid buffers are “radio”, “events”, and “main”. Defaults to “main”.
Returns:

list of lines logcat output.

Raises:
  • ADBTimeoutError
  • ADBError
ADBDevice.get_prop(self, prop, timeout=None)[source]

Gets value of a property from the device via adb shell getprop.

Parameters:
  • prop – string containing the propery name.
  • timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.
Returns:

string value of property.

Raises:
  • ADBTimeoutError
  • ADBError
ADBDevice.get_state(self, timeout=None)[source]

Returns the device’s state via adb get-state.

Parameters:

timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Returns:

string value of adb get-state.

Raises:
  • ADBTimeoutError
  • ADBError

File management methods

ADBDevice.chmod(self, path, recursive=False, mask="777", timeout=None, root=False)[source]

Recursively changes the permissions of a directory on the device.

Parameters:
  • path – string containing the directory name on the device.
  • recursive – boolean specifying if the command should be executed recursively.
  • mask – optional string containing the octal permissions.
  • timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.
  • root – optional boolean specifying if the command should be executed as root.
Raises:
  • ADBTimeoutError
  • ADBRootError
  • ADBError
ADBDevice.exists(self, path, timeout=None, root=False)[source]

Returns True if the path exists on the device.

Parameters:
  • path – string containing the directory name on the device.
  • timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.
  • root – optional boolean specifying if the command should be executed as root.
Returns:

boolean - True if path exists.

Raises:
  • ADBTimeoutError
  • ADBRootError
ADBDevice.is_dir(self, path, timeout=None, root=False)[source]

Returns True if path is an existing directory on the device.

Parameters:
  • path – string containing the path on the device.
  • timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.
  • root – optional boolean specifying if the command should be executed as root.
Returns:

boolean - True if path exists on the device and is a directory.

Raises:
  • ADBTimeoutError
  • ADBRootError
ADBDevice.is_file(self, path, timeout=None, root=False)[source]

Returns True if path is an existing file on the device.

Parameters:
  • path – string containing the file name on the device.
  • timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.
  • root – optional boolean specifying if the command should be executed as root.
Returns:

boolean - True if path exists on the device and is a file.

Raises:
  • ADBTimeoutError
  • ADBRootError
ADBDevice.list_files(self, path, timeout=None, root=False)[source]

Return a list of files/directories contained in a directory on the device.

Parameters:
  • path – string containing the directory name on the device.
  • timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.
  • root – optional boolean specifying if the command should be executed as root.
Returns:

list of files/directories contained in the directory.

Raises:
  • ADBTimeoutError
  • ADBRootError
ADBDevice.mkdir(self, path, parents=False, timeout=None, root=False)[source]

Create a directory on the device.

Parameters:
  • path – string containing the directory name on the device to be created.
  • parents – boolean indicating if the parent directories are also to be created. Think mkdir -p path.
  • timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.
  • root – optional boolean specifying if the command should be executed as root.
Raises:
  • ADBTimeoutError
  • ADBRootError
  • ADBError
ADBDevice.push(self, local, remote, timeout=None)[source]

Pushes a file or directory to the device.

Parameters:
  • local – string containing the name of the local file or directory name.
  • remote – string containing the name of the remote file or directory name.
  • timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.
Raises:
  • ADBTimeoutError
  • ADBError
ADBDevice.rm(self, path, recursive=False, force=False, timeout=None, root=False)[source]

Delete files or directories on the device.

Parameters:
  • path – string containing the path of the remote file or directory.
  • recursive – optional boolean specifying if the command is to be applied recursively to the target. Default is False.
  • force – optional boolean which if True will not raise an error when attempting to delete a non-existent file. Default is False.
  • timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.
  • root – optional boolean specifying if the command should be executed as root.
Raises:
  • ADBTimeoutError
  • ADBRootError
  • ADBError
ADBDevice.rmdir(self, path, timeout=None, root=False)[source]

Delete empty directory on the device.

Parameters:
  • path – string containing the directory name on the device.
  • timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.
  • root – optional boolean specifying if the command should be executed as root.
Raises:
  • ADBTimeoutError
  • ADBRootError
  • ADBError
ADBDevice.test_root

The test_root property returns the directory on the device where temporary test files are stored.

The first time test_root it is called it determines and caches a value for the test root on the device. It determines the appropriate test root by attempting to create a ‘dummy’ directory on each of a list of directories and returning the first successful directory as the test_root value.

The default list of directories checked by test_root are:

  • /storage/sdcard0/tests
  • /storage/sdcard1/tests
  • /sdcard/tests
  • /mnt/sdcard/tests
  • /data/local/tests

You may override the default list by providing a test_root argument to the ADBDevice constructor which will then be used when attempting to create the ‘dummy’ directory.

Raises:
  • ADBTimeoutError
  • ADBRootError
  • ADBError

Process management methods

ADBDevice.get_process_list(self, timeout=None)[source]

Returns list of tuples (pid, name, user) for running processes on device.

Parameters:

timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Returns:

list of (pid, name, user) tuples for running processes on the device.

Raises:
  • ADBTimeoutError
  • ADBError
ADBDevice.kill(self, pids, sig=None, attempts=3, wait=5, timeout=None, root=False)[source]

Kills processes on the device given a list of process ids.

Parameters:
  • pids – list of process ids to be killed.
  • sig – optional signal to be sent to the process.
  • attempts – number of attempts to try to kill the processes.
  • wait – number of seconds to wait after each attempt.
  • timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.
  • root – optional boolean specifying if the command should be executed as root.
Raises:
  • ADBTimeoutError
  • ADBRootError
  • ADBError
ADBDevice.pkill(self, appname, sig=None, attempts=3, wait=5, timeout=None, root=False)[source]

Kills a processes on the device matching a name.

Parameters:
  • appname – string containing the app name of the process to be killed. Note that only the first 75 characters of the process name are significant.
  • sig – optional signal to be sent to the process.
  • attempts – number of attempts to try to kill the processes.
  • wait – number of seconds to wait after each attempt.
  • timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.
  • root – optional boolean specifying if the command should be executed as root.
Raises:
  • ADBTimeoutError
  • ADBRootError
  • ADBError
ADBDevice.process_exist(self, process_name, timeout=None)[source]

Returns True if process with name process_name is running on device.

Parameters:
  • process_name – string containing the name of the process to check. Note that only the first 75 characters of the process name are significant.
  • timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.
Returns:

boolean - True if process exists.

Raises:
  • ADBTimeoutError
  • ADBError

ADBAndroid

class mozdevice.ADBAndroid(device=None, adb='adb', adb_host=None, adb_port=None, test_root='', logger_name='adb', timeout=300, verbose=False, device_ready_retry_wait=20, device_ready_retry_attempts=3)[source]

ADBAndroid provides all of the methods of mozdevice.ADB with Android specific extensions useful for that platform.

from mozdevice import ADBAndroid as ADBDevice

adb = ADBDevice(...)

if adb.is_device_ready():
    adb.install_app("/tmp/build.apk")
    adb.launch_fennec("org.mozilla.fennec")

Informational methods

ADBAndroid.get_battery_percentage(self, timeout=None)

Returns the battery charge as a percentage.

Parameters:

timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Returns:

battery charge as a percentage.

Raises:
  • ADBTimeoutError
  • ADBError

System control methods

ADBAndroid.is_device_ready(self, timeout=None)

Checks if a device is ready for testing.

This method uses the android only package manager to check for readiness.

Parameters:

timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADB constructor is used.

Raises:
  • ADBTimeoutError
  • ADBError
ADBAndroid.power_on(self, timeout=None)

Sets the device’s power stayon value.

Parameters:

timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADB constructor is used.

Raises:
  • ADBTimeoutError
  • ADBError
ADBAndroid.reboot(self, timeout=None)

Reboots the device.

This method uses the Android only package manager to determine if the device is ready after the reboot.

Parameters:

timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADB constructor is used.

Raises:
  • ADBTimeoutError
  • ADBError

reboot() reboots the device, issues an adb wait-for-device in order to wait for the device to complete rebooting, then calls is_device_ready() to determine if the device has completed booting.

Application management methods

ADBAndroid.install_app(self, apk_path, timeout=None)

Installs an app on the device.

Parameters:
  • apk_path – string containing the apk file name to be installed.
  • timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADB constructor is used.
Raises:
  • ADBTimeoutError
  • ADBError
ADBAndroid.is_app_installed(self, app_name, timeout=None)

Returns True if an app is installed on the device.

Parameters:
  • app_name – string containing the name of the app to be checked.
  • timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADB constructor is used.
Raises:
  • ADBTimeoutError
  • ADBError
ADBAndroid.launch_application(self, app_name, activity_name, intent, url=None, extras=None, wait=True, fail_if_running=True, timeout=None)

Launches an Android application

Parameters:
  • app_name – Name of application (e.g. com.android.chrome)
  • activity_name – Name of activity to launch (e.g. .Main)
  • intent – Intent to launch application with
  • url – URL to open
  • extras – Dictionary of extra arguments for application.
  • wait – If True, wait for application to start before returning.
  • fail_if_running – Raise an exception if instance of application is already running.
  • timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADB constructor is used.
Raises:
  • ADBTimeoutError
  • ADBError
ADBAndroid.launch_fennec(self, app_name, intent="android.intent.action.VIEW", moz_env=None, extra_args=None, url=None, wait=True, fail_if_running=True, timeout=None)

Convenience method to launch Fennec on Android with various debugging arguments

Parameters:
  • app_name – Name of fennec application (e.g. org.mozilla.fennec)
  • intent – Intent to launch application.
  • moz_env – Mozilla specific environment to pass into application.
  • extra_args – Extra arguments to be parsed by fennec.
  • url – URL to open
  • wait – If True, wait for application to start before returning
  • fail_if_running – Raise an exception if instance of application is already running
  • timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADB constructor is used.
Raises:
  • ADBTimeoutError
  • ADBError
ADBAndroid.stop_application(self, app_name, timeout=None, root=False)

Stops the specified application

For Android 3.0+, we use the “am force-stop” to do this, which is reliable and does not require root. For earlier versions of Android, we simply try to manually kill the processes started by the app repeatedly until none is around any more. This is less reliable and does require root.

Parameters:
  • app_name – Name of application (e.g. com.android.chrome)
  • timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADB constructor is used.
Raises:
  • ADBTimeoutError
  • ADBError
ADBAndroid.uninstall_app(self, app_name, reboot=False, timeout=None)

Uninstalls an app on the device.

Parameters:
  • app_name – string containing the name of the app to be uninstalled.
  • reboot – boolean flag indicating that the device should be rebooted after the app is uninstalled. No reboot occurs if the app is not installed.
  • timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADB constructor is used.
Raises:
  • ADBTimeoutError
  • ADBError
ADBAndroid.update_app(self, apk_path, timeout=None)

Updates an app on the device and reboots.

Parameters:
  • apk_path – string containing the apk file name to be updated.
  • timeout – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADB constructor is used.
Raises:
  • ADBTimeoutError
  • ADBError

ADBProcess

class mozdevice.ADBProcess(args)[source]

ADBProcess encapsulates the data related to executing the adb process.

ADBError

exception mozdevice.ADBError[source]

ADBError is raised in situations where a command executed on a device either exited with a non-zero exitcode or when an unexpected error condition has occurred. Generally, ADBErrors can be handled and the device can continue to be used.

ADBRootError

exception mozdevice.ADBRootError[source]

ADBRootError is raised when a shell command is to be executed as root but the device does not support it. This error is fatal since there is no recovery possible by the script. You must either root your device or change your scripts to not require running as root.

ADBTimeoutError

exception mozdevice.ADBTimeoutError[source]

ADBTimeoutError is raised when either a host command or shell command takes longer than the specified timeout to execute. The timeout value is set in the ADBCommand constructor and is 300 seconds by default. This error is typically fatal since the host is having problems communicating with the device. You may be able to recover by rebooting, but this is not guaranteed.

Recovery options are:

  • Killing and restarting the adb server via

    adb kill-server; adb start-server
    
  • Rebooting the device manually.

  • Rebooting the host.