Utilities APIs

This is a set of utility APIs that Avocado provides as added value to test writers.

Submodules

avocado.utils.archive module

Module to help extract and create compressed archives.

exception avocado.utils.archive.ArchiveException

Bases: exceptions.Exception

Base exception for all archive errors.

class avocado.utils.archive.ArchiveFile(filename, mode='r')

Bases: object

Class that represents an Archive file.

Archives are ZIP files or Tarballs.

Creates an instance of ArchiveFile.

Parameters:
  • filename – the archive file name.
  • mode – file mode, r read, w write.
add(filename, arcname=None)

Add file to the archive.

Parameters:
  • filename – file to archive.
  • arcname – alternative name for the file in the archive.
close()

Close archive.

extract(path='.')

Extract all files from the archive.

Parameters:path – destination path.
list()

List files to the standard output.

classmethod open(filename, mode='r')

Creates an instance of ArchiveFile.

Parameters:
  • filename – the archive file name.
  • mode – file mode, r read, w write.
avocado.utils.archive.compress(filename, path)

Compress files in an archive.

Parameters:
  • filename – archive file name.
  • path – origin directory path to files to compress. No individual files allowed.
avocado.utils.archive.create(filename, path)

Compress files in an archive.

Parameters:
  • filename – archive file name.
  • path – origin directory path to files to compress. No individual files allowed.
avocado.utils.archive.extract(filename, path)

Extract files from an archive.

Parameters:
  • filename – archive file name.
  • path – destination path to extract to.
avocado.utils.archive.is_archive(filename)

Test if a given file is an archive.

Parameters:filename – file to test.
Returns:True if it is an archive.
avocado.utils.archive.uncompress(filename, path)

Extract files from an archive.

Parameters:
  • filename – archive file name.
  • path – destination path to extract to.

avocado.utils.astring module

Operations with strings (conversion and sanitation).

The unusual name aims to avoid causing name clashes with the stdlib module string. Even with the dot notation, people may try to do things like

import string ... from avocado.utils import string

And not notice until their code starts failing.

avocado.utils.astring.bitlist_to_string(data)

Transform from bit list to ASCII string.

Parameters:data – Bit list to be transformed
avocado.utils.astring.iter_tabular_output(matrix, header=None)

Generator for a pretty, aligned string representation of a nxm matrix.

This representation can be used to print any tabular data, such as database results. It works by scanning the lengths of each element in each column, and determining the format string dynamically.

Parameters:
  • matrix – Matrix representation (list with n rows of m elements).
  • header – Optional tuple or list with header elements to be displayed.
avocado.utils.astring.shell_escape(command)

Escape special characters from a command so that it can be passed as a double quoted (” ”) string in a (ba)sh command.

Parameters:command – the command string to escape.
Returns:The escaped command string. The required englobing double quotes are NOT added and so should be added at some point by the caller.

See also: http://www.tldp.org/LDP/abs/html/escapingsection.html

avocado.utils.astring.string_to_bitlist(data)

Transform from ASCII string to bit list.

Parameters:data – String to be transformed
avocado.utils.astring.strip_console_codes(output, custom_codes=None)

Remove the Linux console escape and control sequences from the console output. Make the output readable and can be used for result check. Now only remove some basic console codes using during boot up.

Parameters:
  • output (string) – The output from Linux console
  • custom_codes – The codes added to the console codes which is not covered in the default codes
Returns:

the string wihout any special codes

Return type:

string

avocado.utils.astring.tabular_output(matrix, header=None)

Pretty, aligned string representation of a nxm matrix.

This representation can be used to print any tabular data, such as database results. It works by scanning the lengths of each element in each column, and determining the format string dynamically.

Parameters:
  • matrix – Matrix representation (list with n rows of m elements).
  • header – Optional tuple or list with header elements to be displayed.
Returns:

String with the tabular output, lines separated by unix line feeds.

Return type:

str

avocado.utils.aurl module

URL related functions.

The strange name is to avoid accidental naming colisions in code.

avocado.utils.aurl.is_url(path)

Return True if path looks like an URL.

Parameters:path – path to check.
Return type:Boolean.

avocado.utils.build module

avocado.utils.build.make(path, make='make', env=None, extra_args='', ignore_status=False, allow_output_check='none')

Run make, adding MAKEOPTS to the list of options.

Parameters:
  • make – what make command name to use.
  • env – dictionary with environment variables to be set before calling make (e.g.: CFLAGS).
  • extra – extra command line arguments to pass to make.
  • allow_output_check (str) – Whether to log the command stream outputs (stdout and stderr) of the make process in the test stream files. Valid values: ‘stdout’, for allowing only standard output, ‘stderr’, to allow only standard error, ‘all’, to allow both standard output and error, and ‘none’, to allow none to be recorded (default). The default here is ‘none’, because usually we don’t want to use the compilation output as a reference in tests.

avocado.utils.cpu module

Get information from the current’s machine CPU.

avocado.utils.cpu.cpu_has_flags(flags)

Check if a list of flags are available on current CPU info

Parameters:flags (list) – A list of cpu flags that must exists on the current CPU.
Returns:bool True if all the flags were found or False if not
Return type:list
avocado.utils.cpu.get_cpu_arch()

Work out which CPU architecture we’re running on

avocado.utils.cpu.get_cpu_vendor_name()

Get the current cpu vendor name

Returns:string ‘intel’ or ‘amd’ or ‘power7’ depending on the current CPU architecture.
Return type:string

avocado.utils.crypto module

avocado.utils.crypto.hash_file(filename, size=None, algorithm='md5')

Calculate the hash value of filename.

If size is not None, limit to first size bytes. Throw exception if something is wrong with filename. Can be also implemented with bash one-liner (assuming size%1024==0):

dd if=filename bs=1024 count=size/1024 | sha1sum -
Parameters:
  • filename – Path of the file that will have its hash calculated.
  • method – Method used to calculate the hash. Supported methods: * md5 * sha1
  • size – If provided, hash only the first size bytes of the file.
Returns:

Hash of the file, if something goes wrong, return None.

avocado.utils.crypto.hash_wrapper(algorithm='md5', data=None)

Returns an hash object of data using either md5 or sha1 only.

Parameters:input – Optional input string that will be used to update the hash.
Returns:Hash object.

avocado.utils.data_factory module

Generate data useful for the avocado framework and tests themselves.

avocado.utils.data_factory.generate_random_string(length, ignore='!"#$%&\'()*+, -./:;<=>?@[\\]^_`{|}~', convert='')

Generate a random string using alphanumeric characters.

Parameters:
  • length (int) – Length of the string that will be generated.
  • ignore (str) – Characters that will not include in generated string.
  • convert (str) – Characters that need to be escaped (prepend “”).
Returns:

The generated random string.

avocado.utils.data_factory.make_dir_and_populate(basedir='/tmp')

Create a directory in basedir and populate with a number of files.

The files just have random text contents.

Parameters:basedir (str) – Base directory where directory should be generated.
Returns:Path of the dir created and populated.
Return type:str

avocado.utils.data_structures module

This module contains handy classes that can be used inside avocado core code or plugins.

class avocado.utils.data_structures.Borg

Multiple instances of this class will share the same state.

This is considered a better design pattern in Python than more popular patterns, such as the Singleton. Inspired by Alex Martelli’s article mentioned below:

See:http://www.aleax.it/5ep.html
class avocado.utils.data_structures.LazyProperty(f_get)

Bases: object

Lazily instantiated property.

Use this decorator when you want to set a property that will only be evaluated the first time it’s accessed. Inspired by the discussion in the Stack Overflow thread below:

See:http://stackoverflow.com/questions/15226721/

avocado.utils.debug module

This file contains tools for (not only) Avocado developers.

avocado.utils.debug.log_calls(length=None, cls_name=None)

Use this as decorator to log the function call altogether with arguments. :param length: Max message length :param cls_name: Optional class name prefix

avocado.utils.debug.log_calls_class(length=None)

Use this as decorator to log the function methods’ calls. :param length: Max message length

avocado.utils.debug.measure_duration(func)

Use this as decorator to measure duration of the function execution. The output is “Function $name: ($current_duration, $accumulated_duration)”

avocado.utils.distro module

This module provides the client facilities to detect the Linux Distribution it’s running under.

class avocado.utils.distro.LinuxDistro(name, version, release, arch)

Bases: object

Simple collection of information for a Linux Distribution

Initializes a new Linux Distro

Parameters:
  • name (str) – a short name that precisely distinguishes this Linux Distribution among all others.
  • version (str) – the major version of the distribution. Usually this is a single number that denotes a large development cycle and support file.
  • release (str) – the release or minor version of the distribution. Usually this is also a single number, that is often omitted or starts with a 0 when the major version is initially release. It’s ofter associated with a shorter development cycle that contains incremental a collection of improvements and fixes.
  • arch (str) – the main target for this Linux Distribution. It’s common for some architectures to ship with packages for previous and still compatible architectures, such as it’s the case with Intel/AMD 64 bit architecture that support 32 bit code. In cases like this, this should be set to the 64 bit architecture name.
class avocado.utils.distro.Probe

Bases: object

Probes the machine and does it best to confirm it’s the right distro

CHECK_FILE = None

Points to a file that can determine if this machine is running a given Linux Distribution. This servers a first check that enables the extra checks to carry on.

CHECK_FILE_CONTAINS = None

Sets the content that should be checked on the file pointed to by CHECK_FILE_EXISTS. Leave it set to None (its default) to check only if the file exists, and not check its contents

CHECK_FILE_DISTRO_NAME = None

The name of the Linux Distribution to be returned if the file defined by CHECK_FILE_EXISTS exist.

CHECK_VERSION_REGEX = None

A regular expresion that will be run on the file pointed to by CHECK_FILE_EXISTS

check_name_for_file()

Checks if this class will look for a file and return a distro

The conditions that must be true include the file that identifies the distro file being set (CHECK_FILE) and the name of the distro to be returned (CHECK_FILE_DISTRO_NAME)

check_name_for_file_contains()

Checks if this class will look for text on a file and return a distro

The conditions that must be true include the file that identifies the distro file being set (CHECK_FILE), the text to look for inside the distro file (CHECK_FILE_CONTAINS) and the name of the distro to be returned (CHECK_FILE_DISTRO_NAME)

check_release()

Checks if this has the conditions met to look for the release number

check_version()

Checks if this class will look for a regex in file and return a distro

get_distro()

Returns the LinuxDistro this probe detected

name_for_file()

Get the distro name if the CHECK_FILE is set and exists

name_for_file_contains()

Get the distro if the CHECK_FILE is set and has content

release()

Returns the release of the distro

version()

Returns the version of the distro

avocado.utils.distro.register_probe(probe_class)

Register a probe to be run during autodetection

avocado.utils.distro.detect()

Attempts to detect the Linux Distribution running on this machine

Returns:the detected LinuxDistro or UNKNOWN_DISTRO
Return type:LinuxDistro

avocado.utils.download module

Methods to download URLs and regular files.

avocado.utils.download.get_file(src, dst, permissions=None, hash_expected=None, hash_algorithm='md5', download_retries=1)

Gets a file from a source location, optionally using caching.

If no hash_expected is provided, simply download the file. Else, keep trying to download the file until download_failures exceeds download_retries or the hashes match.

If the hashes match, return dst. If download_failures exceeds download_retries, raise an EnvironmentError.

Parameters:
  • src – source path or URL. May be local or a remote file.
  • dst – destination path.
  • permissions – (optional) set access permissions.
  • hash_expected – Hash string that we expect the file downloaded to have.
  • hash_algorithm – Algorithm used to calculate the hash string (md5, sha1).
  • download_retries – Number of times we are going to retry a failed download.
Raise:

EnvironmentError.

Returns:

destination path.

avocado.utils.download.url_download(url, filename, data=None, timeout=300)

Retrieve a file from given url.

Parameters:
  • url – source URL.
  • filename – destination path.
  • data – (optional) data to post.
  • timeout – (optional) default timeout in seconds.
Returns:

None.

avocado.utils.download.url_download_interactive(url, output_file, title='', chunk_size=102400)

Interactively downloads a given file url to a given output file.

Parameters:
  • url (string) – URL for the file to be download
  • output_file (string) – file name or absolute path on which to save the file to
  • title (string) – optional title to go along the progress bar
  • chunk_size (integer) – amount of data to read at a time
avocado.utils.download.url_open(url, data=None, timeout=5)

Wrapper to urllib2.urlopen() with timeout addition.

Parameters:
  • url – URL to open.
  • data – (optional) data to post.
  • timeout – (optional) default timeout in seconds.
Returns:

file-like object.

Raises:

URLError.

avocado.utils.gdb module

Module that provides communication with GDB via its GDB/MI interpreter

class avocado.utils.gdb.GDB(path='/usr/bin/gdb', *extra_args)

Bases: object

Wraps a GDB subprocess for easier manipulation

DEFAULT_BREAK = 'main'
REQUIRED_ARGS = ['--interpreter=mi', '--quiet']
cli_cmd(command)

Sends a cli command encoded as an MI command

Parameters:command (str) – a regular GDB cli command
Returns:a CommandResult instance
Return type:CommandResult
cmd(command)

Sends a command and parses all lines until prompt is received

Parameters:command (str) – the GDB command, hopefully in MI language
Returns:a CommandResult instance
Return type:CommandResult
cmd_exists(command)

Checks if a given command exists

Parameters:command (str) – a GDB MI command, including the dash (-) prefix
Returns:either True or False
Return type:bool
connect(port)

Connects to a remote debugger (a gdbserver) at the given TCP port

This uses the “extended-remote” target type only

Parameters:port (int) – the TCP port number
Returns:a CommandResult instance
Return type:CommandResult
del_break(number)

Deletes a breakpoint by its number

Parameters:number (int) – the breakpoint number
Returns:a CommandResult instance
Return type:CommandResult
disconnect()

Disconnects from a remote debugger

Returns:a CommandResult instance
Return type:CommandResult
exit()

Exits the GDB application gracefully

Returns:the result of subprocess.POpen.wait(), that is, a subprocess.POpen.returncode
Return type:int or None
read_gdb_response(timeout=0.01, max_tries=100)

Read raw responses from GDB

Parameters:
  • timeout (float) – the amount of time to way between read attemps
  • max_tries (int) – the maximum number of cycles to try to read until a response is obtained
Returns:

a string containing a raw response from GDB

Return type:

str

read_until_break(max_lines=100)

Read lines from GDB until a break condition is reached

Parameters:max_lines (int) – the maximum number of lines to read
Returns:a list of messages read
Return type:list of str
run(args=[])

Runs the application inside the debugger

Parameters:args (builtin.list) – the arguments to be passed to the binary as command line arguments
Returns:a CommandResult instance
Return type:CommandResult
send_gdb_command(command)

Send a raw command to the GNU debugger input

Parameters:command (str) – the GDB command, hopefully in MI language
Returns:None
set_break(location, ignore_error=False)

Sets a new breakpoint on the binary currently being debugged

Parameters:location (str) – a breakpoint location expression as accepted by GDB
Returns:a CommandResult instance
Return type:CommandResult
set_file(path)

Sets the file that will be executed

Parameters:path (str) – the path of the binary that will be executed
Returns:a CommandResult instance
Return type:CommandResult
class avocado.utils.gdb.GDBServer(path='/usr/bin/gdbserver', port=None, wait_until_running=True, *extra_args)

Bases: object

Wraps a gdbserver instance

Initializes a new gdbserver instance

Parameters:
  • path (str) – location of the gdbserver binary
  • port (int) – tcp port number to listen on for incoming connections
  • wait_until_running (bool) – wait until the gdbserver is running and accepting connections. It may take a little after the process is started and it is actually bound to the aloccated port
  • extra_args – optional extra arguments to be passed to gdbserver
INIT_TIMEOUT = 2.0

The time to optionally wait for the server to initialize itself and be ready to accept new connections

PORT_RANGE = (20000, 20999)

The range from which a port to GDB server will try to be allocated from

REQUIRED_ARGS = ['--multi']

The default arguments used when starting the GDB server process

exit(force=True)

Quits the gdb_server process

Most correct way of quitting the GDB server is by sending it a command. If no GDB client is connected, then we can try to connect to it and send a quit command. If this is not possible, we send it a signal and wait for it to finish.

Parameters:force (bool) – if a forced exit (sending SIGTERM) should be attempted
Returns:None
class avocado.utils.gdb.GDBRemote(host, port, no_ack_mode=True, extended_mode=True)

Bases: object

Initializes a new GDBRemote object.

A GDBRemote acts like a client that speaks the GDB remote protocol, documented at:

https://sourceware.org/gdb/current/onlinedocs/gdb/Remote-Protocol.html

Caveat: we currently do not support communicating with devices, only with TCP sockets. This limitation is basically due to the lack of use cases that justify an implementation, but not due to any technical shortcoming.

Parameters:
  • host (str) – the IP address or host name
  • port (int) – the port number where the the remote GDB is listening on
  • no_ack_mode (bool) – if the packet transmission confirmation mode should be disabled
  • extended_mode – if the remote extended mode should be enabled
cmd(command_data, expected_response=None)

Sends a command data to a remote gdb server

Limitations: the current version does not deal with retransmissions.

Parameters:
  • command_data (str) – the remote command to send the the remote stub
  • expected_response (str) – the (optional) response that is expected as a response for the command sent
Raises:

RetransmissionRequestedError, UnexpectedResponseError

Returns:

raw data read from from the remote server

Return type:

str

connect()

Connects to the remote target and initializes the chosen modes

set_extended_mode()

Enable extended mode. In extended mode, the remote server is made persistent. The ‘R’ packet is used to restart the program being debugged. Original documentation at:

https://sourceware.org/gdb/current/onlinedocs/gdb/Packets.html#extended-mode

start_no_ack_mode()

Request that the remote stub disable the normal +/- protocol acknowledgments. Original documentation at:

https://sourceware.org/gdb/current/onlinedocs/gdb/General-Query-Packets.html#QStartNoAckMode

avocado.utils.genio module

Avocado generic IO related functions.

avocado.utils.genio.ask(question, auto=False)

Prompt the user with a (y/n) question.

Parameters:
  • question (str) – Question to be asked
  • auto (bool) – Whether to return “y” instead of asking the question
Returns:

User answer

Return type:

str

avocado.utils.genio.close_log_file(filename)
avocado.utils.genio.log_line(filename, line)

Write a line to a file.

Parameters:
  • filename – Path of file to write to, either absolute or relative to the dir set by set_log_file_dir().
  • line – Line to write.
avocado.utils.genio.read_all_lines(filename)

Return all lines of a given file

This utility method returns an empty list in any error scenario, that is, it doesn’t attempt to identify error paths and raise appropriate exceptions. It does exactly the opposite to that.

This should be used when it’s fine or desirable to have an empty set of lines if a file is missing or is unreadable.

Parameters:filename (str) – Path to the file.
Returns:all lines of the file as list
Return type:builtin.list
avocado.utils.genio.read_file(filename)

Read the entire contents of file.

Parameters:filename (str) – Path to the file.
Returns:File contents
Return type:str
avocado.utils.genio.read_one_line(filename)

Read the first line of filename.

Parameters:filename (str) – Path to the file.
Returns:First line contents
Return type:str
avocado.utils.genio.set_log_file_dir(directory)

Set the base directory for log files created by log_line().

Parameters:dir – Directory for log files.
avocado.utils.genio.write_file(filename, data)

Write data to a file.

Parameters:
  • filename (str) – Path to the file.
  • line (str) – Line to be written.
avocado.utils.genio.write_one_line(filename, line)

Write one line of text to filename.

Parameters:
  • filename (str) – Path to the file.
  • line (str) – Line to be written.

avocado.utils.git module

APIs to download/update git repositories from inside python scripts.

class avocado.utils.git.GitRepoHelper(uri, branch='master', lbranch='master', commit=None, destination_dir=None, base_uri=None)

Bases: object

Helps to deal with git repos, mostly fetching content from a repo

Instantiates a new GitRepoHelper

Parameters:
  • uri (string) – git repository url
  • branch (string) – git remote branch
  • destination_dir (string) – path of a dir where to save downloaded code
  • commit (string) – specific commit to download
  • lbranch (string) – git local branch name, if different from remote
  • base_uri (string) – a closer, usually local, git repository url from where to fetch content first
checkout(branch=None, commit=None)

Performs a git checkout for a given branch and start point (commit)

Parameters:
  • branch – Remote branch name.
  • commit – Specific commit hash.
execute()

Performs all steps necessary to initialize and download a git repo.

This includes the init, fetch and checkout steps in one single utility method.

fetch(uri)

Performs a git fetch from the remote repo

get_top_commit()

Returns the topmost commit id for the current branch.

Returns:Commit id.
get_top_tag()

Returns the topmost tag for the current branch.

Returns:Tag.
git_cmd(cmd, ignore_status=False)

Wraps git commands.

Parameters:
  • cmd – Command to be executed.
  • ignore_status – Whether we should suppress error.CmdError exceptions if the command did return exit code !=0 (True), or not suppress them (False).
init()

Initializes a directory for receiving a verbatim copy of git repo

This creates a directory if necessary, and either resets or inits the repo

avocado.utils.git.get_repo(uri, branch='master', lbranch='master', commit=None, destination_dir=None, base_uri=None)

Utility function that retrieves a given git code repository.

Parameters:
  • uri (string) – git repository url
  • branch (string) – git remote branch
  • destination_dir (string) – path of a dir where to save downloaded code
  • commit (string) – specific commit to download
  • lbranch (string) – git local branch name, if different from remote
  • uri – a closer, usually local, git repository url from where to fetch content first from

avocado.utils.iso9660 module

Basic ISO9660 file-system support.

This code does not attempt (so far) to implement code that knows about ISO9660 internal structure. Instead, it uses commonly available support either in userspace tools or on the Linux kernel itself (via mount).

avocado.utils.iso9660.iso9660(path)

Checks the avaiable tools on a system and chooses class accordingly

This is a convinience function, that will pick the first avaialable iso9660 capable tool.

Parameters:path (str) – path to an iso9660 image file
Returns:an instance of any iso9660 capable tool
Return type:Iso9660IsoInfo, Iso9660IsoRead, Iso9660Mount or None
class avocado.utils.iso9660.Iso9660IsoInfo(path)

Bases: avocado.utils.iso9660.BaseIso9660

Represents a ISO9660 filesystem

This implementation is based on the cdrkit’s isoinfo tool

read(path)
class avocado.utils.iso9660.Iso9660IsoRead(path)

Bases: avocado.utils.iso9660.BaseIso9660

Represents a ISO9660 filesystem

This implementation is based on the libcdio’s iso-read tool

close()
copy(src, dst)
read(path)
class avocado.utils.iso9660.Iso9660Mount(path)

Bases: avocado.utils.iso9660.BaseIso9660

Represents a mounted ISO9660 filesystem.

initializes a mounted ISO9660 filesystem

Parameters:path (str) – path to the ISO9660 file
close()

Perform umount operation on the temporary dir

Return type:None
copy(src, dst)
Parameters:
  • src (str) – source
  • dst (str) – destination
Return type:

None

read(path)

Read data from path

Parameters:path (str) – path to read data
Returns:data content
Return type:str

avocado.utils.kernel_build module

class avocado.utils.kernel_build.KernelBuild(version, config_path=None, work_dir=None)

Bases: object

Build the Linux Kernel from official tarballs.

Creates an instance of KernelBuild.

Parameters:
  • version – kernel version (“3.19.8”).
  • config_path – path to config file.
  • work_dir – work directory.
Returns:

None.

SOURCE = 'linux-{version}.tar.gz'
URL = 'https://www.kernel.org/pub/linux/kernel/v3.x/'
build()

Build kernel from source.

configure()

Configure/prepare kernel source to build.

download()

Download kernel source.

uncompress()

Uncompress kernel source.

avocado.utils.linux_modules module

APIs to list and load/unload linux kernel modules.

avocado.utils.linux_modules.get_loaded_modules()
avocado.utils.linux_modules.get_submodules(module_name)

Get all submodules of the module.

Parameters:module_name (str) – Name of module to search for
Returns:List of the submodules
Return type:builtin.list
avocado.utils.linux_modules.load_module(module_name)
avocado.utils.linux_modules.loaded_module_info(module_name)

Get loaded module details: Size and Submodules.

Parameters:module_name (str) – Name of module to search for
Returns:Dictionary of module info, name, size, submodules if present
Return type:dict
avocado.utils.linux_modules.module_is_loaded(module_name)

Is module loaded

Parameters:module_name (str) – Name of module to search for
Returns:True is module is loaded
Return type:bool
avocado.utils.linux_modules.parse_lsmod_for_module(l_raw, module_name, escape=True)

Use a regexp to parse raw lsmod output and get module information :param l_raw: raw output of lsmod :type l_raw: str :param module_name: Name of module to search for :type module_name: str :param escape: Escape regexp tokens in module_name, default True :type escape: bool :return: Dictionary of module info, name, size, submodules if present :rtype: dict

avocado.utils.linux_modules.unload_module(module_name)

Removes a module. Handles dependencies. If even then it’s not possible to remove one of the modules, it will throw an error.CmdError exception.

Parameters:module_name (str) – Name of the module we want to remove.

avocado.utils.memory module

avocado.utils.memory.drop_caches()

Writes back all dirty pages to disk and clears all the caches.

avocado.utils.memory.freememtotal()

Read MemFree from meminfo.

avocado.utils.memory.get_buddy_info(chunk_sizes, nodes='all', zones='all')

Get the fragement status of the host.

It uses the same method to get the page size in buddyinfo. The expression to evaluate it is:

2^chunk_size * page_size

The chunk_sizes can be string make up by all orders that you want to check splited with blank or a mathematical expression with >, < or =.

For example:
  • The input of chunk_size could be: 0 2 4, and the return will be {'0': 3, '2': 286, '4': 687}
  • If you are using expression: >=9 the return will be {'9': 63, '10': 225}
Parameters:
  • chunk_size (string) – The order number shows in buddyinfo. This is not the real page size.
  • nodes (string) – The numa node that you want to check. Default value is all
  • zones (string) – The memory zone that you want to check. Default value is all
Returns:

A dict using the chunk_size as the keys

Return type:

dict

avocado.utils.memory.get_huge_page_size()

Get size of the huge pages for this system.

Returns:Huge pages size (KB).
avocado.utils.memory.get_num_huge_pages()

Get number of huge pages for this system.

Returns:Number of huge pages.
avocado.utils.memory.memtotal()

Read Memtotal from meminfo.

avocado.utils.memory.node_size()

Return node size.

Returns:Node size.
avocado.utils.memory.numa_nodes()

Get a list of NUMA nodes present on the system.

Returns:List with nodes.
avocado.utils.memory.read_from_meminfo(key)

Retrieve key from meminfo.

Parameters:key – Key name, such as MemTotal.
avocado.utils.memory.read_from_numa_maps(pid, key)

Get the process numa related info from numa_maps. This function only use to get the numbers like anon=1.

Parameters:
  • pid (String) – Process id
  • key (String) – The item you want to check from numa_maps
Returns:

A dict using the address as the keys

Return type:

dict

avocado.utils.memory.read_from_smaps(pid, key)

Get specific item value from the smaps of a process include all sections.

Parameters:
  • pid (String) – Process id
  • key (String) – The item you want to check from smaps
Returns:

The value of the item in kb

Return type:

int

avocado.utils.memory.read_from_vmstat(key)

Get specific item value from vmstat

Parameters:key (String) – The item you want to check from vmstat
Returns:The value of the item
Return type:int
avocado.utils.memory.rounded_memtotal()

Get memtotal, properly rounded.

Returns:Total memory, KB.
avocado.utils.memory.set_num_huge_pages(num)

Set number of huge pages.

Parameters:num – Target number of huge pages.

avocado.utils.network module

Module with network related utility functions

avocado.utils.network.find_free_port(start_port, end_port, address='localhost')

Return a host free port in the range [start_port, end_port].

Parameters:
  • start_port – First port that will be checked.
  • end_port – Port immediately after the last one that will be checked.
avocado.utils.network.find_free_ports(start_port, end_port, count, address='localhost')

Return count of host free ports in the range [start_port, end_port].

Parameters:
  • count – Initial number of ports known to be free in the range.
  • start_port – First port that will be checked.
  • end_port – Port immediately after the last one that will be checked.
avocado.utils.network.is_port_free(port, address)

Return True if the given port is available for use.

Parameters:port – Port number

avocado.utils.output module

Utility functions for user friendly display of information.

class avocado.utils.output.ProgressBar(minimum=0, maximum=100, width=75, title='')

Bases: object

Displays interactively the progress of a given task

Inspired/adapted from https://gist.github.com/t0xicCode/3306295

Initializes a new progress bar

Parameters:
  • minimum (integer) – minimum (initial) value on the progress bar
  • maximum (integer) – maximum (final) value on the progress bar
  • with – number of columns, that is screen width
append_amount(amount)

Increments the current amount value.

draw()

Prints the updated text to the screen.

update_amount(amount)

Performs sanity checks and update the current amount.

update_percentage(percentage)

Updates the progress bar to the new percentage.

avocado.utils.output.display_data_size(size)

Display data size in human readable units (SI).

Parameters:size (int) – Data size, in Bytes.
Returns:Human readable string with data size, using SI prefixes.

avocado.utils.path module

Avocado path related functions.

exception avocado.utils.path.CmdNotFoundError(cmd, paths)

Bases: exceptions.Exception

Indicates that the command was not found in the system after a search.

Parameters:
  • cmd – String with the command.
  • paths – List of paths where we looked after.
class avocado.utils.path.PathInspector(path)

Bases: object

get_first_line()
has_exec_permission()
is_empty()
is_python()
is_script(language=None)
avocado.utils.path.find_command(cmd, default=None)

Try to find a command in the PATH, paranoid version.

Parameters:
  • cmd – Command to be found.
  • default – Command path to use as a fallback if not found in the standard directories.
Raise:

avocado.utils.path.CmdNotFoundError in case the command was not found and no default was given.

avocado.utils.path.get_path(base_path, user_path)

Translate a user specified path to a real path. If user_path is relative, append it to base_path. If user_path is absolute, return it as is.

Parameters:
  • base_path – The base path of relative user specified paths.
  • user_path – The user specified path.
avocado.utils.path.init_dir(*args)

Wrapper around os.path.join that creates dirs based on the final path.

Parameters:args – List of dir arguments that will be os.path.joined.
Returns:directory.
Return type:str

avocado.utils.process module

Functions dedicated to find and run external commands.

avocado.utils.process.CURRENT_WRAPPER = None

The active wrapper utility script.

exception avocado.utils.process.CmdError(command=None, result=None)

Bases: exceptions.Exception

class avocado.utils.process.CmdResult(command='', stdout='', stderr='', exit_status=None, duration=0)

Bases: object

Command execution result.

Parameters:
  • command – String containing the command line itself
  • exit_status – Integer exit code of the process
  • stdout – String containing stdout of the process
  • stderr – String containing stderr of the process
  • duration – Elapsed wall clock time running the process
class avocado.utils.process.GDBSubProcess(cmd, verbose=True, allow_output_check='all', shell=False, env=None)

Bases: object

Runs a subprocess inside the GNU Debugger

Creates the subprocess object, stdout/err, reader threads and locks.

Parameters:
  • cmd (str) – Command line to run.
  • verbose (bool) – Whether to log the command run and stdout/stderr. Currently unused and provided for compatibility only.
  • allow_output_check (str) – Whether to log the command stream outputs (stdout and stderr) in the test stream files. Valid values: ‘stdout’, for allowing only standard output, ‘stderr’, to allow only standard error, ‘all’, to allow both standard output and error (default), and ‘none’, to allow none to be recorded. Currently unused and provided for compatibility only.
create_and_wait_on_resume_fifo(path)

Creates a FIFO file and waits until it’s written to

Parameters:path (str) – the path that the file will be created
Returns:first character that was written to the fifo
Return type:str
generate_core()
generate_gdb_connect_cmds()
generate_gdb_connect_sh()
handle_break_hit(response)
handle_fatal_signal(response)
run(timeout=None)
wait_for_exit()

Waits until debugger receives a message about the binary exit

class avocado.utils.process.SubProcess(cmd, verbose=True, allow_output_check='all', shell=False, env=None)

Bases: object

Run a subprocess in the background, collecting stdout/stderr streams.

Creates the subprocess object, stdout/err, reader threads and locks.

Parameters:
  • cmd (str) – Command line to run.
  • verbose (bool) – Whether to log the command run and stdout/stderr.
  • allow_output_check (str) – Whether to log the command stream outputs (stdout and stderr) in the test stream files. Valid values: ‘stdout’, for allowing only standard output, ‘stderr’, to allow only standard error, ‘all’, to allow both standard output and error (default), and ‘none’, to allow none to be recorded.
  • shell (bool) – Whether to run the subprocess in a subshell.
  • env (dict) – Use extra environment variables.
get_stderr()

Get the full stderr of the subprocess so far.

Returns:Standard error of the process.
Return type:str
get_stdout()

Get the full stdout of the subprocess so far.

Returns:Standard output of the process.
Return type:str
kill()

Send a signal.SIGKILL to the process.

poll()

Call the subprocess poll() method, fill results if rc is not None.

run(timeout=None, sig=15)

Start a process and wait for it to end, returning the result attr.

If the process was already started using .start(), this will simply wait for it to end.

Parameters:
  • timeout (float) – Time (seconds) we’ll wait until the process is finished. If it’s not, we’ll try to terminate it and get a status.
  • sig (int) – Signal to send to the process in case it did not end after the specified timeout.
Returns:

The command result object.

Return type:

A CmdResult instance.

send_signal(sig)

Send the specified signal to the process.

Parameters:sig – Signal to send.
start()

Start running the subprocess.

This method is particularly useful for background processes, since you can start the subprocess and not block your test flow.

Returns:Subprocess PID.
Return type:int
stop()

Stop background subprocess.

Call this method to terminate the background subprocess and wait for it results.

terminate()

Send a signal.SIGTERM to the process.

wait()

Call the subprocess poll() method, fill results if rc is not None.

avocado.utils.process.UNDEFINED_BEHAVIOR_EXCEPTION = None

Exception to be raised when users of this API need to know that the execution of a given process resulted in undefined behavior. One concrete example when a user, in an interactive session, let the inferior process exit before before avocado resumed the debugger session. Since the information is unknown, and the behavior is undefined, this situation will be flagged by an exception.

avocado.utils.process.WRAP_PROCESS = None

The global wrapper. If set, run every process under this wrapper.

avocado.utils.process.WRAP_PROCESS_NAMES_EXPR = []

Set wrapper per program names. A list of wrappers and program names. Format: [ (‘/path/to/wrapper.sh’, ‘progname’), ... ]

class avocado.utils.process.WrapSubProcess(cmd, verbose=True, allow_output_check='all', shell=False, env=None, wrapper=None)

Bases: avocado.utils.process.SubProcess

Wrap subprocess inside an utility program.

avocado.utils.process.get_children_pids(ppid)

Get all PIDs of children/threads of parent ppid param ppid: parent PID return: list of PIDs of all children/threads of ppid

avocado.utils.process.get_sub_process_klass(cmd)

Which sub process implementation should be used

Either the regular one, or the GNU Debugger version

Parameters:cmd – the command arguments, from where we extract the binary name
avocado.utils.process.kill_process_by_pattern(pattern)

Send SIGTERM signal to a process with matched pattern.

Parameters:pattern – normally only matched against the process name
avocado.utils.process.kill_process_tree(pid, sig=9)

Signal a process and all of its children.

If the process does not exist – return.

Parameters:
  • pid – The pid of the process to signal.
  • sig – The signal to send to the processes.
avocado.utils.process.pid_exists(pid)

Return True if a given PID exists.

Parameters:pid – Process ID number.
avocado.utils.process.process_in_ptree_is_defunct(ppid)

Verify if any processes deriving from PPID are in the defunct state.

Attempt to verify if parent process and any children from PPID is defunct (zombie) or not.

Parameters:ppid – The parent PID of the process to verify.
avocado.utils.process.run(cmd, timeout=None, verbose=True, ignore_status=False, allow_output_check='all', shell=False, env=None)

Run a subprocess, returning a CmdResult object.

Parameters:
  • cmd (str) – Command line to run.
  • timeout (float) – Time limit in seconds before attempting to kill the running process. This function will take a few seconds longer than ‘timeout’ to complete if it has to kill the process.
  • verbose (bool) – Whether to log the command run and stdout/stderr.
  • ignore_status (bool) – Whether to raise an exception when command returns =! 0 (False), or not (True).
  • allow_output_check (str) – Whether to log the command stream outputs (stdout and stderr) in the test stream files. Valid values: ‘stdout’, for allowing only standard output, ‘stderr’, to allow only standard error, ‘all’, to allow both standard output and error (default), and ‘none’, to allow none to be recorded.
  • shell (bool) – Whether to run the command on a subshell
  • env (dict) – Use extra environment variables
Returns:

An CmdResult object.

Raise:

CmdError, if ignore_status=False.

avocado.utils.process.safe_kill(pid, signal)

Attempt to send a signal to a given process that may or may not exist.

Parameters:signal – Signal number.
avocado.utils.process.should_run_inside_gdb(cmd)

Wether the given command should be run inside the GNU debugger

Parameters:cmd – the command arguments, from where we extract the binary name
avocado.utils.process.should_run_inside_wrapper(cmd)

Wether the given command should be run inside the wrapper utility.

Parameters:cmd – the command arguments, from where we extract the binary name
avocado.utils.process.split_gdb_expr(expr)

Splits a GDB expr into (binary_name, breakpoint_location)

Returns avocado.gdb.GDB.DEFAULT_BREAK as the default breakpoint if one is not given.

Parameters:expr (str) – an expression of the form <binary_name>[:<breakpoint>]
Returns:a (binary_name, breakpoint_location) tuple
Return type:tuple
avocado.utils.process.system(cmd, timeout=None, verbose=True, ignore_status=False, allow_output_check='all', shell=False, env=None)

Run a subprocess, returning its exit code.

Parameters:
  • cmd (str) – Command line to run.
  • timeout (float) – Time limit in seconds before attempting to kill the running process. This function will take a few seconds longer than ‘timeout’ to complete if it has to kill the process.
  • verbose (bool) – Whether to log the command run and stdout/stderr.
  • ignore_status (bool) – Whether to raise an exception when command returns =! 0 (False), or not (True).
  • allow_output_check (str) – Whether to log the command stream outputs (stdout and stderr) in the test stream files. Valid values: ‘stdout’, for allowing only standard output, ‘stderr’, to allow only standard error, ‘all’, to allow both standard output and error (default), and ‘none’, to allow none to be recorded.
  • shell (bool) – Whether to run the command on a subshell
  • env (dict) – Use extra environment variables.
Returns:

Exit code.

Return type:

int

Raise:

CmdError, if ignore_status=False.

avocado.utils.process.system_output(cmd, timeout=None, verbose=True, ignore_status=False, allow_output_check='all', shell=False, env=None)

Run a subprocess, returning its output.

Parameters:
  • cmd (str) – Command line to run.
  • timeout (float) – Time limit in seconds before attempting to kill the running process. This function will take a few seconds longer than ‘timeout’ to complete if it has to kill the process.
  • verbose (bool) – Whether to log the command run and stdout/stderr.
  • ignore_status – Whether to raise an exception when command returns =! 0 (False), or not (True).
  • allow_output_check (str) – Whether to log the command stream outputs (stdout and stderr) in the test stream files. Valid values: ‘stdout’, for allowing only standard output, ‘stderr’, to allow only standard error, ‘all’, to allow both standard output and error (default), and ‘none’, to allow none to be recorded.
  • shell (bool) – Whether to run the command on a subshell
  • env (dict) – Use extra environment variables
Returns:

Command output.

Return type:

str

Raise:

CmdError, if ignore_status=False.

avocado.utils.runtime module

Module that contains runtime configuration

avocado.utils.runtime.CURRENT_JOB = None

Sometimes it’s useful for the framework and API to know about the job that is currently running, if one exists

avocado.utils.runtime.CURRENT_TEST = None

Sometimes it’s useful for the framework and API to know about the test that is currently running, if one exists

avocado.utils.script module

Module to handle scripts creation.

class avocado.utils.script.Script(path, content, mode=509)

Bases: object

Class that represents a script.

Creates an instance of Script.

Note that when the instance inside a with statement, it will automatically call save() and then remove() for you.

Parameters:
  • path – the script file name.
  • content – the script content.
  • mode – set file mode, default to 0775.
remove()

Remove script from the file system.

Returns:True if script has been removed, otherwise False.
save()

Store script to file system.

Returns:True if script has been stored, otherwise False.
class avocado.utils.script.TemporaryScript(name, content, prefix='avocado_script', mode=509)

Bases: avocado.utils.script.Script

Class that represents a temporary script.

Creates an instance of TemporaryScript.

Note that when the instance inside a with statement, it will automatically call save() and then remove() for you.

When the instance object is garbage collected, it will automatically call remove() for you.

Parameters:
  • name – the script file name.
  • content – the script content.
  • prefix – prefix for the temporary directory name.
  • mode – set file mode, default to 0775.
remove()
avocado.utils.script.make_script(path, content, mode=509)

Creates a new script stored in the file system.

Parameters:
  • path – the script file name.
  • contet – the script content.
  • mode – set file mode, default to 0775.
Returns:

the script path.

avocado.utils.script.make_temp_script(name, content, prefix='avocado_script', mode=509)

Creates a new temporary script stored in the file system.

Parameters:
  • path – the script file name.
  • contet – the script content.
  • prefix – the directory prefix Default to ‘avocado_script’.
  • mode – set file mode, default to 0775.
Returns:

the script path.

avocado.utils.service module

avocado.utils.service.ServiceManager(run=<function run>)

Detect which init program is being used, init or systemd and return a class has methods to start/stop services.

# Get the system service manager >> service_manager = ServiceManager()

# Stating service/unit “sshd” >> service_manager.start(“sshd”)

# Getting a list of available units >> units = service_manager.list()

# Disabling and stopping a list of services >> services_to_disable = [‘ntpd’, ‘httpd’]

>> for s in services_to_disable: >> service_manager.disable(s) >> service_manager.stop(s)

Returns:SysVInitServiceManager or SystemdServiceManager
Return type:_GenericServiceManager
avocado.utils.service.SpecificServiceManager(service_name, run=<function run>)

# Get the specific service manager for sshd >>> sshd = SpecificServiceManager(“sshd”) >>> sshd.start() >>> sshd.stop() >>> sshd.reload() >>> sshd.restart() >>> sshd.condrestart() >>> sshd.status() >>> sshd.enable() >>> sshd.disable() >>> sshd.is_enabled()

Parameters:service_name (str) – systemd unit or init.d service to manager
Returns:SpecificServiceManager that has start/stop methods
Return type:_SpecificServiceManager
avocado.utils.service.convert_systemd_target_to_runlevel(target)

Convert systemd target to runlevel.

Parameters:target (str) – systemd target
Returns:sys_v runlevel
Return type:str
Raises ValueError:
 when systemd target is unknown
avocado.utils.service.convert_sysv_runlevel(level)

Convert runlevel to systemd target.

Parameters:level (str or int) – sys_v runlevel
Returns:systemd target
Return type:str
Raises ValueError:
 when runlevel is unknown
avocado.utils.service.get_name_of_init(run=<function run>)

Determine what executable is PID 1, aka init by checking /proc/1/exe This init detection will only run once and cache the return value.

Returns:executable name for PID 1, aka init
Return type:str
avocado.utils.service.service_manager(run=<function run>)

Detect which init program is being used, init or systemd and return a class has methods to start/stop services.

# Get the system service manager >> service_manager = ServiceManager()

# Stating service/unit “sshd” >> service_manager.start(“sshd”)

# Getting a list of available units >> units = service_manager.list()

# Disabling and stopping a list of services >> services_to_disable = [‘ntpd’, ‘httpd’]

>> for s in services_to_disable: >> service_manager.disable(s) >> service_manager.stop(s)

Returns:SysVInitServiceManager or SystemdServiceManager
Return type:_GenericServiceManager
avocado.utils.service.specific_service_manager(service_name, run=<function run>)

# Get the specific service manager for sshd >>> sshd = SpecificServiceManager(“sshd”) >>> sshd.start() >>> sshd.stop() >>> sshd.reload() >>> sshd.restart() >>> sshd.condrestart() >>> sshd.status() >>> sshd.enable() >>> sshd.disable() >>> sshd.is_enabled()

Parameters:service_name (str) – systemd unit or init.d service to manager
Returns:SpecificServiceManager that has start/stop methods
Return type:_SpecificServiceManager
avocado.utils.service.sys_v_init_command_generator(command)

Generate lists of command arguments for sys_v style inits.

Parameters:command (str) – start,stop,restart, etc.
Returns:list of commands to pass to process.run or similar function
Return type:builtin.list
avocado.utils.service.sys_v_init_result_parser(command)

Parse results from sys_v style commands.

command status: return true if service is running. command is_enabled: return true if service is enalbled. command list: return a dict from service name to status. command others: return true if operate success.

Parameters:command (str.) – command.
Returns:different from the command.
avocado.utils.service.systemd_command_generator(command)

Generate list of command line argument strings for systemctl.

One argument per string for compatibility Popen

WARNING: If systemctl detects that it is running on a tty it will use color, pipe to $PAGER, change column sizes and not truncate unit names. Use –no-pager to suppress pager output, or set PAGER=cat in the environment. You may need to take other steps to suppress color output. See https://bugzilla.redhat.com/show_bug.cgi?id=713567

Parameters:command (str) – start,stop,restart, etc.
Returns:List of command and arguments to pass to process.run or similar functions
Return type:builtin.list
avocado.utils.service.systemd_result_parser(command)

Parse results from systemd style commands.

command status: return true if service is running. command is_enabled: return true if service is enalbled. command list: return a dict from service name to status. command others: return true if operate success.

Parameters:command (str.) – command.
Returns:different from the command.

avocado.utils.software_manager module

Software package management library.

This is an abstraction layer on top of the existing distributions high level package managers. It supports package operations useful for testing purposes, and multiple high level package managers (here called backends). If you want to make this lib to support your particular package manager/distro, please implement the given backend class.

author:Higor Vieira Alves <halves@br.ibm.com>
author:Lucas Meneghel Rodrigues <lmr@redhat.com>
author:Ramon de Carvalho Valle <rcvalle@br.ibm.com>
copyright:IBM 2008-2009
copyright:Red Hat 2009-2014
class avocado.utils.software_manager.AptBackend

Bases: avocado.utils.software_manager.DpkgBackend

Implements the apt backend for software manager.

Set of operations for the apt package manager, commonly found on Debian and Debian based distributions, such as Ubuntu Linux.

Initializes the base command and the debian package repository.

add_repo(repo)

Add an apt repository.

Parameters:repo – Repository string. Example: ‘deb http://archive.ubuntu.com/ubuntu/ maverick universe’
install(name)

Installs package [name].

Parameters:name – Package name.
provides(path)

Return a list of packages that provide [path].

Parameters:path – File path.
remove(name)

Remove package [name].

Parameters:name – Package name.
remove_repo(repo)

Remove an apt repository.

Parameters:repo – Repository string. Example: ‘deb http://archive.ubuntu.com/ubuntu/ maverick universe’
upgrade(name=None)

Upgrade all packages of the system with eventual new versions.

Optionally, upgrade individual packages.

Parameters:name (str) – optional parameter wildcard spec to upgrade
class avocado.utils.software_manager.BaseBackend

Bases: object

This class implements all common methods among backends.

install_what_provides(path)

Installs package that provides [path].

Parameters:path – Path to file.
class avocado.utils.software_manager.DpkgBackend

Bases: avocado.utils.software_manager.BaseBackend

This class implements operations executed with the dpkg package manager.

dpkg is a lower level package manager, used by higher level managers such as apt and aptitude.

INSTALLED_OUTPUT = 'install ok installed'
PACKAGE_TYPE = 'deb'
check_installed(name)
list_all()

List all packages available in the system.

list_files(package)

List files installed by package [package].

Parameters:package – Package name.
Returns:List of paths installed by package.
class avocado.utils.software_manager.RpmBackend

Bases: avocado.utils.software_manager.BaseBackend

This class implements operations executed with the rpm package manager.

rpm is a lower level package manager, used by higher level managers such as yum and zypper.

PACKAGE_TYPE = 'rpm'
SOFTWARE_COMPONENT_QRY = 'rpm %{NAME} %{VERSION} %{RELEASE} %{SIGMD5} %{ARCH}'
check_installed(name, version=None, arch=None)

Check if package [name] is installed.

Parameters:
  • name – Package name.
  • version – Package version.
  • arch – Package architecture.
list_all(software_components=True)

List all installed packages.

Parameters:software_components – log in a format suitable for the SoftwareComponent schema
list_files(name)

List files installed on the system by package [name].

Parameters:name – Package name.
class avocado.utils.software_manager.SoftwareManager

Bases: object

Package management abstraction layer.

It supports a set of common package operations for testing purposes, and it uses the concept of a backend, a helper class that implements the set of operations of a given package management tool.

Lazily instantiate the object

class avocado.utils.software_manager.SystemInspector

Bases: object

System inspector class.

This may grow up to include more complete reports of operating system and machine properties.

Probe system, and save information for future reference.

get_package_management()

Determine the supported package management systems present on the system. If more than one package management system installed, try to find the best supported system.

class avocado.utils.software_manager.YumBackend

Bases: avocado.utils.software_manager.RpmBackend

Implements the yum backend for software manager.

Set of operations for the yum package manager, commonly found on Yellow Dog Linux and Red Hat based distributions, such as Fedora and Red Hat Enterprise Linux.

Initializes the base command and the yum package repository.

add_repo(url)

Adds package repository located on [url].

Parameters:url – Universal Resource Locator of the repository.
install(name)

Installs package [name]. Handles local installs.

provides(name)

Returns a list of packages that provides a given capability.

Parameters:name – Capability name (eg, ‘foo’).
remove(name)

Removes package [name].

Parameters:name – Package name (eg. ‘ipython’).
remove_repo(url)

Removes package repository located on [url].

Parameters:url – Universal Resource Locator of the repository.
upgrade(name=None)

Upgrade all available packages.

Optionally, upgrade individual packages.

Parameters:name (str) – optional parameter wildcard spec to upgrade
class avocado.utils.software_manager.ZypperBackend

Bases: avocado.utils.software_manager.RpmBackend

Implements the zypper backend for software manager.

Set of operations for the zypper package manager, found on SUSE Linux.

Initializes the base command and the yum package repository.

add_repo(url)

Adds repository [url].

Parameters:url – URL for the package repository.
install(name)

Installs package [name]. Handles local installs.

Parameters:name – Package Name.
provides(name)

Searches for what provides a given file.

Parameters:name – File path.
remove(name)

Removes package [name].

remove_repo(url)

Removes repository [url].

Parameters:url – URL for the package repository.
upgrade(name=None)

Upgrades all packages of the system.

Optionally, upgrade individual packages.

Parameters:name (str) – Optional parameter wildcard spec to upgrade
avocado.utils.software_manager.install_distro_packages(distro_pkg_map, interactive=False)

Installs packages for the currently running distribution

This utility function checks if the currently running distro is a key in the distro_pkg_map dictionary, and if there is a list of packages set as its value.

If these conditions match, the packages will be installed using the software manager interface, thus the native packaging system if the currenlty running distro.

Parameters:distro_pkg_map (dict) – mapping of distro name, as returned by utils.get_os_vendor(), to a list of package names
Returns:True if any packages were actually installed, False otherwise

avocado.utils.stacktrace module

Traceback standard module plus some additional APIs.

avocado.utils.stacktrace.log_exc_info(exc_info, logger='root')

Log exception info to logger_name.

Parameters:
  • exc_info – Exception info produced by sys.exc_info()
  • logger – Name of the logger (defaults to root)
avocado.utils.stacktrace.log_message(message, logger='root')

Log message to logger.

Parameters:
  • message – Message
  • logger – Name of the logger (defaults to root)
avocado.utils.stacktrace.prepare_exc_info(exc_info)

Prepare traceback info.

Parameters:exc_info – Exception info produced by sys.exc_info()
avocado.utils.stacktrace.tb_info(exc_info)

Prepare traceback info.

Parameters:exc_info – Exception info produced by sys.exc_info()

avocado.utils.wait module

avocado.utils.wait.wait_for(func, timeout, first=0.0, step=1.0, text=None)

Wait until func() evaluates to True.

If func() evaluates to True before timeout expires, return the value of func(). Otherwise return None.

Parameters:
  • timeout – Timeout in seconds
  • first – Time to sleep before first attempt
  • steps – Time to sleep between attempts in seconds
  • text – Text to print while waiting, for debug purposes

Module contents