mobly.controllers.android_device module¶
- class mobly.controllers.android_device.AndroidDevice(serial='')[source]¶
Bases:
objectClass 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.
- __getattr__(name)[source]¶
Tries to return a snippet client registered with name.
This is for backward compatibility of direct accessing snippet clients.
- property 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.
- property 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.
- property 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.
- property 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.
- 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)
- property has_active_service¶
True if any service is running on the device.
A service can be a snippet or logcat collection.
- property is_adb_root¶
True if adb is running as root for this device.
- property is_bootloader¶
True if the device is in bootloader mode.
- property is_emulator¶
Whether this device is probably an emulator.
- Returns:
True if this is probably an emulator.
- property 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, config=None)[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.
config – snippet_client_v2.Config, the configuration object for controlling the snippet behaviors. See the docstring of the Config class for supported configurations.
- Raises:
SnippetError – Illegal load operations are attempted.
- property log_path¶
A string that is the path for all logs collected from this device.
- property 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
- property 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.
- 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', all_displays=False)[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.
all_displays – bool, if true will take a screenshot on all connnected displays, if false will take a screenshot on the default display.
- Returns:
string, full path to the screenshot file on the host, or list[str], when all_displays is True, the full paths to the screenshot
files 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.
- class mobly.controllers.android_device.AndroidDeviceLoggerAdapter(logger, extra=None)[source]¶
Bases:
LoggerAdapterA 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(value)[source]¶
Bases:
EnumEnums 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')¶
- BUILD_VERSION_SDK_FULL = ('build_version_sdk_full', 'ro.build.version.sdk_full')¶
- 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 –
Represents configurations for Android devices, this can take one of the following forms: * str, only asterisk symbol is accepted, indicating that all connected
Android devices will be used
A list of dict, each representing a configuration for an Android device.
A list of str, each representing the serial number of 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. Everything in this dict should be yaml serializable.
- 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=None)[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. Only devices with the specified key in device_list_str are parsed, such as ‘device’ or ‘fastbootd’. If not specified, all devices listed are parsed.
- 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.