mobly.controllers.android_device_lib package

Submodules

mobly.controllers.android_device_lib.adb module

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.

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.

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

Bases: mobly.controllers.android_device_lib.errors.DeviceError

exception mobly.controllers.android_device_lib.callback_handler.TimeoutError(ad, msg)[source]

Bases: mobly.controllers.android_device_lib.callback_handler.Error

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.>
}
exception mobly.controllers.android_device_lib.jsonrpc_client_base.ApiError(ad, msg)[source]

Bases: mobly.controllers.android_device_lib.jsonrpc_client_base.Error

Raised when remote API reports an error.

exception mobly.controllers.android_device_lib.jsonrpc_client_base.AppRestoreConnectionError(ad, msg)[source]

Bases: mobly.controllers.android_device_lib.jsonrpc_client_base.Error

Raised when failed to restore app from disconnection.

exception mobly.controllers.android_device_lib.jsonrpc_client_base.AppStartError(ad, msg)[source]

Bases: mobly.controllers.android_device_lib.jsonrpc_client_base.Error

Raised when the app is not able to be started.

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

Bases: mobly.controllers.android_device_lib.errors.DeviceError

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.

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:
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'
exception mobly.controllers.android_device_lib.jsonrpc_client_base.ProtocolError(ad, msg)[source]

Bases: mobly.controllers.android_device_lib.jsonrpc_client_base.Error

Raised when there is some error in exchanging data with server.

MISMATCHED_API_ID = 'RPC request-response ID mismatch.'
NO_RESPONSE_FROM_HANDSHAKE = 'No response from handshake.'
NO_RESPONSE_FROM_SERVER = 'No response from server. Check the device logcat for crashes.'

mobly.controllers.android_device_lib.jsonrpc_shell_base module

mobly.controllers.android_device_lib.service_manager module

mobly.controllers.android_device_lib.sl4a_client module

mobly.controllers.android_device_lib.snippet_client module

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.

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.

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

Module contents