mobly.controllers.android_device_lib package

Submodules

mobly.controllers.android_device_lib.adb module

exception mobly.controllers.android_device_lib.adb.AdbError(cmd, stdout, stderr, ret_code, serial='')[source]

Bases: mobly.controllers.android_device_lib.adb.Error

Raised when an adb command encounters an error.

cmd

list of strings, the adb command executed.

stdout

byte string, the raw stdout of the command.

stderr

byte string, the raw stderr of the command.

ret_code

int, the return code of the command.

serial

string, the serial of the device the command is executed on. This is an empty string if the adb command is not specific to a device.

class mobly.controllers.android_device_lib.adb.AdbProxy(serial='')[source]

Bases: object

Proxy class for ADB.

For syntactic reasons, the ‘-’ in adb commands need to be replaced with ‘_’. Can directly execute adb commands on an object: >> adb = AdbProxy(<serial>) >> adb.start_server() >> adb.devices() # will return the console output of “adb devices”.

By default, command args are expected to be an iterable which is passed directly to subprocess.Popen(): >> adb.shell([‘echo’, ‘a’, ‘b’])

This way of launching commands is recommended by the subprocess documentation to avoid shell injection vulnerabilities and avoid having to deal with multiple layers of shell quoting and different shell environments between different OSes.

If you really want to run the command through the system shell, this is possible by supplying shell=True, but try to avoid this if possible: >> adb.shell(‘cat /foo > /tmp/file’, shell=True)

connect(address) → bytes[source]

Executes the adb connect command with proper status checking.

Parameters:address – string, the address of the Android instance to connect to.
Returns:The stdout content.
Raises:AdbError – if the connection failed.
current_user_id

The integer ID of the current Android user.

Some adb commands require specifying a user ID to work properly. Use this to get the current user ID.

Note a “user” is not the same as an “account” in Android. See AOSP’s documentation for details. https://source.android.com/devices/tech/admin/multi-user

forward(args=None, shell=False) → bytes[source]
getprop(prop_name, timeout=10)[source]

Get a property of the device.

This is a convenience wrapper for adb shell getprop xxx.

Parameters:
  • prop_name – A string that is the name of the property to get.
  • timeout – float, the number of seconds to wait before timing out. If not specified, the DEFAULT_GETPROP_TIMEOUT_SEC is used.
Returns:

A string that is the value of the property, or None if the property doesn’t exist.

getprops(prop_names)[source]

Get multiple properties of the device.

This is a convenience wrapper for adb shell getprop. Use this to reduce the number of adb calls when getting multiple properties.

Parameters:prop_names – list of strings, the names of the properties to get.
Returns:A dict containing name-value pairs of the properties requested, if they exist.
has_shell_command(command) → bool[source]

Checks to see if a given check command exists on the device.

Parameters:command – A string that is the name of the command to check.
Returns:A boolean that is True if the command exists and False otherwise.
instrument(package, options=None, runner=None, handler=None) → bytes[source]

Runs an instrumentation command on the device.

This is a convenience wrapper to avoid parameter formatting.

Example:

device.instrument(
  'com.my.package.test',
  options = {
    'class': 'com.my.package.test.TestSuite',
  },
)
Parameters:
  • package – string, the package of the instrumentation tests.
  • options – dict, the instrumentation options including the test class.
  • runner – string, the test runner name, which defaults to DEFAULT_INSTRUMENTATION_RUNNER.
  • handler – optional func, when specified the function is used to parse the instrumentation stdout line by line as the output is generated; otherwise, the stdout is simply returned once the instrumentation is finished.
Returns:

The stdout of instrumentation command or the stderr if the handler

is set.

root() → bytes[source]

Enables ADB root mode on the device.

This method will retry to execute the command adb root when an AdbError occurs, since sometimes the error adb: unable to connect for root: closed is raised when executing adb root immediately after the device is booted to OS.

Returns:A string that is the stdout of root command.
Raises:AdbError – If the command exit code is not 0.
exception mobly.controllers.android_device_lib.adb.AdbTimeoutError(cmd, timeout, serial='')[source]

Bases: mobly.controllers.android_device_lib.adb.Error

Raised when an command did not complete within expected time.

cmd

list of strings, the adb command that timed out

timeout

float, the number of seconds passed before timing out.

serial

string, the serial of the device the command is executed on. This is an empty string if the adb command is not specific to a device.

exception mobly.controllers.android_device_lib.adb.Error[source]

Bases: Exception

Base error type for adb proxy module.

mobly.controllers.android_device_lib.adb.is_adb_available()[source]

Checks if adb is available as a command line tool.

Returns:True if adb binary is available in console, False otherwise.
mobly.controllers.android_device_lib.adb.list_occupied_adb_ports()[source]

Lists all the host ports occupied by adb forward.

This is useful because adb will silently override the binding if an attempt to bind to a port already used by adb was made, instead of throwing binding error. So one should always check what ports adb is using before trying to bind to a port with adb.

Returns:A list of integers representing occupied host ports.

mobly.controllers.android_device_lib.callback_handler module

class mobly.controllers.android_device_lib.callback_handler.CallbackHandler(callback_id, event_client, ret_value, method_name, ad)[source]

Bases: object

The class used to handle a specific group of callback events.

DEPRECATED: Use mobly.controllers.android_device_lib.callback_handler_v2.CallbackHandlerV2 instead.

All the events handled by a CallbackHandler are originally triggered by one async Rpc call. All the events are tagged with a callback_id specific to a call to an AsyncRpc method defined on the server side.

The raw message representing an event looks like:

{
  'callbackId': <string, callbackId>,
  'name': <string, name of the event>,
  'time': <long, epoch time of when the event was created on the
    server side>,
  'data': <dict, extra data from the callback on the server side>
}

Each message is then used to create a SnippetEvent object on the client side.

ret_value

The direct return value of the async Rpc call.

callback_id
getAll(event_name)[source]

Gets all the events of a certain name that have been received so far. This is a non-blocking call.

Parameters:
  • callback_id – The id of the callback.
  • event_name – string, the name of the event to get.
Returns:

A list of SnippetEvent, each representing an event from the Java side.

waitAndGet(event_name, timeout=120)[source]

Blocks until an event of the specified name has been received and return the event, or timeout.

Parameters:
  • event_name – string, name of the event to get.
  • timeout – float, the number of seconds to wait before giving up.
Returns:

SnippetEvent, the oldest entry of the specified event.

Raises:
  • Error – If the specified timeout is longer than the max timeout supported.
  • TimeoutError – The expected event does not occur within time limit.
waitForEvent(event_name, predicate, timeout=120)[source]

Wait for an event of a specific name that satisfies the predicate.

This call will block until the expected event has been received or time out.

The predicate function defines the condition the event is expected to satisfy. It takes an event and returns True if the condition is satisfied, False otherwise.

Note all events of the same name that are received but don’t satisfy the predicate will be discarded and not be available for further consumption.

Parameters:
  • event_name – string, the name of the event to wait for.
  • predicate – function, a function that takes an event (dictionary) and returns a bool.
  • timeout – float, default is 120s.
Returns:

dictionary, the event that satisfies the predicate if received.

Raises:

TimeoutError – raised if no event that satisfies the predicate is received after timeout seconds.

mobly.controllers.android_device_lib.errors module

exception mobly.controllers.android_device_lib.errors.DeviceError(ad, msg)[source]

Bases: mobly.controllers.android_device_lib.errors.Error

Raised for errors specific to an AndroidDevice object.

exception mobly.controllers.android_device_lib.errors.Error[source]

Bases: mobly.signals.ControllerError

exception mobly.controllers.android_device_lib.errors.ServiceError(device, msg)[source]

Bases: mobly.controllers.android_device_lib.errors.DeviceError

Raised for errors specific to an AndroidDevice service.

A service is inherently associated with a device instance, so the service error type is a subtype of DeviceError.

SERVICE_TYPE = None

mobly.controllers.android_device_lib.event_dispatcher module

exception mobly.controllers.android_device_lib.event_dispatcher.DuplicateError[source]

Bases: mobly.controllers.android_device_lib.event_dispatcher.EventDispatcherError

Raise when a duplicate is being created and it shouldn’t.

class mobly.controllers.android_device_lib.event_dispatcher.EventDispatcher(sl4a)[source]

Bases: object

Class managing events for an sl4a connection.

DEFAULT_TIMEOUT = 60
clean_up()[source]

Clean up and release resources after the event dispatcher polling loop has been broken.

The following things happen: 1. Clear all events and flags. 2. Close the sl4a client the event_dispatcher object holds. 3. Shut down executor without waiting.

clear_all_events()[source]

Clear all event queues and their cached events.

clear_events(event_name)[source]

Clear all events of a particular name.

Parameters:event_name – Name of the events to be popped.
get_event_q(event_name)[source]

Obtain the queue storing events of the specified name.

If no event of this name has been polled, wait for one to.

Returns:A queue storing all the events of the specified name. None if timed out.
Raises:queue.Empty – Raised if the queue does not exist and timeout has passed.
handle_event(event_handler, event_name, user_args, event_timeout=None, cond=None, cond_timeout=None)[source]

Handle events that don’t have registered handlers

In a new thread, poll one event of specified type from its queue and execute its handler. If no such event exists, the thread waits until one appears.

Parameters:
  • event_handler – Handler for the event, which should take at least one argument - the event json object.
  • event_name – Name of the event to be handled.
  • user_args – User arguments for the handler; to be passed in after the event json.
  • event_timeout – Number of seconds to wait for the event to come.
  • cond – A condition to wait on before executing the handler. Should be a threading.Event object.
  • cond_timeout – Number of seconds to wait before the condition times out. Never times out if None.
Returns:

A concurrent.Future object associated with the handler. If blocking call worker.result() is triggered, the handler needs to return something to unblock.

handle_subscribed_event(event_obj, event_name)[source]

Execute the registered handler of an event.

Retrieve the handler and its arguments, and execute the handler in a
new thread.
Parameters:
  • event_obj – Json object of the event.
  • event_name – Name of the event to call handler for.
poll_events()[source]

Continuously polls all types of events from sl4a.

Events are sorted by name and store in separate queues. If there are registered handlers, the handlers will be called with corresponding event immediately upon event discovery, and the event won’t be stored. If exceptions occur, stop the dispatcher and return

pop_all(event_name)[source]

Return and remove all stored events of a specified name.

Pops all events from their queue. May miss the latest ones. If no event is available, return immediately.

Parameters:event_name – Name of the events to be popped.
Returns:List of the desired events.
Raises:IllegalStateError – Raised if pop is called before the dispatcher starts polling.
pop_event(event_name, timeout=60)[source]

Pop an event from its queue.

Return and remove the oldest entry of an event. Block until an event of specified name is available or times out if timeout is set.

Parameters:
  • event_name – Name of the event to be popped.
  • timeout – Number of seconds to wait when event is not present. Never times out if None.
Returns:

The oldest entry of the specified event. None if timed out.

Raises:

IllegalStateError – Raised if pop is called before the dispatcher starts polling.

pop_events(regex_pattern, timeout)[source]

Pop events whose names match a regex pattern.

If such event(s) exist, pop one event from each event queue that satisfies the condition. Otherwise, wait for an event that satisfies the condition to occur, with timeout.

Results are sorted by timestamp in ascending order.

Parameters:
  • regex_pattern – The regular expression pattern that an event name should match in order to be popped.
  • timeout – Number of seconds to wait for events in case no event matching the condition exits when the function is called.
Returns:

Events whose names match a regex pattern. Empty if none exist and the wait timed out.

Raises:
  • IllegalStateError – Raised if pop is called before the dispatcher starts polling.
  • queue.Empty – Raised if no event was found before time out.
register_handler(handler, event_name, args)[source]

Registers an event handler.

One type of event can only have one event handler associated with it.

Parameters:
  • handler – The event handler function to be registered.
  • event_name – Name of the event the handler is for.
  • args – User arguments to be passed to the handler when it’s called.
Raises:
  • IllegalStateError – Raised if attempts to register a handler after the dispatcher starts running.
  • DuplicateError – Raised if attempts to register more than one handler for one type of event.
start()[source]

Starts the event dispatcher.

Initiates executor and start polling events.

Raises:IllegalStateError – Can’t start a dispatcher again when it’s already running.
wait_for_event(event_name, predicate, timeout=60, *args, **kwargs)[source]

Wait for an event that satisfies a predicate to appear.

Continuously pop events of a particular name and check against the predicate until an event that satisfies the predicate is popped or timed out. Note this will remove all the events of the same name that do not satisfy the predicate in the process.

Parameters:
  • event_name – Name of the event to be popped.
  • predicate – A function that takes an event and returns True if the predicate is satisfied, False otherwise.
  • timeout – Number of seconds to wait.
  • *args – Optional positional args passed to predicate().
  • **kwargs – Optional keyword args passed to predicate().
Returns:

The event that satisfies the predicate.

Raises:

queue.Empty – Raised if no event that satisfies the predicate was found before time out.

exception mobly.controllers.android_device_lib.event_dispatcher.EventDispatcherError[source]

Bases: Exception

exception mobly.controllers.android_device_lib.event_dispatcher.IllegalStateError[source]

Bases: mobly.controllers.android_device_lib.event_dispatcher.EventDispatcherError

Raise when user tries to put event_dispatcher into an illegal state.

mobly.controllers.android_device_lib.fastboot module

class mobly.controllers.android_device_lib.fastboot.FastbootProxy(serial='')[source]

Bases: object

Proxy class for fastboot.

For syntactic reasons, the ‘-’ in fastboot commands need to be replaced with ‘_’. Can directly execute fastboot commands on an object: >> fb = FastbootProxy(<serial>) >> fb.devices() # will return the console output of “fastboot devices”.

args(*args)[source]
mobly.controllers.android_device_lib.fastboot.exe_cmd(*cmds)[source]

Executes commands in a new shell. Directing stderr to PIPE.

This is fastboot’s own exe_cmd because of its peculiar way of writing non-error info to stderr.

Parameters:cmds – A sequence of commands and arguments.
Returns:The output of the command run.
Raises:Exception – An error occurred during the command execution.

mobly.controllers.android_device_lib.jsonrpc_client_base module

Base class for clients that communicate with apps over a JSON RPC interface.

The JSON protocol expected by this module is:

Request:
{
  "id": <monotonically increasing integer containing the ID of
       this request>
  "method": <string containing the name of the method to execute>
  "params": <JSON array containing the arguments to the method>
}

Response:
{
  "id": <int id of request that this response maps to>,
  "result": <Arbitrary JSON object containing the result of
         executing the method. If the method could not be
         executed or returned void, contains 'null'.>,
  "error": <String containing the error thrown by executing the
        method. If no error occurred, contains 'null'.>
  "callback": <String that represents a callback ID used to
         identify events associated with a particular
         CallbackHandler object.>
}
class mobly.controllers.android_device_lib.jsonrpc_client_base.JsonRpcClientBase(app_name, ad)[source]

Bases: abc.ABC

Base class for jsonrpc clients that connect to remote servers.

Connects to a remote device running a jsonrpc-compatible app. Before opening a connection a port forward must be setup to go over usb. This be done using adb.forward([local, remote]). Once the port has been forwarded it can be used in this object as the port of communication.

host_port

(int) The host port of this RPC client.

device_port

(int) The device port of this RPC client.

app_name

(str) The user-visible name of the app being communicated with.

uid

(int) The uid of this session.

clear_host_port()[source]

Stops the adb port forwarding of the host port used by this client.

close_socket_connection()[source]

Closes the socket connection to the server.

connect(uid=-1, cmd='initiate')[source]

Opens a connection to a JSON RPC server.

Opens a connection to a remote client. The connection attempt will time out if it takes longer than _SOCKET_CONNECTION_TIMEOUT seconds. Each subsequent operation over this socket will time out after _SOCKET_READ_TIMEOUT seconds as well.

Parameters:
  • uid – int, The uid of the session to join, or UNKNOWN_UID to start a new session.
  • cmd – JsonRpcCommand, The command to use for creating the connection.
Raises:
  • IOError – Raised when the socket times out from io error
  • socket.timeout – Raised when the socket waits to long for connection.
  • ProtocolError – Raised when there is an error in the protocol.
disable_hidden_api_blacklist()[source]

If necessary and possible, disables hidden api blacklist.

disconnect()[source]

Close the connection to the snippet server on the device.

This is a unilateral disconnect from the client side, without tearing down the snippet server running on the device.

The connection to the snippet server can be re-established by calling SnippetClient.restore_app_connection.

restore_app_connection(port=None)[source]

Reconnects to the app after device USB was disconnected.

Instead of creating new instance of the client:
  • Uses the given port (or finds a new available host_port if none is

given). - Tries to connect to remote server with selected port.

Must be implemented by subclasses.

Parameters:

port – If given, this is the host port from which to connect to remote device port. If not provided, find a new available port as host port.

Raises:
  • AppRestoreConnectionError – When the app was not able to be
  • reconnected.
set_snippet_client_verbose_logging(verbose)[source]

Switches verbose logging. True for logging full RPC response.

By default it will only write max_rpc_return_value_length for Rpc return strings. If you need to see full message returned from Rpc, please turn on verbose logging.

max_rpc_return_value_length will set to 1024 by default, the length contains full Rpc response in Json format, included 1st element “id”.

Parameters:verbose – bool. If True, turns on verbose logging, if False turns off
start_app_and_connect()[source]

Starts the server app on the android device and connects to it.

After this, the self.host_port and self.device_port attributes must be set.

Must be implemented by subclasses.

Raises:AppStartError – When the app was not able to be started.
stop_app()[source]

Kills any running instance of the app.

Must be implemented by subclasses.

class mobly.controllers.android_device_lib.jsonrpc_client_base.JsonRpcCommand[source]

Bases: object

Commands that can be invoked on all jsonrpc clients.

INIT: Initializes a new session. CONTINUE: Creates a connection.

CONTINUE = 'continue'
INIT = 'initiate'

mobly.controllers.android_device_lib.jsonrpc_shell_base module

Shared library for frontends to jsonrpc servers.

exception mobly.controllers.android_device_lib.jsonrpc_shell_base.Error[source]

Bases: Exception

class mobly.controllers.android_device_lib.jsonrpc_shell_base.JsonRpcShellBase[source]

Bases: object

load_device(serial=None)[source]

Creates an AndroidDevice for the given serial number.

If no serial is given, it will read from the ANDROID_SERIAL environmental variable. If the environmental variable is not set, then it will read from ‘adb devices’ if there is only one.

main(serial=None)[source]
start_console()[source]

mobly.controllers.android_device_lib.service_manager module

Module for the manager of services.

exception mobly.controllers.android_device_lib.service_manager.Error(ad, msg)[source]

Bases: mobly.controllers.android_device_lib.errors.DeviceError

Root error type for this module.

class mobly.controllers.android_device_lib.service_manager.ServiceManager(device)[source]

Bases: object

Manager for services of AndroidDevice.

A service is a long running process that involves an Android device, like adb logcat or Snippet.

create_output_excerpts_all(test_info)[source]

Creates output excerpts from all services.

This calls create_output_excerpts on all registered services.

Parameters:test_info – RuntimeTestInfo, the test info associated with the scope of the excerpts.
Returns:
Dict, keys are the names of the services, values are the paths to
the excerpt files created by the corresponding services.
for_each(func)[source]

Executes a function with all registered services.

Parameters:func – function, the function to execute. This function should take a service object as args.
has_service_by_name(name)[source]

Checks if the manager has a service registered with a specific name.

Parameters:name – string, the name to look for.
Returns:True if a service is registered with the specified name, False otherwise.
is_any_alive

True if any service is alive; False otherwise.

list_live_services()[source]

Lists the aliases of all the services that are alive.

Order of this list is determined by the order the services are registered in.

Returns:list of strings, the aliases of the services that are running.
pause_all()[source]

Pauses all service instances.

Services will be paused in the reverse order they were registered.

register(alias, service_class, configs=None, start_service=True)[source]

Registers a service.

This will create a service instance, starts the service, and adds the instance to the mananger.

Parameters:
  • alias – string, the alias for this instance.
  • service_class – class, the service class to instantiate.
  • configs – (optional) config object to pass to the service class’s constructor.
  • start_service – bool, whether to start the service instance or not. Default is True.
resume_all()[source]

Resumes all service instances.

Services will be resumed in the order they were registered.

resume_services(service_alises)[source]

Resumes the specified services.

Services will be resumed in the order specified by the input list.

Parameters:service_alises – list of strings, the names of services to start.
start_all()[source]

Starts all inactive service instances.

Services will be started in the order they were registered.

start_services(service_alises)[source]

Starts the specified services.

Services will be started in the order specified by the input list. No-op for services that are already running.

Parameters:service_alises – list of strings, the aliases of services to start.
stop_all()[source]

Stops all active service instances.

Services will be stopped in the reverse order they were registered.

unregister(alias)[source]

Unregisters a service instance.

Stops a service and removes it from the manager.

Parameters:alias – string, the alias of the service instance to unregister.
unregister_all()[source]

Safely unregisters all active instances.

Errors occurred here will be recorded but not raised.

mobly.controllers.android_device_lib.sl4a_client module

JSON RPC interface to android scripting engine.

class mobly.controllers.android_device_lib.sl4a_client.Sl4aClient(ad)[source]

Bases: mobly.controllers.android_device_lib.jsonrpc_client_base.JsonRpcClientBase

A client for interacting with SL4A using Mobly Snippet Lib.

Extra public attributes: ed: Event dispatcher instance for this sl4a client.

restore_app_connection(port=None)[source]

Restores the sl4a after device got disconnected.

Instead of creating new instance of the client:
  • Uses the given port (or find a new available host_port if none is

given). - Tries to connect to remote server with selected port.

Parameters:port – If given, this is the host port from which to connect to remote device port. If not provided, find a new available port as host port.
Raises:AppRestoreConnectionError – When the app was not able to be started.
start_app_and_connect()[source]

Overrides superclass.

stop_app()[source]

Overrides superclass.

stop_event_dispatcher()[source]

mobly.controllers.android_device_lib.snippet_client module

JSON RPC interface to Mobly Snippet Lib.

class mobly.controllers.android_device_lib.snippet_client.SnippetClient(package, ad)[source]

Bases: mobly.controllers.android_device_lib.jsonrpc_client_base.JsonRpcClientBase

A client for interacting with snippet APKs using Mobly Snippet Lib.

DEPRECATED: Use mobly.controllers.android_device_lib.snippet_client_v2.SnippetClientV2 instead.

See superclass documentation for a list of public attributes.

For a description of the launch protocols, see the documentation in mobly-snippet-lib, SnippetRunner.java.

help(print_output=True)[source]

Calls the help RPC, which returns the list of RPC calls available.

This RPC should normally be used in an interactive console environment where the output should be printed instead of returned. Otherwise, newlines will be escaped, which will make the output difficult to read.

Parameters:print_output – A bool for whether the output should be printed.
Returns:
A str containing the help output otherwise None if print_output
wasn’t set.
is_alive

Does the client have an active connection to the snippet server.

restore_app_connection(port=None)[source]

Restores the app after device got reconnected.

Instead of creating new instance of the client:
  • Uses the given port (or find a new available host_port if none is

given). - Tries to connect to remote server with selected port.

Parameters:port – If given, this is the host port from which to connect to remote device port. If not provided, find a new available port as host port.
Raises:AppRestoreConnectionError – When the app was not able to be started.
start_app_and_connect()[source]

Starts snippet apk on the device and connects to it.

This wraps the main logic with safe handling

Raises:AppStartPreCheckError, when pre-launch checks fail.
stop_app()[source]

Kills any running instance of the app.

Must be implemented by subclasses.

user_id

The user id to use for this snippet client.

This value is cached and, once set, does not change through the lifecycles of this snippet client object. This caching also reduces the number of adb calls needed.

Because all the operations of the snippet client should be done for a partucular user.

mobly.controllers.android_device_lib.snippet_event module

class mobly.controllers.android_device_lib.snippet_event.SnippetEvent(callback_id, name, creation_time, data)[source]

Bases: object

The class that represents callback events for mobly snippet library.

DEPRECATED: Use mobly.snippet.callback_event.CallbackEvent instead.

callback_id

string, the callback ID associated with the event.

name

string, the name of the event.

creation_time

int, the epoch time when the event is created on the Rpc server side.

data

dictionary, the data held by the event. Can be None.

mobly.controllers.android_device_lib.snippet_event.from_dict(event_dict)[source]

Create a SnippetEvent object from a dictionary.

DEPRECATED: Use mobly.snippet.callback_event.from_dict instead.

Parameters:event_dict – a dictionary representing an event.
Returns:A SnippetEvent object.

Module contents