mobly.controllers package

Subpackages

Submodules

mobly.controllers.android_device module

class mobly.controllers.android_device.AndroidDevice(serial='')[source]

Bases: object

Class representing an android device.

Each object of this class represents one Android device in Mobly. This class provides various ways, like adb, fastboot, and Mobly snippets, to control an Android device, whether it’s a real device or an emulator instance.

You can also register your own services to the device’s service manager. See the docs of service_manager and base_service for details.

serial

A string that’s the serial number of the Android device.

log_path

A string that is the path where all logs collected on this android device should be stored.

log

A logger adapted from root logger with an added prefix specific to an AndroidDevice instance. The default prefix is [AndroidDevice|<serial>]. Use self.debug_tag = ‘tag’ to use a different tag in the prefix.

adb_logcat_file_path

A string that’s the full path to the adb logcat file collected, if any.

adb

An AdbProxy object used for interacting with the device via adb.

fastboot

A FastbootProxy object used for interacting with the device via fastboot.

services

ServiceManager, the manager of long-running services on the device.

adb_logcat_file_path
add_device_info(name, info)[source]

Add information of the device to be pulled into controller info.

Adding the same info name the second time will override existing info.

Parameters:
  • name – string, name of this info.
  • info – serializable, content of the info.
build_info

Gets the build info of this Android device, including build id and type.

This is not available if the device is in bootloader mode.

Returns:A dict with the build info of this Android device, or None if the device is in bootloader mode.
debug_tag

A string that represents a device object in debug info. Default value is the device serial.

This will be used as part of the prefix of debugging messages emitted by this device object, like log lines and the message of DeviceError.

device_info

Information to be pulled into controller info.

The latest serial, model, and build_info are included. Additional info can be added via add_device_info.

ed

Attribute for direct access of sl4a’s event dispatcher.

Not recommended. This is here for backward compatibility reasons.

Preferred: directly access ad.services.sl4a.ed.

generate_filename(file_type, time_identifier=None, extension_name=None)[source]

Generates a name for an output file related to this device.

The name follows the pattern:

{file type},{debug_tag},{serial},{model},{time identifier}.{ext}

“debug_tag” is only added if it’s different from the serial. “ext” is added if specified by user.

Parameters:
  • file_type – string, type of this file, like “logcat” etc.
  • time_identifier – string or RuntimeTestInfo. If a RuntimeTestInfo is passed in, the signature of the test case will be used. If a string is passed in, the string itself will be used. Otherwise the current timestamp will be used.
  • extension_name – string, the extension name of the file.
Returns:

String, the filename generated.

handle_reboot()[source]

Properly manage the service life cycle when the device needs to temporarily disconnect.

The device can temporarily lose adb connection due to user-triggered reboot. Use this function to make sure the services started by Mobly are properly stopped and restored afterwards.

For sample usage, see self.reboot().

handle_usb_disconnect()[source]

Properly manage the service life cycle when USB is disconnected.

The device can temporarily lose adb connection due to user-triggered USB disconnection, e.g. the following cases can be handled by this method:

  • Power measurement: Using Monsoon device to measure battery consumption would potentially disconnect USB.
  • Unplug USB so device loses connection.
  • ADB connection over WiFi and WiFi got disconnected.
  • Any other type of USB disconnection, as long as snippet session can be kept alive while USB disconnected (reboot caused USB disconnection is not one of these cases because snippet session cannot survive reboot. Use handle_reboot() instead).

Use this function to make sure the services started by Mobly are properly reconnected afterwards.

Just like the usage of self.handle_reboot(), this method does not automatically detect if the disconnection is because of a reboot or USB disconnect. Users of this function should make sure the right handle_* function is used to handle the correct type of disconnection.

This method also reconnects snippet event client. Therefore, the callback objects created (by calling Async RPC methods) before disconnection would still be valid and can be used to retrieve RPC execution result after device got reconnected.

Example Usage:

with ad.handle_usb_disconnect():
  try:
    # User action that triggers USB disconnect, could throw
    # exceptions.
    do_something()
  finally:
    # User action that triggers USB reconnect
    action_that_reconnects_usb()
    # Make sure device is reconnected before returning from this
    # context
    ad.adb.wait_for_device(timeout=SOME_TIMEOUT)
has_active_service

True if any service is running on the device.

A service can be a snippet or logcat collection.

is_adb_detectable()[source]

Checks if USB is on and device is ready by verifying adb devices.

is_adb_root

True if adb is running as root for this device.

is_boot_completed()[source]

Checks if device boot is completed by verifying system property.

is_bootloader

True if the device is in bootloader mode.

is_emulator

Whether this device is probably an emulator.

Returns:True if this is probably an emulator.
is_rootable
load_config(config)[source]

Add attributes to the AndroidDevice object based on config.

Parameters:config – A dictionary representing the configs.
Raises:Error – The config is trying to overwrite an existing attribute.
load_snippet(name, package)[source]

Starts the snippet apk with the given package name and connects.

Examples:

ad.load_snippet(
    name='maps', package='com.google.maps.snippets')
ad.maps.activateZoom('3')
Parameters:
  • name – string, the attribute name to which to attach the snippet client. E.g. name=’maps’ attaches the snippet client to ad.maps.
  • package – string, the package name of the snippet apk to connect to.
Raises:

SnippetError – Illegal load operations are attempted.

log_path

A string that is the path for all logs collected from this device.

model

The Android code name for the device.

reboot()[source]

Reboots the device.

Generally one should use this method to reboot the device instead of directly calling adb.reboot. Because this method gracefully handles the teardown and restoration of running services.

This method is blocking and only returns when the reboot has completed and the services restored.

Raises:Error – Waiting for completion timed out.
root_adb()[source]

Change adb to root mode for this device if allowed.

If executed on a production build, adb will not be switched to root mode per security restrictions.

run_iperf_client(server_host, extra_args='')[source]

Start iperf client on the device.

Return status as true if iperf client start successfully. And data flow information as results.

Parameters:
  • server_host – Address of the iperf server.
  • extra_args – A string representing extra arguments for iperf client, e.g. ‘-i 1 -t 30’.
Returns:

true if iperf client start successfully. results: results have data flow information

Return type:

status

serial

The serial number used to identify a device.

This is essentially the value used for adb’s -s arg, which means it can be a network address or USB bus number.

sl4a

Attribute for direct access of sl4a client.

Not recommended. This is here for backward compatibility reasons.

Preferred: directly access ad.services.sl4a.

take_bug_report(test_name=None, begin_time=None, timeout=300, destination=None)[source]

Takes a bug report on the device and stores it in a file.

Parameters:
  • test_name – Name of the test method that triggered this bug report.
  • begin_time – Timestamp of when the test started. If not set, then this will default to the current time.
  • timeout – float, the number of seconds to wait for bugreport to complete, default is 5min.
  • destination – string, path to the directory where the bugreport should be saved.
Returns:

A string that is the absolute path to the bug report on the host.

take_screenshot(destination, prefix='screenshot')[source]

Takes a screenshot of the device.

Parameters:
  • destination – string, full path to the directory to save in.
  • prefix – string, prefix file name of the screenshot.
Returns:

string, full path to the screenshot file on the host.

unload_snippet(name)[source]

Stops a snippet apk.

Parameters:name – The attribute name the snippet server is attached with.
Raises:SnippetError – The given snippet name is not registered.
update_serial(new_serial)[source]

Updates the serial number of a device.

The “serial number” used with adb’s -s arg is not necessarily the actual serial number. For remote devices, it could be a combination of host names and port numbers.

This is used for when such identifier of remote devices changes during a test. For example, when a remote device reboots, it may come back with a different serial number.

This is NOT meant for switching the object to represent another device.

We intentionally did not make it a regular setter of the serial property so people don’t accidentally call this without understanding the consequences.

Parameters:new_serial – string, the new serial number for the same device.
Raises:DeviceError – tries to update serial when any service is running.
wait_for_boot_completion(timeout=900)[source]

Waits for Android framework to broadcast ACTION_BOOT_COMPLETED.

This function times out after 15 minutes.

Parameters:timeout – float, the number of seconds to wait before timing out. If not specified, no timeout takes effect.
class mobly.controllers.android_device.AndroidDeviceLoggerAdapter(logger, extra)[source]

Bases: logging.LoggerAdapter

A wrapper class that adds a prefix to each log line.

Usage:

my_log = AndroidDeviceLoggerAdapter(logging.getLogger(), {
  'tag': <custom tag>
})

Then each log line added by my_log will have a prefix ‘[AndroidDevice|<tag>]’

process(msg, kwargs)[source]

Process the logging message and keyword arguments passed in to a logging call to insert contextual information. You can either manipulate the message itself, the keyword args or both. Return the message and kwargs modified (or not) to suit your needs.

Normally, you’ll only need to override this one method in a LoggerAdapter subclass for your specific needs.

class mobly.controllers.android_device.BuildInfoConstants(build_info_key, system_prop_key)[source]

Bases: enum.Enum

Enums for build info constants used for AndroidDevice build info.

build_info_key

The key used for the build_info dictionary in AndroidDevice.

system_prop_key

The key used for getting the build info from system properties.

BUILD_CHARACTERISTICS = ('build_characteristics', 'ro.build.characteristics')
BUILD_FINGERPRINT = ('build_fingerprint', 'ro.build.fingerprint')
BUILD_ID = ('build_id', 'ro.build.id')
BUILD_PRODUCT = ('build_product', 'ro.build.product')
BUILD_TYPE = ('build_type', 'ro.build.type')
BUILD_VERSION_CODENAME = ('build_version_codename', 'ro.build.version.codename')
BUILD_VERSION_INCREMENTAL = ('build_version_incremental', 'ro.build.version.incremental')
BUILD_VERSION_SDK = ('build_version_sdk', 'ro.build.version.sdk')
DEBUGGABLE = ('debuggable', 'ro.debuggable')
HARDWARE = ('hardware', 'ro.hardware')
PRODUCT_NAME = ('product_name', 'ro.product.name')
mobly.controllers.android_device.create(configs)[source]

Creates AndroidDevice controller objects.

Parameters:configs – A list of dicts, each representing a configuration for an Android device.
Returns:A list of AndroidDevice objects.
mobly.controllers.android_device.destroy(ads)[source]

Cleans up AndroidDevice objects.

Parameters:ads – A list of AndroidDevice objects.
mobly.controllers.android_device.filter_devices(ads, func)[source]

Finds the AndroidDevice instances from a list that match certain conditions.

Parameters:
  • ads – A list of AndroidDevice instances.
  • func – A function that takes an AndroidDevice object and returns True if the device satisfies the filter condition.
Returns:

A list of AndroidDevice instances that satisfy the filter condition.

mobly.controllers.android_device.get_all_instances(include_fastboot=False)[source]

Create AndroidDevice instances for all attached android devices.

Parameters:include_fastboot – Whether to include devices in bootloader mode or not.
Returns:A list of AndroidDevice objects each representing an android device attached to the computer.
mobly.controllers.android_device.get_device(ads, **kwargs)[source]

Finds a unique AndroidDevice instance from a list that has specific attributes of certain values.

Example

get_device(android_devices, label=’foo’, phone_number=’1234567890’) get_device(android_devices, model=’angler’)

Parameters:
  • ads – A list of AndroidDevice instances.
  • kwargs – keyword arguments used to filter AndroidDevice instances.
Returns:

The target AndroidDevice instance.

Raises:

Error – None or more than one device is matched.

mobly.controllers.android_device.get_devices(ads, **kwargs)[source]

Finds a list of AndroidDevice instance from a list that has specific attributes of certain values.

Example

get_devices(android_devices, label=’foo’, phone_number=’1234567890’) get_devices(android_devices, model=’angler’)

Parameters:
  • ads – A list of AndroidDevice instances.
  • kwargs – keyword arguments used to filter AndroidDevice instances.
Returns:

A list of target AndroidDevice instances.

Raises:

Error – No devices are matched.

mobly.controllers.android_device.get_info(ads)[source]

Get information on a list of AndroidDevice objects.

Parameters:ads – A list of AndroidDevice objects.
Returns:A list of dict, each representing info for an AndroidDevice objects.
mobly.controllers.android_device.get_instances(serials)[source]

Create AndroidDevice instances from a list of serials.

Parameters:serials – A list of android device serials.
Returns:A list of AndroidDevice objects.
mobly.controllers.android_device.get_instances_with_configs(configs)[source]

Create AndroidDevice instances from a list of dict configs.

Each config should have the required key-value pair ‘serial’.

Parameters:configs – A list of dicts each representing the configuration of one android device.
Returns:A list of AndroidDevice objects.
mobly.controllers.android_device.list_adb_devices()[source]

List all android devices connected to the computer that are detected by adb.

Returns:A list of android device serials. Empty if there’s none.
mobly.controllers.android_device.list_adb_devices_by_usb_id()[source]

List the usb id of all android devices connected to the computer that are detected by adb.

Returns:A list of strings that are android device usb ids. Empty if there’s none.
mobly.controllers.android_device.list_fastboot_devices()[source]

List all android devices connected to the computer that are in in fastboot mode. These are detected by fastboot.

This function doesn’t raise any error if fastboot binary doesn’t exist, because FastbootProxy itself doesn’t raise any error.

Returns:A list of android device serials. Empty if there’s none.
mobly.controllers.android_device.parse_device_list(device_list_str, key)[source]

Parses a byte string representing a list of devices.

The string is generated by calling either adb or fastboot. The tokens in each string is tab-separated.

Parameters:
  • device_list_str – Output of adb or fastboot.
  • key – The token that signifies a device in device_list_str.
Returns:

A list of android device serial numbers.

mobly.controllers.android_device.take_bug_reports(ads, test_name=None, begin_time=None, destination=None)[source]

Takes bug reports on a list of android devices.

If you want to take a bug report, call this function with a list of android_device objects in on_fail. But reports will be taken on all the devices in the list concurrently. Bug report takes a relative long time to take, so use this cautiously.

Parameters:
  • ads – A list of AndroidDevice instances.
  • test_name – Name of the test method that triggered this bug report. If None, the default name “bugreport” will be used.
  • begin_time – timestamp taken when the test started, can be either string or int. If None, the current time will be used.
  • destination – string, path to the directory where the bugreport should be saved.

mobly.controllers.attenuator module

Controller module for attenuators.

Sample Config:

"Attenuator": [
    {
        "address": "192.168.1.12",
        "port": 23,
        "model": "minicircuits",
        "paths": ["AP1-2G", "AP1-5G", "AP2-2G", "AP2-5G"]
    },
    {
        "address": "192.168.1.14",
        "port": 23,
        "model": "minicircuits",
        "paths": ["AP-DUT"]
    }
]
class mobly.controllers.attenuator.AttenuatorPath(attenuation_device, idx=0, name=None)[source]

Bases: object

A convenience class that allows users to control each attenuator path separately as different objects, as opposed to passing in an index number to the functions of an attenuator device object.

This decouples the test code from the actual attenuator device used in the physical test bed.

For example, if a test needs to attenuate four signal paths, this allows the test to do:

self.attenuation_paths[0].set_atten(50)
self.attenuation_paths[1].set_atten(40)

instead of:

self.attenuators[0].set_atten(0, 50)
self.attenuators[0].set_atten(1, 40)

The benefit the former is that the physical test bed can use either four single-channel attenuators, or one four-channel attenuators. Whereas the latter forces the test bed to use a four-channel attenuator.

get_atten()[source]

Gets the current attenuation setting of Attenuator.

Returns:A float that is the current attenuation value. Unit is db.
get_max_atten()[source]

Gets the max attenuation supported by the Attenuator.

Returns:A float that is the max attenuation value.
set_atten(value)[source]

This function sets the attenuation of Attenuator.

Parameters:value – This is a floating point value for nominal attenuation to be set. Unit is db.
exception mobly.controllers.attenuator.Error[source]

Bases: Exception

This is the Exception class defined for all errors generated by Attenuator-related modules.

mobly.controllers.attenuator.create(configs)[source]
mobly.controllers.attenuator.destroy(objs)[source]

mobly.controllers.iperf_server module

class mobly.controllers.iperf_server.IPerfResult(result_path)[source]

Bases: object

avg_rate

Average receiving rate in MB/s over the entire run.

If the result is not from a success run, this property is None.

avg_receive_rate

Average receiving rate in MB/s over the entire run. This data may not exist if iperf was interrupted.

If the result is not from a success run, this property is None.

avg_send_rate

Average sending rate in MB/s over the entire run. This data may not exist if iperf was interrupted.

If the result is not from a success run, this property is None.

error
get_json()[source]
Returns:The raw json output from iPerf.
class mobly.controllers.iperf_server.IPerfServer(port, log_path)[source]

Bases: object

Class that handles iperf3 operations.

start(extra_args='', tag='')[source]

Starts iperf server on specified port.

Parameters:
  • extra_args – A string representing extra arguments to start iperf server with.
  • tag – Appended to log file name to identify logs from different iperf runs.
stop()[source]
mobly.controllers.iperf_server.create(configs)[source]
mobly.controllers.iperf_server.destroy(objs)[source]

mobly.controllers.monsoon module

mobly.controllers.sniffer module

class mobly.controllers.sniffer.ActiveCaptureContext(sniffer, timeout=None)[source]

Bases: object

This class defines an object representing an active sniffer capture.

The object is returned by a Sniffer.start_capture() command and terminates the capture when the ‘with’ clause exits. It is syntactic sugar for try/finally.

exception mobly.controllers.sniffer.ExecutionError[source]

Bases: mobly.controllers.sniffer.SnifferError

This exception is thrown when trying to configure the capture device or when trying to execute the capture operation.

When this exception is seen, it is possible that the sniffer module is run without sudo (for local sniffers) or keys are out-of-date (for remote sniffers).

exception mobly.controllers.sniffer.InvalidDataError[source]

Bases: Exception

This exception is thrown when invalid configuration data is passed to a method.

exception mobly.controllers.sniffer.InvalidOperationError[source]

Bases: mobly.controllers.sniffer.SnifferError

Certain methods may only be accessed when the instance upon which they are invoked is in a certain state. This indicates that the object is not in the correct state for a method to be called.

class mobly.controllers.sniffer.Sniffer(interface, logger, base_configs=None)[source]

Bases: object

This class defines an object representing a sniffer.

The object defines the generic behavior of sniffers - irrespective of how they are implemented, or where they are located: on the local machine or on the remote machine.

CONFIG_KEY_CHANNEL = 'channel'
get_capture_file()[source]

The sniffer places a capture in the logger directory. This function enables the caller to obtain the path of that capture.

Returns:The full path of the current or last capture.
get_descriptor()[source]

This function returns a string describing the sniffer. The specific string (and its format) is up to each derived sniffer type.

Returns:A string describing the sniffer.
get_interface()[source]

This function returns The interface used to configure the sniffer, e.g. ‘wlan0’.

Returns:The interface (string) used to configure the sniffer. Corresponds to the ‘Interface’ key of the sniffer configuration.
get_subtype()[source]

This function returns the sub-type of the sniffer.

Returns:The sub-type (string) of the sniffer. Corresponds to the ‘SubType’ key of the sniffer configuration.
get_type()[source]

This function returns the type of the sniffer.

Returns:The type (string) of the sniffer. Corresponds to the ‘Type’ key of the sniffer configuration.
start_capture(override_configs=None, additional_args=None, duration=None, packet_count=None)[source]

This function starts a capture which is saved to the specified file path.

Depending on the type/subtype and configuration of the sniffer the capture may terminate on its own or may require an explicit call to the stop_capture() function.

This is a non-blocking function so a terminating function must be called either explicitly or implicitly:

  • Explicitly: call either stop_capture() or wait_for_capture()
  • Implicitly: use with a with clause. The wait_for_capture()
    function will be called if a duration is specified (i.e. is not None), otherwise a stop_capture() will be called.

The capture is saved to a file in the log path of the logger. Use the get_capture_file() to get the full path to the current or most recent capture.

Parameters:
  • override_configs – A dictionary which is combined with the base_configs (“BaseConfigs” in the sniffer configuration). The keys (specified by Sniffer.CONFIG_KEY_*) determine the configuration of the sniffer for this specific capture.
  • additional_args – A string specifying additional raw command-line arguments to pass to the underlying sniffer. The interpretation of these flags is sniffer-dependent.
  • duration – An integer specifying the number of seconds over which to capture packets. The sniffer will be terminated after this duration. Used in implicit mode when using a ‘with’ clause. In explicit control cases may have to be performed using a sleep+stop or as the timeout argument to the wait function.
  • packet_count – An integer specifying the number of packets to capture before terminating. Should be used with duration to guarantee that capture terminates at some point (even if did not capture the specified number of packets).
Returns:

An ActiveCaptureContext process which can be used with a ‘with’ clause.

Raises:
  • InvalidDataError – for invalid configurations
  • NoPermissionError – if an error occurs while configuring and running the sniffer.
stop_capture()[source]

This function stops a capture and guarantees that the capture is saved to the capture file configured during the start_capture() method. Depending on the type of the sniffer the file may previously contain partial results (e.g. for a local sniffer) or may not exist until the stop_capture() method is executed (e.g. for a remote sniffer).

Depending on the type/subtype and configuration of the sniffer the capture may terminate on its own without requiring a call to this function. In such a case it is still necessary to call either this function or the wait_for_capture() function to make sure that the capture file is moved to the correct location.

Raises:NoPermissionError – No permission when trying to stop a capture and save the capture file.
wait_for_capture(timeout=None)[source]

This function waits for a capture to terminate and guarantees that the capture is saved to the capture file configured during the start_capture() method. Depending on the type of the sniffer the file may previously contain partial results (e.g. for a local sniffer) or may not exist until the stop_capture() method is executed (e.g. for a remote sniffer).

Depending on the type/subtype and configuration of the sniffer the capture may terminate on its own without requiring a call to this function. In such a case it is still necessary to call either this function or the stop_capture() function to make sure that the capture file is moved to the correct location.

Parameters:timeout – An integer specifying the number of seconds to wait for the capture to terminate on its own. On expiration of the timeout the sniffer is stopped explicitly using the stop_capture() function.
Raises:NoPermissionError – No permission when trying to stop a capture and save the capture file.
exception mobly.controllers.sniffer.SnifferError[source]

Bases: Exception

This is the Exception class defined for all errors generated by Sniffer-related modules.

mobly.controllers.sniffer.create(configs)[source]

Initializes the sniffer structures based on the JSON configuration. The expected keys are:

  • Type: A first-level type of sniffer. Planned to be ‘local’ for
    sniffers running on the local machine, or ‘remote’ for sniffers running remotely.
  • SubType: The specific sniffer type to be used.
  • Interface: The WLAN interface used to configure the sniffer.
  • BaseConfigs: A dictionary specifying baseline configurations of
    the sniffer. Configurations can be overridden when starting a capture. The keys must be one of the Sniffer.CONFIG_KEY_* values.
mobly.controllers.sniffer.destroy(objs)[source]

Destroys the sniffers and terminates any ongoing capture sessions.

Module contents