mobly.utils module

exception mobly.utils.Error[source]

Bases: Exception

Raised when an error occurs in a util

mobly.utils.abs_path(path)[source]

Resolve the ‘.’ and ‘~’ in a path to get the absolute path.

Parameters:

path – The path to expand.

Returns:

The absolute path of the input path.

mobly.utils.cli_cmd_to_string(args)[source]

Converts a cmd arg list to string.

Parameters:

args – list of strings, the arguments of a command.

Returns:

String representation of the command.

mobly.utils.concurrent_exec(func, param_list, max_workers=30, raise_on_exception=False)[source]

Executes a function with different parameters pseudo-concurrently.

This is basically a map function. Each element (should be an iterable) in the param_list is unpacked and passed into the function. Due to Python’s GIL, there’s no true concurrency. This is suited for IO-bound tasks.

Parameters:
  • func – The function that performs a task.

  • param_list – A list of iterables, each being a set of params to be passed into the function.

  • max_workers – int, the number of workers to use for parallelizing the tasks. By default, this is 30 workers.

  • raise_on_exception – bool, raises all of the task failures if any of the tasks failed if True. By default, this is False.

Returns:

A list of return values from each function execution. If an execution caused an exception, the exception object will be the corresponding result.

Raises:

RuntimeError – If executing any of the tasks failed and raise_on_exception is True.

mobly.utils.create_alias(target_path, alias_path)[source]

Creates an alias at ‘alias_path’ pointing to the file ‘target_path’.

On Unix, this is implemented via symlink. On Windows, this is done by creating a Windows shortcut file.

Parameters:
  • target_path – Destination path that the alias should point to.

  • alias_path – Path at which to create the new alias.

mobly.utils.create_dir(path)[source]

Creates a directory if it does not exist already.

Parameters:

path – The path of the directory to create.

mobly.utils.epoch_to_human_time(epoch_time)[source]

Converts an epoch timestamp to human readable time.

This essentially converts an output of get_current_epoch_time to an output of get_current_human_time

Parameters:

epoch_time – An integer representing an epoch timestamp in milliseconds.

Returns:

A time string representing the input time. None if input param is invalid.

mobly.utils.find_field(item_list, cond, comparator, target_field)[source]

Finds the value of a field in a dict object that satisfies certain conditions.

Parameters:
  • item_list – A list of dict objects.

  • cond – A param that defines the condition.

  • comparator – A function that checks if an dict satisfies the condition.

  • target_field – Name of the field whose value to be returned if an item satisfies the condition.

Returns:

Target value or None if no item satisfies the condition.

mobly.utils.find_files(paths, file_predicate)[source]

Locate files whose names and extensions match the given predicate in the specified directories.

Parameters:
  • paths – A list of directory paths where to find the files.

  • file_predicate – A function that returns True if the file name and extension are desired.

Returns:

A list of files that match the predicate.

mobly.utils.find_subclass_in_module(base_class, module)[source]

Finds the single subclass of the given base class in the given module.

Parameters:
  • base_class – class, the base class to look for a subclass of in the module.

  • module – module, the module to look for the single subclass in.

Returns:

The single subclass of the given base class.

Raises:

ValueError – If the number of subclasses found was not exactly one.

mobly.utils.find_subclasses_in_module(base_classes, module)[source]

Finds the subclasses of the given classes in the given module.

Parameters:
  • base_classes – list of classes, the base classes to look for the subclasses of in the module.

  • module – module, the module to look for the subclasses in.

Returns:

A list of all of the subclasses found in the module.

mobly.utils.get_available_host_port()[source]

Gets a host port number available for adb forward.

Deprecated since version 1.12: This method is unreliable. Pass tcp:0 to adb forward instead.

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.get_current_epoch_time()[source]

Current epoch time in milliseconds.

Returns:

An integer representing the current epoch time in milliseconds.

mobly.utils.get_current_human_time()[source]

Returns the current time in human readable format.

Returns:

Min:Sec format.

Return type:

The current time stamp in Month-Day-Year Hour

mobly.utils.get_settable_properties(cls)[source]

Gets the settable properties of a class.

Only returns the explicitly defined properties with setters.

Parameters:

cls – A class in Python.

mobly.utils.get_timezone_olson_id()[source]

Return the Olson ID of the local (non-DST) timezone.

Returns:

A string representing one of the Olson IDs of the local (non-DST) timezone.

mobly.utils.grep(regex, output)[source]

Similar to linux’s grep, this returns the line in an output stream that matches a given regex pattern.

It does not rely on the grep binary and is not sensitive to line endings, so it can be used cross-platform.

Parameters:
  • regex – string, a regex that matches the expected pattern.

  • output – byte string, the raw output of the adb cmd.

Returns:

A list of strings, all of which are output lines that matches the regex pattern.

mobly.utils.load_file_to_base64_str(f_path)[source]

Loads the content of a file into a base64 string.

Parameters:

f_path – full path to the file including the file name.

Returns:

A base64 string representing the content of the file in utf-8 encoding.

mobly.utils.rand_ascii_str(length)[source]

Generates a random string of specified length, composed of ascii letters and digits.

Parameters:

length – The number of characters in the string.

Returns:

The random string generated.

mobly.utils.run_command(cmd, stdout=None, stderr=None, shell=False, timeout=None, cwd=None, env=None, text=False, universal_newlines=None)[source]

Runs a command in a subprocess.

This function is very similar to subprocess.check_output. The main difference is that it returns the return code and std error output as well as supporting a timeout parameter.

Parameters:
  • cmd – string or list of strings, the command to run. See subprocess.Popen() documentation.

  • stdout – file handle, the file handle to write std out to. If None is given, then subprocess.PIPE is used. See subprocess.Popen() documentation.

  • stderr – file handle, the file handle to write std err to. If None is given, then subprocess.PIPE is used. See subprocess.Popen() documentation.

  • shell – bool, True to run this command through the system shell, False to invoke it directly. See subprocess.Popen() docs.

  • timeout – float, the number of seconds to wait before timing out. If not specified, no timeout takes effect.

  • cwd – string, the path to change the child’s current directory to before it is executed. Note that this directory is not considered when searching the executable, so you can’t specify the program’s path relative to cwd.

  • env – dict, a mapping that defines the environment variables for the new process. Default behavior is inheriting the current process’ environment.

  • text – bool, True to open file objects in text mode, False in binary mode.

  • universal_newlines – bool, legacy alias for text.

Returns:

A 3-tuple of the consisting of the return code, the std output, and the

std error.

Raises:

subprocess.TimeoutExpired – The command timed out.

mobly.utils.start_standing_subprocess(cmd, shell=False, env=None, stdout=-1, stderr=-1)[source]

Starts a long-running subprocess.

This is not a blocking call and the subprocess started by it should be explicitly terminated with stop_standing_subprocess.

For short-running commands, you should use subprocess.check_call, which blocks.

Parameters:
  • cmd – string, the command to start the subprocess with.

  • shell – bool, True to run this command through the system shell, False to invoke it directly. See subprocess.Popen() docs.

  • env – dict, a custom environment to run the standing subprocess. If not specified, inherits the current environment. See subprocess.Popen() docs.

  • stdout – None, subprocess.PIPE, subprocess.DEVNULL, an existing file descriptor, or an existing file object. See subprocess.Popen() docs.

  • stderr – None, subprocess.PIPE, subprocess.DEVNULL, an existing file descriptor, or an existing file object. See subprocess.Popen() docs.

Returns:

The subprocess that was started.

mobly.utils.stop_standing_subprocess(proc)[source]

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:

proc – Subprocess to terminate.

Raises:

Error – if the subprocess could not be stopped.

mobly.utils.wait_for_standing_subprocess(proc, timeout=None)[source]

Waits for a subprocess started by start_standing_subprocess to finish or times out.

Propagates the exception raised by the subprocess.wait(.) function. The subprocess.TimeoutExpired exception is raised if the process timed-out rather than terminating.

If no exception is raised: the subprocess terminated on its own. No need to call stop_standing_subprocess() to kill it.

If an exception is raised: the subprocess is still alive - it did not terminate. Either call stop_standing_subprocess() to kill it, or call wait_for_standing_subprocess() to keep waiting for it to terminate on its own.

If the corresponding subprocess command generates a large amount of output and this method is called with a timeout value, then the command can hang indefinitely. See http://go/pylib/subprocess.html#subprocess.Popen.wait

Parameters:
  • proc – Subprocess to wait for.

  • timeout – An integer number of seconds to wait before timing out.