### Class Setup Source: https://github.com/google/mobly/blob/master/docs/mobly.md The setup_class method is an optional setup function executed before any test in the class, used for initializing test environments. ```APIDOC ## setup_class() ### Description Setup function that will be called before executing any test in the class. To signal setup failure, use asserts or raise your own exception. Errors raised from setup_class will trigger on_fail. Implementation is optional. ### Method N/A (Lifecycle method) ### Endpoint N/A (Internal framework method) ``` -------------------------------- ### Test Setup Source: https://github.com/google/mobly/blob/master/docs/mobly.md The setup_test method is an optional setup function executed before each individual test method within a test class. ```APIDOC ## setup_test() ### Description Setup function that will be called every time before executing each test method in the test class. To signal setup failure, use asserts or raise your own exception. Implementation is optional. ### Method N/A (Lifecycle method) ### Endpoint N/A (Internal framework method) ``` -------------------------------- ### Example of assert_count_equal Source: https://github.com/google/mobly/blob/master/docs/mobly.md Demonstrates the usage of `assert_count_equal`. The first example passes, while the second fails due to differing element counts. ```python assert_count_equal([0, 1, 1], [1, 0, 1]) passes the assertion. assert_count_equal([0, 0, 1], [0, 1]) raises an assertion error. ``` -------------------------------- ### Install Mobly from source Source: https://github.com/google/mobly/blob/master/README.md Install Mobly from its source code to use the latest development version. This requires cloning the repository and installing it in editable mode. ```sh git clone https://github.com/google/mobly.git cd mobly pip install -e . ``` -------------------------------- ### Attenuator Configuration Example Source: https://github.com/google/mobly/blob/master/docs/mobly.controllers.md Sample configuration for setting up attenuator devices in Mobly. This includes network address, port, model, and the paths available on each device. ```python "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"] } ] ``` -------------------------------- ### IPerfServer Class Source: https://github.com/google/mobly/blob/master/docs/mobly.controllers.md Handles iperf3 operations, allowing for starting and stopping iperf servers. ```APIDOC ## Class IPerfServer ### Description Class that handles iperf3 operations. ### Methods #### start(extra_args='', tag='') Starts iperf server on specified port. - **Parameters:** - **extra_args** (str) - A string representing extra arguments to start iperf server with. - **tag** (str) - Appended to log file name to identify logs from different iperf runs. #### stop() Stops the iperf server. ``` -------------------------------- ### Install pyink for Code Linting Source: https://github.com/google/mobly/blob/master/CONTRIBUTING.md Install the pyink package, a code formatter used for linting code style in the Mobly project. Specify the version for consistency. ```sh $ pip3 install pyink==24.3.0 ``` -------------------------------- ### Load a Snippet Client Source: https://github.com/google/mobly/blob/master/docs/mobly.controllers.md Starts a snippet APK with the given package name and connects to it. The snippet client is then attached to the device object under the specified name. ```python ad.load_snippet( name='maps', package='com.google.maps.snippets') ad.maps.activateZoom('3') ``` -------------------------------- ### Create AndroidDevice Instances from Configurations Source: https://github.com/google/mobly/blob/master/docs/mobly.controllers.md Instantiate AndroidDevice objects using a list of dictionaries, where each dictionary contains configuration details including the 'serial' key. This is useful for more complex setups. ```python android_devices = mobly.controllers.android_device.get_instances_with_configs(configs=[ {"serial": "192.168.1.10:5555"}, {"serial": "192.168.1.11:5555"}, ]) ``` -------------------------------- ### Install Mobly using pip Source: https://github.com/google/mobly/blob/master/README.md Install the released Mobly package using pip. Ensure you have Python 3.11 or newer. ```sh pip install mobly ``` -------------------------------- ### JSON RPC Protocol Request Example Source: https://github.com/google/mobly/blob/master/docs/mobly.controllers.android_device_lib.md Illustrates the structure of a JSON RPC request, including ID, method name, and parameters. This is the format expected by JsonRpcClientBase. ```json { "id": "method": "params": } ``` -------------------------------- ### Install tox for Mobly Unit Tests Source: https://github.com/google/mobly/blob/master/CONTRIBUTING.md Install the tox package, which is required to run Mobly's unit tests. Ensure you are using pip3. ```sh pip3 install tox ``` -------------------------------- ### Run iPerf Client Source: https://github.com/google/mobly/blob/master/docs/mobly.controllers.md Starts an iPerf client on the Android device to measure network performance. Requires the server host address and optional extra arguments for the iPerf command. ```python ad.run_iperf_client(server_host='192.168.1.100', extra_args='-i 1 -t 30') ``` -------------------------------- ### Pre-run Processing Source: https://github.com/google/mobly/blob/master/docs/mobly.md The pre_run method handles preprocessing tasks before the class setup. It's the designated place for generating tests. ```APIDOC ## pre_run() ### Description Preprocesses that need to be done before setup_class. This phase is used to do pre-test processes like generating tests. This is the only place self.generate_tests should be called. If this function throws an error, the test class will be marked failure and the “Requested” field will be 0 because the number of tests requested is unknown at this point. ### Method N/A (Lifecycle method) ### Endpoint N/A (Internal framework method) ``` -------------------------------- ### Create a Custom Test Suite with base_suite.BaseSuite Source: https://github.com/google/mobly/blob/master/docs/mobly.md Subclass BaseSuite to define custom suite-level setup, teardown, and configuration for test classes. Use add_test_class to register individual tests, optionally with specific test selections, custom configurations, or name suffixes. ```python from mobly import base_suite from mobly import suite_runner from my.path import MyFooTest from my.path import MyBarTest class MySuite(base_suite.BaseSuite): def setup_suite(self, config): # Add a class with default config. self.add_test_class(MyFooTest) # Add a class with test selection. self.add_test_class(MyBarTest, tests=['test_a', 'test_b']) # Add the same class again with a custom config and suffix. my_config = some_config_logic(config) self.add_test_class(MyBarTest, config=my_config, name_suffix='WithCustomConfig') if __name__ == '__main__': suite_runner.run_suite_class() ``` -------------------------------- ### Implement a Custom Mobly Android Service Source: https://github.com/google/mobly/blob/master/docs/android_device_service.md Define a custom service by inheriting from `base_service.BaseService`. This example shows how to create a dummy service with configuration and lifecycle methods. ```python class Configs: def __init__(self, secret=None): self.secret = secret class MyService(base_service.BaseService): """Dummy service demonstrating the service interface.""" def __init__(self, device, configs=None): self._device = device self._configs = configs self._is_alive = False def get_my_secret(self): return self._configs.secret @property def is_alive(self): """Override base class.""" return self._is_alive def start(self): """Override base class.""" self._is_alive = True def stop(self): """Override base class.""" self._is_alive = False ``` -------------------------------- ### JSON RPC Protocol Response Example Source: https://github.com/google/mobly/blob/master/docs/mobly.controllers.android_device_lib.md Illustrates the structure of a JSON RPC response, including ID, result, error, and callback information. This is the format returned by JsonRpcClientBase. ```json { "id": , "result": , "error": "callback": } ``` -------------------------------- ### Run a Collection of Test Classes with suite_runner.run_suite Source: https://github.com/google/mobly/blob/master/docs/mobly.md Use this method when you need to execute a list of test classes without custom setup or teardown. Ensure all necessary test libraries are imported. ```python from mobly import suite_runner from my.test.lib import foo_test from my.test.lib import bar_test ... if __name__ == '__main__': suite_runner.run_suite([foo_test.FooTest, bar_test.BarTest]) ``` -------------------------------- ### Get Multiple Android Devices Source: https://github.com/google/mobly/blob/master/docs/mobly.controllers.md Use get_devices to find a list of AndroidDevice instances from a list that match specific attribute values. Raises an error if no devices are matched. ```python get_devices(android_devices, label=’foo’, phone_number=’1234567890’) ``` ```python get_devices(android_devices, model=’angler’) ``` -------------------------------- ### Configuration File for Smart Light Source: https://github.com/google/mobly/blob/master/docs/tutorial_custom_controller.md YAML configuration defining a test bed and registering the 'SmartLight' controller with device-specific name and IP address. ```yaml TestBeds: - Name: BedroomTestBed Controllers: SmartLight: - name: "BedLight" ip: "192.168.1.50" ``` -------------------------------- ### Creating Custom Test Suites with `base_suite.BaseSuite` Source: https://github.com/google/mobly/blob/master/docs/mobly.md Illustrates how to create a custom test suite by subclassing `base_suite.BaseSuite` and using `suite_runner.run_suite_class()`. ```APIDOC ## Creating Custom Test Suites with `base_suite.BaseSuite` ### Description Users can define custom test suites by inheriting from `base_suite.BaseSuite`. This allows for suite-level setup and teardown, as well as custom configurations for individual test classes using `add_test_class()`. ### Method `suite_runner.run_suite_class()` ### Parameters This method does not take direct parameters but relies on the configuration within the `BaseSuite` subclass. ### Request Example ```python from mobly import base_suite from mobly import suite_runner from my.path import MyFooTest from my.path import MyBarTest class MySuite(base_suite.BaseSuite): def setup_suite(self, config): # Add a class with default config. self.add_test_class(MyFooTest) # Add a class with test selection. self.add_test_class(MyBarTest, tests=['test_a', 'test_b']) # Add the same class again with a custom config and suffix. my_config = some_config_logic(config) self.add_test_class(MyBarTest, config=my_config, name_suffix='WithCustomConfig') if __name__ == '__main__': suite_runner.run_suite_class() ``` ### Response This function executes the test suite defined by the `BaseSuite` subclass and generates reports. ``` -------------------------------- ### mobly.utils.get_settable_properties Source: https://github.com/google/mobly/blob/master/docs/mobly.md Gets the explicitly defined properties with setters for a given class. ```APIDOC ## mobly.utils.get_settable_properties ### Description Gets the settable properties of a class. Only returns the explicitly defined properties with setters. ### Method N/A (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **cls** (class) - A class in Python. ### Returns A list of settable properties. ``` -------------------------------- ### Running Test Suites with `suite_runner.run_suite()` Source: https://github.com/google/mobly/blob/master/docs/mobly.md Demonstrates how to use `suite_runner.run_suite()` to execute a list of individual test classes. ```APIDOC ## Running Test Suites with `suite_runner.run_suite()` ### Description This method allows users to run a collection of Mobly test classes directly by providing a list of test class objects. ### Method `suite_runner.run_suite(test_classes, **kwargs)` ### Parameters * **test_classes** (list) - A list of one or more individual test class objects (e.g., `[FooTest, BarTest]`). * **kwargs** - Additional keyword arguments that can be passed to the test runner. ### Request Example ```python from mobly import suite_runner from my.test.lib import foo_test from my.test.lib import bar_test if __name__ == '__main__': suite_runner.run_suite([foo_test.FooTest, bar_test.BarTest]) ``` ### Response This function does not return a value directly but executes the tests and generates reports. ``` -------------------------------- ### create Source: https://github.com/google/mobly/blob/master/docs/mobly.controllers.md Creates AndroidDevice controller objects based on provided configurations. ```APIDOC ## mobly.controllers.android_device.create(configs) ### Description Creates AndroidDevice controller objects. ### Parameters - **configs** (str or list) - 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. ``` -------------------------------- ### Fastboot Utility Function Source: https://github.com/google/mobly/blob/master/docs/mobly.md Executes a Fastboot command. ```APIDOC ## exe_cmd() ### Description Executes a Fastboot command on the device. ### Method POST ### Endpoint Not applicable (function call) ### Parameters - **cmd** (str) - Required - The Fastboot command to execute. - **timeout** (float) - Optional - The timeout for the command in seconds. ### Request Example ```python from mobly.controllers.android_device_lib.fastboot import exe_cmd try: result = exe_cmd('reboot') print("Fastboot command executed successfully.") except Exception as e: print(f"Error executing Fastboot command: {e}") ``` ### Response #### Success Response (200) - **str**: The output of the Fastboot command. #### Response Example ```json { "example": "Reboot successful." } ``` -------------------------------- ### mobly.utils.get_available_host_port Source: https://github.com/google/mobly/blob/master/docs/mobly.md Gets an available host port number for adb forward. DEPRECATED: Use tcp:0 with adb forward instead. ```APIDOC ## mobly.utils.get_available_host_port ### Description Gets a host port number available for adb forward. DEPRECATED: This method is unreliable. Pass tcp:0 to adb forward instead. ### Method N/A (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Returns An integer representing a port number on the host available for adb forward. ### Raises * **Error** - When no port is found after MAX_PORT_ALLOCATION_RETRY times. ``` -------------------------------- ### mobly.utils.stop_standing_subprocess Source: https://github.com/google/mobly/blob/master/docs/mobly.md Terminates a subprocess previously started with start_standing_subprocess. It checks if the process is running before attempting termination and handles potential errors. ```APIDOC ## mobly.utils.stop_standing_subprocess ### Description Stops a subprocess started by start_standing_subprocess. Before killing the process, we check if the process is running, if it has terminated, Error is raised. Catches and ignores the PermissionError which only happens on Macs. ### Parameters #### Parameters - **proc** (subprocess object) - Required - Subprocess to terminate. ### Raises [**Error**](#mobly.utils.Error) – if the subprocess could not be stopped. ``` -------------------------------- ### Get Attenuation Setting Source: https://github.com/google/mobly/blob/master/docs/mobly.controllers.md Retrieves the current attenuation level in dB for an AttenuatorPath object. This is useful for monitoring or verifying the current state. ```python current_atten = self.attenuation_paths[0].get_atten() ``` -------------------------------- ### SnippetManagementService API Source: https://github.com/google/mobly/blob/master/docs/mobly.md Provides methods for managing snippets on Android devices, including starting, stopping, pausing, resuming, and client management. ```APIDOC ## SnippetManagementService API ### Description Provides methods for managing snippets on Android devices, including starting, stopping, pausing, resuming, and client management. ### Methods - **add_snippet_client()**: Adds a snippet client. - **get_snippet_client()**: Retrieves a snippet client. - **is_alive**: Checks if the snippet service is alive. - **pause()**: Pauses the snippet service. - **remove_snippet_client()**: Removes a snippet client. - **resume()**: Resumes the snippet service. - **start()**: Starts the snippet service. - **stop()**: Stops the snippet service. ### Error Handling - **Error**: Represents an error in the snippet management service. - **SERVICE_TYPE**: The type of the service. ``` -------------------------------- ### Smart Light Controller Module Source: https://github.com/google/mobly/blob/master/docs/tutorial_custom_controller.md Implements a custom controller for a Smart Light device with type hinting and fault-tolerant cleanup. Requires 'name' and 'ip' in configuration. ```python """Mobly controller module for a Smart Light.""" import logging from typing import Any, Dict, List # The key used in the config file to identify this controller. MOBLY_CONTROLLER_CONFIG_NAME = "SmartLight" class SmartLight: """A class representing a smart light device.
Attributes: : name: the name of the device. ip: the IP address of the device. is_on: True if the light is currently on, False otherwise.
"""
def __init__(self, name: str, ip: str): self.name = name self.ip = ip self.is_on = False logging.info("Initialized SmartLight [%s] at %s", self.name, self.ip)
def power_on(self): """Turns the light on.""" self.is_on = True logging.info("SmartLight [%s] turned ON", self.name)
def power_off(self): """Turns the light off.""" self.is_on = False logging.info("SmartLight [%s] turned OFF", self.name)
def close(self): """Simulates closing the connection.""" logging.info("SmartLight [%s] connection closed", self.name) def create(configs: List[Dict[str, Any]]) -> List[SmartLight]: """Creates SmartLight instances from a list of configurations.
Args: : configs: A list of dicts, where each dict represents a configuration for a SmartLight device.
Returns: : A list of SmartLight objects.
Raises: : ValueError: If a required configuration parameter is missing.
""" devices = [] for config in configs:
if "name" not in config or "ip" not in config: raise ValueError( f"Invalid config: {config}. ‘name’ and ‘ip’ are required." )
devices.append(SmartLight( name=config["name"], ip=config["ip"] ))
return devices def destroy(objects: List[SmartLight]) -> None: """Cleans up SmartLight instances.
Args: : objects: A list of SmartLight objects to be destroyed.
""" for light in objects:
try: if light.is_on: light.power_off()
light.close()
except Exception: # Catching broad exceptions ensures that a failure in one device # does not prevent others from being cleaned up. logging.exception("Failed to clean up SmartLight [%s]", light.name) def get_info(objects: List[SmartLight]) -> List[Dict[str, Any]]: """Returns information for the test result.
Args: : objects: A list of SmartLight objects.
Returns: : A list of dicts containing device information.
""" return [{ "name": light.name, "ip": light.ip } for light in objects] ``` -------------------------------- ### Get Maximum Attenuation Source: https://github.com/google/mobly/blob/master/docs/mobly.controllers.md Fetches the maximum attenuation value in dB supported by the AttenuatorPath. This helps in understanding the operational limits of the device path. ```python max_atten = self.attenuation_paths[0].get_max_atten() ``` -------------------------------- ### Basic Mobly 'Hello World' Test Source: https://github.com/google/mobly/blob/master/docs/tutorial.md A Python script demonstrating a Mobly test case that loads the Mobly Bundled Snippets (MBS) and displays 'Hello World!' on an Android device's screen. ```python from mobly import base_test from mobly import test_runner from mobly.controllers import android_device class HelloWorldTest(base_test.BaseTestClass): def setup_class(self): # Registering android_device controller module declares the test's # dependency on Android device hardware. By default, we expect at least one # object is created from this. self.ads = self.register_controller(android_device) self.dut = self.ads[0] # Start Mobly Bundled Snippets (MBS). self.dut.load_snippet('mbs', android_device.MBS_PACKAGE) def test_hello(self): self.dut.mbs.makeToast('Hello World!') if __name__ == '__main__': test_runner.main() ``` -------------------------------- ### Get Log Line Timestamp Source: https://github.com/google/mobly/blob/master/docs/mobly.md Returns a timestamp formatted for individual log lines. Defaults to the current time, but can be offset by a specified number of seconds. ```python mobly.logger.get_log_line_timestamp(delta=None) ``` -------------------------------- ### mobly.logger.setup_test_logger Source: https://github.com/google/mobly/blob/master/docs/mobly.md Customizes the root logger for a test run, configuring Mobly logging handlers and setting output directory attributes. ```APIDOC ## mobly.logger.setup_test_logger ### Description Customizes the root logger for a test run. In addition to configuring the Mobly logging handlers, this also sets two attributes on the logging module for the output directories: `root_output_path` and `log_path`. ### Parameters #### Path Parameters - **log_path** (string) - Required - The location of the report file. - **prefix** (string) - Optional - A prefix for each log line in the terminal. - **alias** (string) - Optional - The name of the alias to use for the latest log directory. If a falsy value is provided, then the alias directory will not be created. - **console_level** (logging level) - Optional - Log level threshold used for log messages printed to the console. Logs with a level less severe than `console_level` will not be printed to the console. ``` -------------------------------- ### Get Log File Timestamp Source: https://github.com/google/mobly/blob/master/docs/mobly.md Returns a timestamp formatted for log file names. Defaults to the current time, but can be offset by a specified number of seconds. ```python mobly.logger.get_log_file_timestamp(delta=None) ``` -------------------------------- ### Get All Events by Name Source: https://github.com/google/mobly/blob/master/docs/mobly.controllers.android_device_lib.md Retrieves all events associated with a specific name for a given callback ID. This is a non-blocking call and returns a list of SnippetEvent objects. ```python handler.getAll(event_name) ``` -------------------------------- ### Mobly Logger Context Manager Source: https://github.com/google/mobly/blob/master/docs/mobly.md Starts and stops a logging context for a Mobly test run. Yields the host file path where logs are stored. ```python from mobly import test_runner # Assuming runner is an instance of TestRunner with runner.mobly_logger(alias='my_log', console_level=20) as log_path: print(f'Logs are being written to: {log_path}') # Run tests or perform other actions within this context ``` -------------------------------- ### FastbootProxy Methods Source: https://github.com/google/mobly/blob/master/docs/mobly.md Provides methods for interacting with Fastboot on Android devices. ```APIDOC ## FastbootProxy.args() ### Description Returns the arguments used to initialize the FastbootProxy. ### Method GET ### Endpoint Not specified ### Parameters None explicitly mentioned. ### Request Example ```json { "example": "No request body example available" } ``` ### Response #### Success Response (200) - **list[str]**: A list of arguments. #### Response Example ```json { "example": "['--port', '5037']" } ``` ```APIDOC ## FastbootProxy.fastboot_str() ### Description Returns a string representation of the Fastboot command and its arguments. ### Method GET ### Endpoint Not specified ### Parameters None explicitly mentioned. ### Request Example ```json { "example": "No request body example available" } ``` ### Response #### Success Response (200) - **str**: The string representation of the Fastboot command. #### Response Example ```json { "example": "fastboot --port 5037" } ``` -------------------------------- ### Mobly 'Hello World' Test Script Source: https://github.com/google/mobly/wiki/Getting-Started-with-Mobly A basic Mobly test script that loads the Android device controller and displays a 'Hello World!' toast message on the device. ```python from mobly import base_test from mobly import test_runner from mobly.controllers import android_device class HelloWorldTest(base_test.BaseTestClass): def setup_class(self): # Registering android_device controller module declares the test's # dependency on Android device hardware. By default, we expect at least one # object is created from this. self.ads = self.register_controller(android_device) self.dut = self.ads[0] self.dut.load_sl4a() # starts sl4a. def test_hello(self): self.dut.sl4a.makeToast('Hello World!') if __name__ == "__main__": test_runner.main() ``` -------------------------------- ### Specify Android Devices in Mobly Config Source: https://github.com/google/mobly/wiki/Getting-Started-with-Mobly An example of how to specify individual Android devices by serial number and attach custom attributes within the Mobly configuration. ```json "AndroidDevice": [ {"serial": "xyz", "phone_number": "123456"}, {"serial": "abc", "label": "golden_device"}, ] ``` -------------------------------- ### Configure Multiple Test Beds in JSON Source: https://github.com/google/mobly/wiki/Getting-Started-with-Mobly Define multiple test bed configurations within a single JSON file. Each test bed can specify its own set of devices and properties. ```json { "testbed":[ { "name" : "XyzTestBed", "AndroidDevice" : [{"serial": "xyz", "phone_number": "123456"}] }, { "name" : "AbcTestBed", "AndroidDevice" : [{"serial": "abc", "label": "golden_device"}] } ], "logpath" : "/tmp/logs", "favorite_food": "green eggs and ham" } ``` -------------------------------- ### Execute Generic Command in Shell Source: https://github.com/google/mobly/blob/master/docs/mobly.controllers.android_device_lib.md Executes a sequence of commands in a new shell with a specified timeout. stderr is piped, and the output is returned in bytes. Use for commands not directly supported by FastbootProxy or when needing raw command output. ```python mobly.controllers.android_device_lib.fastboot.exe_cmd("fastboot", "devices", timeout=180) ``` -------------------------------- ### Select Test Bed via Command Line Source: https://github.com/google/mobly/wiki/Getting-Started-with-Mobly Use the `--test_bed` command-line argument to specify which test bed configuration to use when running your Mobly test script. ```bash python hello_world_test.py -c sample_config.json --test_bed AbcTestBed ``` -------------------------------- ### Initialize AndroidDeviceLoggerAdapter Source: https://github.com/google/mobly/blob/master/docs/mobly.controllers.md Use AndroidDeviceLoggerAdapter to add a prefix to each log line. The prefix includes '[AndroidDevice|]'. ```python my_log = AndroidDeviceLoggerAdapter(logging.getLogger(), { 'tag': }) ``` -------------------------------- ### BaseService API Source: https://github.com/google/mobly/blob/master/docs/mobly.controllers.android_device_lib.md Provides core functionalities for managing Android device services, including starting, stopping, pausing, and resuming services, as well as checking their alive status. ```APIDOC ## Class: BaseService ### Description Represents a base service for Android devices, offering common control methods. ### Methods - **alias**: Property to get or set an alias for the service. - **create_output_excerpts()**: Creates excerpts from the service's output. - **is_alive**: Boolean property indicating if the service is currently running. - **pause()**: Pauses the service. - **resume()**: Resumes the service. - **start()**: Starts the service. - **stop()**: Stops the service. ``` -------------------------------- ### Execute Fastboot Command Source: https://github.com/google/mobly/blob/master/docs/mobly.controllers.android_device_lib.md Executes a fastboot command directly using the FastbootProxy. The '-' in commands is replaced with '_'. Useful for interacting with devices in fastboot mode. ```python fb = FastbootProxy(serial=ad.serial) fb.devices() ``` -------------------------------- ### Configuration Parsing Source: https://github.com/google/mobly/blob/master/docs/mobly.md Utilities for loading and parsing test configuration files. ```APIDOC ## mobly.config_parser.load_test_config_file(test_config_path, tb_filters=None) ### Description Processes the test configuration file provided by user. Loads the configuration file into a dict, unpacks each testbed config into its own dict, and validates the configuration in the process. ### Parameters * **test_config_path** (string) - Required - Path to the test configuration file. * **tb_filters** (list) - Optional - A subset of test bed names to be pulled from the config file. If None, then all test beds will be selected. ### Returns A list of test configuration dicts to be passed to test_runner.TestRunner. ``` -------------------------------- ### Main Test Execution Entry Points Source: https://github.com/google/mobly/blob/master/docs/mobly.md Default entry points for executing test scripts directly. ```APIDOC ## mobly.test_runner.main(argv=None) ### Description Execute the test class in a test module. This is the default entry point for running a test script file directly. In this case, only one test class in a test script is allowed. To make your test script executable, add the following to your file: ```python from mobly import test_runner ... if __name__ == '__main__': test_runner.main() ``` If you want to implement your own cli entry point, you could use function execute_one_test_class(test_class, test_config, test_identifier) ### Parameters * **argv** (List[str], optional) - A list that is then parsed as cli args. If None, defaults to cli input. ``` -------------------------------- ### Device Control and Utility Methods Source: https://github.com/google/mobly/blob/master/docs/mobly.controllers.md Methods for controlling the device state and performing utility operations. ```APIDOC ## POST /reboot ### Description Reboots the device. This method gracefully handles the teardown and restoration of running services and is blocking until the reboot is complete. ### Method POST ### Endpoint /reboot ### Response #### Success Response (200) - **status** (boolean) - Indicates if the reboot was successful. #### Response Example ```json { "status": true } ``` ## POST /root_adb ### Description Changes adb to root mode for this device if allowed. Note: This will not work on production builds due to security restrictions. ### Method POST ### Endpoint /root_adb ### Response #### Success Response (200) - **status** (boolean) - Indicates if adb was successfully switched to root mode. #### Response Example ```json { "status": true } ``` ## POST /run_iperf_client ### Description Starts the iperf client on the device. ### Method POST ### Endpoint /run_iperf_client ### Parameters #### Query Parameters - **server_host** (string) - Required - Address of the iperf server. - **extra_args** (string) - Optional - Extra arguments for iperf client, e.g. ‘-i 1 -t 30’. ### Response #### Success Response (200) - **status** (boolean) - True if iperf client started successfully. - **results** (object) - Data flow information. #### Response Example ```json { "status": true, "results": { "data_flow": "..." } } ``` ## POST /take_bug_report ### Description Takes a bug report on the device and stores it in a file. ### Method POST ### Endpoint /take_bug_report ### Parameters #### Query Parameters - **test_name** (string) - Optional - Name of the test method that triggered this bug report. - **begin_time** (timestamp) - Optional - Timestamp of when the test started. - **timeout** (float) - Optional - The number of seconds to wait for bugreport to complete, default is 5min. - **destination** (string) - Optional - Path to the directory where the bugreport should be saved. ### Response #### Success Response (200) - **file_path** (string) - The absolute path to the bug report on the host. #### Response Example ```json { "file_path": "/path/to/bugreport.zip" } ``` ## POST /take_screenshot ### Description Takes a screenshot of the device. ### Method POST ### Endpoint /take_screenshot ### Parameters #### Query Parameters - **destination** (string) - Required - Full path to the directory to save in. - **prefix** (string) - Optional - Prefix file name of the screenshot, default is 'screenshot'. - **all_displays** (boolean) - Optional - If true, takes a screenshot on all connected displays; otherwise, takes a screenshot on the default display. ### Response #### Success Response (200) - **file_path** (string or list[string]) - Full path to the screenshot file on the host, or a list of paths if all_displays is True. #### Response Example ```json { "file_path": "/path/to/screenshot.png" } ``` ## POST /update_serial ### Description Updates the serial number of a device. This is intended for cases where the device's identifier changes during a test, such as after a reboot. ### Method POST ### Endpoint /update_serial ### Parameters #### Query Parameters - **new_serial** (string) - Required - The new serial number for the same device. ### Response #### Success Response (200) - **status** (boolean) - Indicates if the serial number was updated successfully. #### Response Example ```json { "status": true } ``` ## POST /wait_for_boot_completion ### Description Waits for Android framework to broadcast ACTION_BOOT_COMPLETED. ### Method POST ### Endpoint /wait_for_boot_completion ### Parameters #### Query Parameters - **timeout** (float) - Optional - The number of seconds to wait before timing out. If not specified, no timeout takes effect. ### Response #### Success Response (200) - **status** (boolean) - Indicates if the boot completion was detected within the timeout. #### Response Example ```json { "status": true } ``` ``` -------------------------------- ### TelnetScpiClient Methods Source: https://github.com/google/mobly/blob/master/docs/mobly.controllers.md Methods for interacting with devices using Telnet and SCPI commands. ```APIDOC ## TelnetScpiClient Methods ### Description Provides a client for sending SCPI commands over Telnet to devices. ### Methods - `close()`: Closes the Telnet connection. - `cmd()`: Sends a command to the device and returns the response. ``` -------------------------------- ### Get a Unique Android Device Source: https://github.com/google/mobly/blob/master/docs/mobly.controllers.md Use get_device to find a unique AndroidDevice instance from a list based on specific attribute values. Raises an error if zero or more than one device is matched. ```python get_device(android_devices, label=’foo’, phone_number=’1234567890’) ``` ```python get_device(android_devices, model=’angler’) ``` -------------------------------- ### Fastboot Operations Source: https://github.com/google/mobly/blob/master/docs/mobly.controllers.android_device_lib.md Provides methods for interacting with devices in fastboot mode. ```APIDOC ## Class: mobly.controllers.android_device_lib.fastboot.FastbootProxy ### Description Proxy class for executing fastboot commands. Note: The '-' in fastboot commands need to be replaced with '_'. Commands can be directly executed on an instance of this class. ### Example ```python fb = FastbootProxy('some_serial') output = fb.devices() ``` #### Method: args(*args, timeout=180) Executes a fastboot command with arguments. ### Parameters - **\*args** - Sequence of command and arguments. - **timeout** (int) - The number of seconds to wait before timing out. Defaults to 180. #### Method: fastboot_str() Returns a string representation of the fastboot command. ``` ```APIDOC ## Function: mobly.controllers.android_device_lib.fastboot.exe_cmd(*cmds, timeout=180) ### Description Executes commands in a new shell, directing stderr to PIPE, with a timeout. This method is specific to fastboot due to its handling of non-error information on stderr. ### Parameters - **\*cmds** - A sequence of commands and arguments. - **timeout** (int) - The number of seconds to wait before timing out. Defaults to 180. ### Returns - **bytes** - The output of the command run. ### Raises - **Exception** - An error occurred during the command execution or the command timed out. ``` -------------------------------- ### Take Bug Report Source: https://github.com/google/mobly/blob/master/docs/mobly.controllers.md Captures a bug report from the Android device and saves it to a specified file path. Optional parameters include test name, start time, and timeout duration. ```python ad.take_bug_report(test_name='MyTest', destination='/tmp/bugreports/') ``` -------------------------------- ### Get Controller Info Records Source: https://github.com/google/mobly/blob/master/docs/mobly.md The `get_controller_info_records` method within `ControllerManager` retrieves the latest info records for all controller objects managed by the instance. New records are generated on each call to ensure up-to-date information. ```python controller_manager.get_controller_info_records() ``` -------------------------------- ### ADB Controller Source: https://github.com/google/mobly/blob/master/docs/mobly.controllers.md Provides functionalities for interacting with Android devices via ADB. ```APIDOC ## ADB Controller API ### Description APIs for controlling Android devices using ADB. ### Classes - **AdbProxy** - Description: A proxy class for ADB operations. - Methods: - **connect()**: Connects to an ADB device. - **current_user_id**: Gets the current user ID. - **forward()**: Forwards a port. - **getprop()**: Gets a system property. - **getprops()**: Gets multiple system properties. - **has_shell_command()**: Checks if a shell command exists. - **instrument()**: Runs an instrumentation. - **reverse()**: Reverses a port. - **root()**: Roots the device. - **AdbError** - Description: Represents an error during ADB operations. - Attributes: - **cmd**: The command that failed. - **stdout**: Standard output of the command. - **stderr**: Standard error of the command. - **ret_code**: The return code of the command. - **serial**: The serial number of the device. - **AdbTimeoutError** - Description: Represents a timeout error during ADB operations. ``` -------------------------------- ### Handle USB Disconnect with Context Manager Source: https://github.com/google/mobly/blob/master/docs/mobly.controllers.md Use this context manager to properly handle service lifecycle during USB disconnections. Ensure the device is reconnected before exiting the context. ```python 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) ``` -------------------------------- ### get_info Source: https://github.com/google/mobly/blob/master/docs/mobly.controllers.md Retrieves information on a list of AndroidDevice objects. ```APIDOC ## mobly.controllers.android_device.get_info(ads) ### Description Get information on a list of AndroidDevice objects. ### Parameters - **ads** (list) - 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 Python Test for Bluetooth Discovery Source: https://github.com/google/mobly/wiki/Getting-Started-with-Mobly This Python test class uses Mobly to set up two Android devices, enable Bluetooth, and test device discovery. It includes setup for controllers, loading SL4A, and handling Bluetooth-related events and states. ```python from mobly import base_test from mobly import test_runner from mobly.controllers import android_device class HelloWorldTest(base_test.BaseTestClass): def setup_class(self): # Registering android_device controller module, and declaring that the test # requires at least two Android devices. self.ads = self.register_controller(android_device, min_number=2) self.dut = android_device.get_device(self.ads, label="dut") self.dut.load_sl4a() self.discoverer = android_device.get_device(self.ads, label="discoverer") self.discoverer.load_sl4a() self.dut.ed.clear_all_events() self.discoverer.ed.clear_all_events() def setup_test(self): # Make sure bluetooth is on self.dut.sl4a.bluetoothToggleState(True) self.discoverer.sl4a.bluetoothToggleState(True) self.dut.ed.pop_event(event_name='BluetoothStateChangedOn', timeout=10) self.discoverer.ed.pop_event(event_name='BluetoothStateChangedOn', timeout=10) if (not self.dut.sl4a.bluetoothCheckState() or not self.discoverer.sl4a.bluetoothCheckState()): asserts.abort_class('Could not turn on Bluetooth on both devices.') # Set the name of device #1 and verify the name properly registered. self.dut.sl4a.bluetoothSetLocalName(self.bluetooth_name) asserts.assert_equal(self.dut.sl4a.bluetoothGetLocalName(), self.bluetooth_name, 'Failed to set bluetooth name to %s on %s' % (self.bluetooth_name, self.dut.serial)) def test_bluetooth_discovery(self): # Make dut discoverable. self.dut.sl4a.bluetoothMakeDiscoverable() scan_mode = self.dut.sl4a.bluetoothGetScanMode() asserts.assert_equal( scan_mode, 3, # 3 signifies CONNECTABLE and DISCOVERABLE 'Android device %s failed to make blueooth discoverable.' % self.dut.serial) # Start the discovery process on #discoverer. self.discoverer.ed.clear_all_events() self.discoverer.sl4a.bluetoothStartDiscovery() self.discoverer.ed.pop_event( event_name='BluetoothDiscoveryFinished', timeout=self.bluetooth_timeout) # The following log entry demonstrates AndroidDevice log object, which # prefixes log entries with "[AndroidDevice|] " self.discoverer.log.info('Discovering other bluetooth devices.') # Get a list of discovered devices discovered_devices = self.discoverer.sl4a.bluetoothGetDiscoveredDevices() self.discoverer.log.info('Found devices: %s', discovered_devices) matching_devices = [d for d in discovered_devices if d.get('name') == self.bluetooth_name] if not matching_devices: asserts.fail('Android device %s did not discover %s.' % (self.discoverer.serial, self.dut.serial)) self.discoverer.log.info('Discovered at least 1 device named ' '%s: %s', self.bluetooth_name, matching_devices) if __name__ == "__main__": test_runner.main() ``` -------------------------------- ### Command Line Execution of Mobly Test Cases in Order Source: https://github.com/google/mobly/blob/master/docs/tutorial.md This command shows how to execute multiple test cases from a Mobly script in a specified order: 'test_bye', 'test_hello', and 'test_bye' again. ```bash $ python hello_world_test.py -c sample_config.yml --test_case test_bye test_hello test_bye ``` -------------------------------- ### AdbProxy Methods Source: https://github.com/google/mobly/blob/master/docs/mobly.md Provides methods for interacting with ADB on Android devices. ```APIDOC ## AdbProxy.reverse() ### Description Sets up or removes a reverse TCP connection. ### Method Not specified (likely POST or PUT based on context) ### Endpoint Not specified ### Parameters None explicitly mentioned in the provided text. ### Request Example ```json { "example": "No request body example available" } ``` ### Response #### Success Response (200) Details not provided. #### Response Example ```json { "example": "No response example available" } ``` ```APIDOC ## AdbProxy.root() ### Description Restarts the ADB daemon with root privileges. ### Method Not specified (likely POST or PUT based on context) ### Endpoint Not specified ### Parameters None explicitly mentioned in the provided text. ### Request Example ```json { "example": "No request body example available" } ``` ### Response #### Success Response (200) Details not provided. #### Response Example ```json { "example": "No response example available" } ``` -------------------------------- ### TelnetScpiClient Methods Source: https://github.com/google/mobly/blob/master/docs/mobly.md Methods for interacting with devices via Telnet SCPI client. ```APIDOC ## TelnetScpiClient Methods ### Description Provides methods to manage a Telnet connection for sending SCPI commands. ### Methods - **close()**: Closes the Telnet connection. - **cmd(command)**: Sends a command to the device and returns the response. - **is_open**: Property to check if the connection is open. - **open()**: Opens the Telnet connection. ### Endpoint N/A (These are methods within the TelnetScpiClient class) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Assuming 'client' is an instance of TelnetScpiClient # client.open() # response = client.cmd("*IDN?") # client.close() ``` ### Response #### Success Response (200) - **cmd()**: Returns the string response from the device. - **is_open**: Returns a boolean indicating connection status. #### Response Example ```json { "response": "Example Device Response" } ``` ``` -------------------------------- ### YAML Configuration for Test Bed Source: https://github.com/google/mobly/blob/master/docs/instrumentation_tutorial.md This YAML configuration defines a test bed named 'TwoDeviceTestBed' with two Android devices, each labeled as 'dut'. ```yaml TestBeds: - Name: TwoDeviceTestBed Controllers: AndroidDevice: - serial: xyz label: dut - serial: abc label: dut ``` -------------------------------- ### Run Mobly Test with Specific Test Bed Source: https://github.com/google/mobly/blob/master/docs/tutorial.md Execute a Mobly test using a specified test bed configuration from the command line. ```bash $ python hello_world_test.py -c sample_config.yml --test_bed AbcTestBed ``` -------------------------------- ### get_all_instances Source: https://github.com/google/mobly/blob/master/docs/mobly.controllers.md Retrieves all attached Android devices as AndroidDevice instances. ```APIDOC ## mobly.controllers.android_device.get_all_instances(include_fastboot=False) ### Description Create AndroidDevice instances for all attached android devices. ### Parameters - **include_fastboot** (bool, optional) - Whether to include devices in bootloader mode or not. Defaults to False. ### Returns A list of AndroidDevice objects each representing an android device attached to the computer. ``` -------------------------------- ### Register a Service with AndroidDevice Source: https://github.com/google/mobly/blob/master/docs/android_device_service.md Register a custom service with the `ServiceManager` using an `AndroidDevice` instance. Provide the service name, class, and configuration object. ```python ad.services.register('secret_service', my_service.MyService, my_service.Configs(secret=42)) ``` -------------------------------- ### Command Line Execution of Mobly Test Source: https://github.com/google/mobly/blob/master/docs/tutorial.md This command shows how to execute a Mobly Python test script, specifying the configuration file to use. ```bash $ python hello_world_test.py -c sample_config.yml ```