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) – The command and its arguments to be executed.
  • device_serial (str or None) – The device’s serial number if the adb command is to be executed against a specific device.
  • timeout (integer or None) – 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) – The command and its arguments to be executed.
  • device_serial (str or None) – The device’s serial number if the adb command is to be executed against a specific device.
  • timeout (integer or None) – 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) – The command and its arguments to be executed.
  • timeout (integer or None) – 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) – The command and its arguments to be executed.
  • timeout (integer or None) – 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 (integer or None) – 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 (integer or None) – 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 (integer or None) – 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
  • ADBListDevicesError
  • 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 is an abstract base class which provides methods which can be used to interact with the associated Android or B2G based device. It must be used via one of the concrete implementations in ADBAndroid or ADBB2G.

Host Command methods

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

Executes an adb command on the host against the device.

Parameters:
  • cmds (list) – The command and its arguments to be executed.
  • timeout (integer or None) – 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) – The command and its arguments to be executed.
  • timeout (integer or None) – 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 (str) – The command to be executed.
  • env (dict or None) – Contains the environment variables and their values.
  • cwd (str or None) – The directory from which to execute.
  • timeout (integer or None) – 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 (bool) – Flag 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 (str) – The command to be executed.
  • env (dict or None) – Contains the environment variables and their values.
  • cwd (str or None) – The directory from which to execute.
  • timeout (integer or None) – 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 (bool) – Flag 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 (str) – The command to be executed.
  • env (dict or None) – Contains the environment variables and their values.
  • cwd (str or None) – The directory from which to execute.
  • timeout (integer or None) – 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 (bool) – Flag 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=[])[source]

Clears logcat via adb logcat -c.

Parameters:
  • timeout (integer or None) – 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) – Log buffers to clear. Valid buffers are “radio”, “events”, and “main”. Defaults to “main”.
Raises:
  • ADBTimeoutError
  • ADBError
ADBDevice.get_battery_percentage(timeout=None)[source]

Abstract class that 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
ADBDevice.get_info(directive=None, timeout=None)[source]

Returns a dictionary of information strings about the device.

Parameters:
  • directive
    information you want to get. Options are:
    • battery - battery charge as a percentage
    • disk - total, free, available bytes on disk
    • id - unique id of the device
    • os - name of the os
    • process - list of running processes (same as ps)
    • systime - system time of the device
    • uptime - uptime of the device

    If directive is None, will return all available information

  • 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
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=[])[source]

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

Parameters:
  • filter_specs (list) – Optional logcat messages to be included.
  • format (str) – Optional logcat format.
  • filterOutRexps (list) – Optional logcat messages to be excluded.
  • timeout (integer or None) – 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) – 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(prop, timeout=None)[source]

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

Parameters:
  • prop (str) – The propery name.
  • timeout (integer or None) – 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(timeout=None)[source]

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

Parameters:

timeout (integer or None) – 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

System control methods

ADBDevice.is_device_ready(timeout=None)[source]

Abstract class that returns True if the device is ready.

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
ADBDevice.reboot(timeout=None)[source]

Reboots the 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 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.

File management methods

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

Recursively changes the permissions of a directory on the device.

Parameters:
  • path (str) – The directory name on the device.
  • recursive (bool) – Flag specifying if the command should be executed recursively.
  • mask (str) – The octal permissions.
  • timeout (integer or None) – 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 (bool) – Flag specifying if the command should be executed as root.
Raises:
  • ADBTimeoutError
  • ADBRootError
  • ADBError
ADBDevice.cp(source, destination, recursive=False, timeout=None, root=False)[source]

Copies a file or directory on the device.

Parameters:
  • source – string containing the path of the source file or directory.
  • destination – string containing the path of the destination file or directory.
  • recursive – optional boolean indicating if a recursive copy is to be performed. Required if the source is a directory. Defaults to False. Think cp -R source destination.
  • 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
  • ADBRootError
  • ADBError
ADBDevice.exists(path, timeout=None, root=False)[source]

Returns True if the path exists on the device.

Parameters:
  • path (str) – The directory name on the device.
  • timeout (integer or None) – 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 (bool) – Flag specifying if the command should be executed as root.
Returns:

boolean - True if path exists.

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

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

Parameters:
  • path (str) – The path on the device.
  • timeout (integer or None) – 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 (bool) – Flag 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(path, timeout=None, root=False)[source]

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

Parameters:
  • path (str) – The file name on the device.
  • timeout (integer or None) – 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 (bool) – Flag 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(path, timeout=None, root=False)[source]

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

Parameters:
  • path (str) – The directory name on the device.
  • timeout (integer or None) – 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 (bool) – Flag specifying if the command should be executed as root.
Returns:

list of files/directories contained in the directory.

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

Create a directory on the device.

Parameters:
  • path (str) – The directory name on the device to be created.
  • parents (bool) – Flag indicating if the parent directories are also to be created. Think mkdir -p path.
  • timeout (integer or None) – 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 (bool) – Flag specifying if the command should be executed as root.
Raises:
  • ADBTimeoutError
  • ADBRootError
  • ADBError
ADBDevice.mv(source, destination, timeout=None, root=False)[source]

Moves a file or directory on the device.

Parameters:
  • source – string containing the path of the source file or directory.
  • destination – string containing the path of the destination file or directory.
  • 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
  • ADBRootError
  • ADBError
ADBDevice.push(local, remote, timeout=None)[source]

Pushes a file or directory to the device.

Parameters:
  • local (str) – The name of the local file or directory name.
  • remote (str) – The name of the remote file or directory name.
  • timeout (integer or None) – 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(path, recursive=False, force=False, timeout=None, root=False)[source]

Delete files or directories on the device.

Parameters:
  • path (str) – The path of the remote file or directory.
  • recursive (bool) – Flag specifying if the command is to be applied recursively to the target. Default is False.
  • force (bool) – Flag which if True will not raise an error when attempting to delete a non-existent file. Default is False.
  • timeout (integer or None) – 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 (bool) – Flag specifying if the command should be executed as root.
Raises:
  • ADBTimeoutError
  • ADBRootError
  • ADBError
ADBDevice.rmdir(path, timeout=None, root=False)[source]

Delete empty directory on the device.

Parameters:
  • path (str) – The directory name on the device.
  • timeout (integer or None) – 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 (bool) – Flag 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(timeout=None)[source]

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

Parameters:

timeout (integer or None) – 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(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) – process ids to be killed.
  • sig (integer or None) – signal to be sent to the process.
  • attempts (integer) – number of attempts to try to kill the processes.
  • wait (integer) – number of seconds to wait after each attempt.
  • timeout (integer or None) – 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 (bool) – Flag specifying if the command should be executed as root.
Raises:
  • ADBTimeoutError
  • ADBRootError
  • ADBError
ADBDevice.pkill(appname, sig=None, attempts=3, wait=5, timeout=None, root=False)[source]

Kills a processes on the device matching a name.

Parameters:
  • appname (str) – The app name of the process to be killed. Note that only the first 75 characters of the process name are significant.
  • sig (integer or None) – optional signal to be sent to the process.
  • attempts (integer) – number of attempts to try to kill the processes.
  • wait (integer) – number of seconds to wait after each attempt.
  • timeout (integer or None) – 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 (bool) – Flag specifying if the command should be executed as root.
Raises:
  • ADBTimeoutError
  • ADBRootError
  • ADBError
ADBDevice.process_exist(process_name, timeout=None)[source]

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

Parameters:
  • process_name (str) – The name of the process to check. Note that only the first 75 characters of the process name are significant.
  • timeout (integer or None) – 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 implements ADBDevice providing Android-specific functionality.

from mozdevice import ADBAndroid

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

Informational methods

ADBAndroid.get_battery_percentage(timeout=None)[source]

Returns the battery charge as a percentage.

Parameters:

timeout (integer or None) – 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(timeout=None)[source]

Checks if a device is ready for testing.

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

Parameters:

timeout (integer or None) – 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(timeout=None)[source]

Sets the device’s power stayon value.

Parameters:

timeout (integer or None) – 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

Application management methods

ADBAndroid.install_app(apk_path, timeout=None)[source]

Installs an app on the device.

Parameters:
  • apk_path (str) – The apk file name to be installed.
  • timeout (integer or None) – 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(app_name, timeout=None)[source]

Returns True if an app is installed on the device.

Parameters:
  • app_name (str) – The name of the app to be checked.
  • timeout (integer or None) – 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(app_name, activity_name, intent, url=None, extras=None, wait=True, fail_if_running=True, timeout=None)[source]

Launches an Android application

Parameters:
  • app_name (str) – Name of application (e.g. com.android.chrome)
  • activity_name (str) – Name of activity to launch (e.g. .Main)
  • intent (str) – Intent to launch application with
  • url (str or None) – URL to open
  • extras (dict or None) – Extra arguments for application.
  • wait (bool) – If True, wait for application to start before returning.
  • fail_if_running (bool) – Raise an exception if instance of application is already running.
  • timeout (integer or None) – 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(app_name, intent='android.intent.action.VIEW', moz_env=None, extra_args=None, url=None, wait=True, fail_if_running=True, timeout=None)[source]

Convenience method to launch Fennec on Android with various debugging arguments

Parameters:
  • app_name (str) – Name of fennec application (e.g. org.mozilla.fennec)
  • intent (str) – Intent to launch application.
  • moz_env (str or None) – Mozilla specific environment to pass into application.
  • extra_args (str or None) – Extra arguments to be parsed by fennec.
  • url (str or None) – URL to open
  • wait (bool) – If True, wait for application to start before returning.
  • fail_if_running (bool) – Raise an exception if instance of application is already running.
  • timeout (integer or None) – 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(app_name, timeout=None, root=False)[source]

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 (str) – Name of application (e.g. com.android.chrome)
  • timeout (integer or None) – 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.
  • root (bool) – Flag specifying if the command should be executed as root.
Raises:
  • ADBTimeoutError
  • ADBError
ADBAndroid.uninstall_app(app_name, reboot=False, timeout=None)[source]

Uninstalls an app on the device.

Parameters:
  • app_name (str) – The name of the app to be uninstalled.
  • reboot (bool) – Flag indicating that the device should be rebooted after the app is uninstalled. No reboot occurs if the app is not installed.
  • timeout (integer or None) – 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(apk_path, timeout=None)[source]

Updates an app on the device and reboots.

Parameters:
  • apk_path (str) – The apk file name to be updated.
  • timeout (integer or None) – 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

ADBB2G

class mozdevice.ADBB2G(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]

ADBB2G implements ADBDevice providing B2G-specific functionality.

from mozdevice import ADBB2G

adbdevice = ADBB2G()
print adbdevice.list_files("/mnt/sdcard")
if adbdevice.process_exist("b2g"):
    print "B2G is running"

Informational methods

ADBB2G.get_battery_percentage(timeout=None)[source]

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
ADBB2G.get_info(directive=None, timeout=None)[source]

Returns a dictionary of information strings about the device.

Parameters:
  • directive
    information you want to get. Options are:
    • battery - battery charge as a percentage
    • disk - total, free, available bytes on disk
    • id - unique id of the device
    • memtotal - total memory available on the device
    • os - name of the os
    • process - list of running processes (same as ps)
    • systime - system time of the device
    • uptime - uptime of the device

    If directive is None, will return all available information

  • 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
ADBB2G.get_memory_total(timeout=None)[source]

Returns the total memory available with units.

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:

memory total with units.

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.