Internal (Core) APIs

Internal APIs that may be of interest to Avocado hackers.

Submodules

avocado.core.app module

avocado.core.data_dir module

Library used to let avocado tests find important paths in the system.

The general reasoning to find paths is:

  • When running in tree, don’t honor avocado.conf. Also, we get to run/display the example tests shipped in tree.
  • When avocado.conf is in /etc/avocado, or ~/.config/avocado, then honor the values there as much as possible. If they point to a location where we can’t write to, use the next best location available.
  • The next best location is the default system wide one.
  • The next best location is the default user specific one.
avocado.core.data_dir.clean_tmp_files()

Try to clean the tmp directory by removing it.

This is a useful function for avocado entry points looking to clean after tests/jobs are done. If OSError is raised, silently ignore the error.

avocado.core.data_dir.create_job_logs_dir(logdir=None, unique_id=None)

Create a log directory for a job, or a stand alone execution of a test.

Parameters:
  • logdir – Base log directory, if None, use value from configuration.
  • unique_id – The unique identification. If None, create one.
Return type:

basestring

avocado.core.data_dir.get_base_dir()

Get the most appropriate base dir.

The base dir is the parent location for most of the avocado other important directories.

Examples:
  • Log directory
  • Data directory
  • Tests directory
avocado.core.data_dir.get_data_dir()

Get the most appropriate data dir location.

The data dir is the location where any data necessary to job and test operations are located.

Examples:
  • ISO files
  • GPG files
  • VM images
  • Reference bitmaps
avocado.core.data_dir.get_datafile_path(*args)

Get a path relative to the data dir.

Parameters:args – Arguments passed to os.path.join. Ex (‘images’, ‘jeos.qcow2’)
avocado.core.data_dir.get_logs_dir()

Get the most appropriate log dir location.

The log dir is where we store job/test logs in general.

avocado.core.data_dir.get_test_dir()

Get the most appropriate test location.

The test location is where we store tests written with the avocado API.

avocado.core.data_dir.get_tmp_dir()

Get the most appropriate tmp dir location.

The tmp dir is where artifacts produced by the test are kept.

Examples:
  • Copies of a test suite source code
  • Compiled test suite source code

avocado.core.dispatcher module

avocado.core.exceptions module

Exception classes, useful for tests, and other parts of the framework code.

exception avocado.core.exceptions.JobBaseException

Bases: exceptions.Exception

The parent of all job exceptions.

You should be never raising this, but just in case, we’ll set its status’ as FAIL.

status = 'FAIL'
exception avocado.core.exceptions.JobError

Bases: avocado.core.exceptions.JobBaseException

A generic error happened during a job execution.

status = 'ERROR'
exception avocado.core.exceptions.NotATestError

Bases: avocado.core.exceptions.TestBaseException

Indicates that the file is not a test.

Causes: Non executable, non python file or python module without an avocado test class in it.

status = 'NOT_A_TEST'
exception avocado.core.exceptions.OptionValidationError

Bases: exceptions.Exception

An invalid option was passed to the test runner

status = 'ERROR'
exception avocado.core.exceptions.TestAbortError

Bases: avocado.core.exceptions.TestBaseException

Indicates that the test was prematurely aborted.

status = 'ERROR'
exception avocado.core.exceptions.TestBaseException

Bases: exceptions.Exception

The parent of all test exceptions.

You should be never raising this, but just in case, we’ll set its status’ as FAIL.

status = 'FAIL'
exception avocado.core.exceptions.TestError

Bases: avocado.core.exceptions.TestBaseException

Indicates that the test was not fully executed and an error happened.

This is the sort of exception you raise if the test was partially executed and could not complete due to a setup, configuration, or another fatal condition.

status = 'ERROR'
exception avocado.core.exceptions.TestFail

Bases: avocado.core.exceptions.TestBaseException, exceptions.AssertionError

Indicates that the test failed.

TestFail inherits from AssertionError in order to keep compatibility with vanilla python unittests (they only consider failures the ones deriving from AssertionError).

status = 'FAIL'
exception avocado.core.exceptions.TestInterruptedError

Bases: avocado.core.exceptions.TestBaseException

Indicates that the test was interrupted by the user (Ctrl+C)

status = 'INTERRUPTED'
exception avocado.core.exceptions.TestNotFoundError

Bases: avocado.core.exceptions.TestBaseException

Indicates that the test was not found in the test directory.

status = 'ERROR'
exception avocado.core.exceptions.TestSetupFail

Bases: avocado.core.exceptions.TestBaseException

Indicates an error during a setup or cleanup procedure.

status = 'ERROR'
exception avocado.core.exceptions.TestSkipError

Bases: avocado.core.exceptions.TestBaseException

Indictates that the test is skipped.

Should be thrown when various conditions are such that the test is inappropriate. For example, inappropriate architecture, wrong OS version, program being tested does not have the expected capability (older version).

status = 'SKIP'
exception avocado.core.exceptions.TestTimeoutError

Bases: avocado.core.exceptions.TestBaseException

Indicates that the test did not finish before the timeout specified.

status = 'ERROR'
exception avocado.core.exceptions.TestWarn

Bases: avocado.core.exceptions.TestBaseException

Indicates that bad things (may) have happened, but not an explicit failure.

status = 'WARN'
avocado.core.exceptions.fail_on(exceptions=None)

Fail the test when decorated function produces exception of the specified type.

(For example, our method may raise IndexError on tested software failure. We can either try/catch it or use this decorator instead)

Parameters:exceptions – Tuple or single exception to be assumed as test fail [Exception]
Note:self.error and self.skip behavior remains intact
Note:To allow simple usage param “exceptions” must not be callable

avocado.core.exit_codes module

Avocado exit codes.

These codes are returned on the command line and may be used by applications that interface (that is, run) the Avocado command line application.

Besides main status about the execution of the command line application, these exit status may also give extra, although limited, information about test statuses.

avocado.core.exit_codes.AVOCADO_ALL_OK = 0

Both job and tests PASSed

avocado.core.exit_codes.AVOCADO_FAIL = 3

Something else went wrong and avocado failed (or crashed). Commonly used on command line validation errors.

avocado.core.exit_codes.AVOCADO_GENERIC_CRASH = -1

Avocado generic crash

avocado.core.exit_codes.AVOCADO_JOB_FAIL = 2

Something went wrong with the Job itself, by explicit avocado.core.exceptions.JobError exception.

avocado.core.exit_codes.AVOCADO_JOB_INTERRUPTED = 4

The job was explicitly interrupted. Usually this means that a user hit CTRL+C while the job was still running.

avocado.core.exit_codes.AVOCADO_TESTS_FAIL = 1

Job went fine, but some tests FAILed or ERRORed

avocado.core.html module

HTML output module.

class avocado.core.html.HTMLTestResult(job, force_html_file=None)

Bases: avocado.core.result.TestResult

HTML Test Result class.

Parameters:
  • job – Job which defines this result
  • force_html_file – Override the output html file location
command_line_arg_name = '--html'
end_test(state)

Called when the given test has been run.

Parameters:state (dict) – result of avocado.core.test.Test.get_state.
end_tests()

Called once after all tests are executed.

start_tests()

Called once before any tests are executed.

class avocado.core.html.ReportModel(json_input, html_output)

Bases: object

Prepares JSON that can be passed up to mustache for rendering.

Base JSON that comes from test results.

execution_time()
get(key, default)
hostname()
job_id()
logdir()
pass_rate()
passed()
results_dir(relative_links=True)
results_dir_basename()
sysinfo()
tests
total()
update(**kwargs)

Hook for updates not supported

avocado.core.html.check_resource_requirements()

Checks if necessary resource files to render the report are in place

Currently, only the template file is looked for

avocado.core.job module

Job module - describes a sequence of automated test operations.

class avocado.core.job.Job(args=None)

Bases: object

A Job is a set of operations performed on a test machine.

Most of the time, we are interested in simply running tests, along with setup operations and event recording.

Creates an instance of Job class.

Parameters:args – an instance of argparse.Namespace.
run()

Handled main job method. Runs a list of test URLs to its completion.

Note that the behavior is as follows:

  • If urls is provided alone, just make a simple list with no specific params (all tests use default params).
  • If urls and multiplex_files are provided, multiplex provides params and variants to all tests it can.
  • If multiplex_files are provided alone, just use the matrix produced by the file

The test runner figures out which tests need to be run on an empty urls list by assuming the first component of the shortname is the test url.

Returns:Integer with overall job status. See avocado.core.exit_codes for more information.
class avocado.core.job.TestProgram

Bases: object

Convenience class to make avocado test modules executable.

parseArgs(argv)
runTests()
avocado.core.job.main

alias of TestProgram

avocado.core.job_id module

avocado.core.job_id.create_unique_job_id()

Create a 40 digit hex number to be used as a job ID string. (similar to SHA1)

Returns:40 digit hex number string
Return type:str

avocado.core.jsonresult module

JSON output module.

class avocado.core.jsonresult.JSONTestResult(job, force_json_file=None)

Bases: avocado.core.result.TestResult

JSON Test Result class.

Parameters:
  • job – Job which defines this result
  • force_json_file – Override the json output file location
command_line_arg_name = '--json'
end_test(state)

Called when the given test has been run.

Parameters:state (dict) – result of avocado.core.test.Test.get_state.
end_tests()

Called once after all tests are executed.

start_tests()

Called once before any tests are executed.

avocado.core.loader module

Test loader module.

class avocado.core.loader.AccessDeniedPath

Bases: object

Dummy object to represent url pointing to a inaccessible path

Bases: object

Dummy object to represent url pointing to a BrokenSymlink path

class avocado.core.loader.ExternalLoader(args, extra_params)

Bases: avocado.core.loader.TestLoader

External-runner loader class

discover(url, which_tests=False)
Parameters:
  • url – arguments passed to the external_runner
  • which_tests – Limit tests to be displayed (ALL, AVAILABLE or DEFAULT)
Returns:

list of matching tests

static get_decorator_mapping()
static get_type_label_mapping()
name = 'external'
class avocado.core.loader.FileLoader(args, extra_params)

Bases: avocado.core.loader.TestLoader

Test loader class.

discover(url, which_tests=False)

Discover (possible) tests from a directory.

Recursively walk in a directory and find tests params. The tests are returned in alphabetic order.

Afterwards when “allowed_test_types” is supplied it verifies if all found tests are of the allowed type. If not return None (even on partial match).

Parameters:
  • url – the directory path to inspect.
  • which_tests – Limit tests to be displayed (ALL, AVAILABLE or DEFAULT)
Returns:

list of matching tests

static get_decorator_mapping()
static get_type_label_mapping()
name = 'file'
class avocado.core.loader.FilteredOut

Bases: object

Dummy object to represent test filtered out by the optional mask

exception avocado.core.loader.InvalidLoaderPlugin

Bases: avocado.core.loader.LoaderError

Invalid loader plugin

exception avocado.core.loader.LoaderError

Bases: exceptions.Exception

Loader exception

exception avocado.core.loader.LoaderUnhandledUrlError(unhandled_urls, plugins)

Bases: avocado.core.loader.LoaderError

Urls not handled by any loader

class avocado.core.loader.TestLoader(args, extra_params)

Bases: object

Base for test loader classes

discover(url, which_tests=False)

Discover (possible) tests from an url.

Parameters:
  • url (str) – the url to be inspected.
  • which_tests – Limit tests to be displayed (ALL, AVAILABLE or DEFAULT)
Returns:

a list of test matching the url as params.

static get_decorator_mapping()

Get label mapping for display in test listing.

Returns:Dict {TestClass: decorator function}
get_extra_listing()
static get_type_label_mapping()

Get label mapping for display in test listing.

Returns:Dict {TestClass: ‘TEST_LABEL_STRING’}
name = None
class avocado.core.loader.TestLoaderProxy

Bases: object

discover(urls, which_tests=False)

Discover (possible) tests from test urls.

Parameters:
  • urls (builtin.list) – a list of tests urls; if [] use plugin defaults
  • which_tests – Limit tests to be displayed (ALL, AVAILABLE or DEFAULT)
Returns:

A list of test factories (tuples (TestClass, test_params))

get_base_keywords()
get_decorator_mapping()
get_extra_listing()
get_type_label_mapping()
load_plugins(args)
load_test(test_factory)

Load test from the test factory.

Parameters:test_factory – a pair of test class and parameters.
Returns:an instance of avocado.core.test.Test.
register_plugin(plugin)
avocado.core.loader.add_loader_options(parser)

avocado.core.multiplexer module

Multiplex and create variants.

class avocado.core.multiplexer.AvocadoParam(leaves, name)

Bases: object

This is a single slice params. It can contain multiple leaves and tries to find matching results.

Parameters:
  • leaves – this slice’s leaves
  • name – this slice’s name (identifier used in exceptions)
get_or_die(path, key)

Get a value or raise exception if not present :raise NoMatchError: When no matches :raise KeyError: When value is not certain (multiple matches)

iteritems()

Very basic implementation which iterates through __ALL__ params, which generates lots of duplicite entries due to inherited values.

str_leaves_variant

String with identifier and all params

class avocado.core.multiplexer.AvocadoParams(leaves, test_id, tag, mux_path, default_params)

Bases: object

Params object used to retrieve params from given path. It supports absolute and relative paths. For relative paths one can define multiple paths to search for the value. It contains compatibility wrapper to act as the original avocado Params, but by special usage you can utilize the new API. See get() docstring for details.

You can also iterate through all keys, but this can generate quite a lot of duplicate entries inherited from ancestor nodes. It shouldn’t produce false values, though.

In this version each new “get()” call is logged into “avocado.test” log. This is subject of change (separate file, perhaps)

Parameters:
  • leaves – List of TreeNode leaves defining current variant
  • test_id – test id
  • tag – test tag
  • mux_path – list of entry points
  • default_params – dict of params used when no matches found
get(key, path=None, default=None)

Retrieve value associated with key from params :param key: Key you’re looking for :param path: namespace [‘*’] :param default: default value when not found :raise KeyError: In case of multiple different values (params clash)

iteritems()

Iterate through all available params and yield origin, key and value of each unique value.

log(key, path, default, value)

Predefined format for displaying params query

objects(key, path=None)

Return the names of objects defined using a given key.

Parameters:key – The name of the key whose value lists the objects (e.g. ‘nics’).
class avocado.core.multiplexer.Mux(args)

Bases: object

This is a multiplex object which multiplexes the test_suite.

get_number_of_tests(test_suite)
Returns:overall number of tests * multiplex variants
itertests(template)

Processes the template and yields test definition with proper params

class avocado.core.multiplexer.MuxTree(root)

Bases: object

Object representing part of the tree from the root to leaves or another multiplex domain. Recursively it creates multiplexed variants of the full tree.

Parameters:root – Root of this tree slice
exception avocado.core.multiplexer.NoMatchError

Bases: exceptions.KeyError

avocado.core.multiplexer.yaml2tree(input_yamls, filter_only=None, filter_out=None, debug=False)

avocado.core.output module

Manages output and logging in avocado applications.

avocado.core.output.BUILTIN_STREAMS = {'test': 'test output', 'debug': 'tracebacks and other debugging info', 'app': 'application output', 'early': 'early logging of other streams, including test (very verbose)', 'remote': 'fabric/paramiko debug'}

Builtin special keywords to enable set of logging streams

avocado.core.output.BUILTIN_STREAM_SETS = {'all': 'all builtin streams', 'none': 'disables regular output (leaving only errors enabled)'}

Groups of builtin streams

class avocado.core.output.FilterInfoAndLess(name='')

Bases: logging.Filter

Initialize a filter.

Initialize with the name of the logger which, together with its children, will have its events allowed through the filter. If no name is specified, allow every event.

filter(record)
class avocado.core.output.FilterWarnAndMore(name='')

Bases: logging.Filter

Initialize a filter.

Initialize with the name of the logger which, together with its children, will have its events allowed through the filter. If no name is specified, allow every event.

filter(record)
class avocado.core.output.LoggingFile(prefix='', level=10, logger=[<logging.RootLogger object at 0x7f8399820ad0>])

Bases: object

File-like object that will receive messages pass them to logging.

Constructor. Sets prefixes and which logger is going to be used.

:param prefix - The prefix for each line logged by this object.

flush()
isatty()
write(data)

” Writes data only if it constitutes a whole line. If it’s not the case, store it in a buffer and wait until we have a complete line. :param data - Raw data (a string) that will be processed.

writelines(lines)

” Writes itertable of lines

Parameters:lines – An iterable of strings that will be processed.
class avocado.core.output.MemStreamHandler(stream=None)

Bases: logging.StreamHandler

Handler that stores all records in self.log (shared in all instances)

Initialize the handler.

If stream is not specified, sys.stderr is used.

emit(record)
flush()

This is in-mem object, it does not require flushing

log = []
exception avocado.core.output.PagerNotFoundError

Bases: exceptions.Exception

class avocado.core.output.Paginator

Bases: object

Paginator that uses less to display contents on the terminal.

Contains cleanup handling for when user presses ‘q’ (to quit less).

close()
write(msg)
class avocado.core.output.ProgressStreamHandler(stream=None)

Bases: logging.StreamHandler

Handler class that allows users to skip new lines on each emission.

Initialize the handler.

If stream is not specified, sys.stderr is used.

emit(record)
avocado.core.output.STD_OUTPUT = <avocado.core.output.StdOutput object>

Allows modifying the sys.stdout/sys.stderr

class avocado.core.output.StdOutput

Bases: object

Class to modify sys.stdout/sys.stderr

close()

Enable original sys.stdout/sys.stderr and cleanup

enable_outputs()

Enable sys.stdout/sys.stderr (either with 2 streams or with paginator)

enable_paginator()

Enable paginator

enable_stderr()

Enable sys.stderr and disable sys.stdout

fake_outputs()

Replace sys.stdout/sys.stderr with in-memory-objects

print_records()

Prints all stored messages as they occured into streams they were produced for.

records = []

List of records of stored output when stdout/stderr is disabled

avocado.core.output.TERM_SUPPORT = <avocado.core.output.TermSupport object>

Transparently handles colored terminal, when one is used

class avocado.core.output.TermSupport

Bases: object

COLOR_BLUE = '\x1b[94m'
COLOR_DARKGREY = '\x1b[90m'
COLOR_GREEN = '\x1b[92m'
COLOR_RED = '\x1b[91m'
COLOR_YELLOW = '\x1b[93m'
CONTROL_END = '\x1b[0m'
ESCAPE_CODES = ['\x1b[94m', '\x1b[92m', '\x1b[93m', '\x1b[91m', '\x1b[90m', '\x1b[0m', '\x1b[1D', '\x1b[1C']

Class to help applications to colorize their outputs for terminals.

This will probe the current terminal and colorize ouput only if the stdout is in a tty or the terminal type is recognized.

MOVE_BACK = '\x1b[1D'
MOVE_FORWARD = '\x1b[1C'
disable()

Disable colors from the strings output by this class.

error_str()

Print a error string (red colored).

If the output does not support colors, just return the original string.

fail_header_str(msg)

Print a fail header string (red colored).

If the output does not support colors, just return the original string.

fail_str()

Print a fail string (red colored).

If the output does not support colors, just return the original string.

header_str(msg)

Print a header string (blue colored).

If the output does not support colors, just return the original string.

healthy_str(msg)

Print a healthy string (green colored).

If the output does not support colors, just return the original string.

interrupt_str()

Print an interrupt string (red colored).

If the output does not support colors, just return the original string.

partial_str(msg)

Print a string that denotes partial progress (yellow colored).

If the output does not support colors, just return the original string.

pass_str()

Print a pass string (green colored).

If the output does not support colors, just return the original string.

skip_str()

Print a skip string (yellow colored).

If the output does not support colors, just return the original string.

warn_header_str(msg)

Print a warning header string (yellow colored).

If the output does not support colors, just return the original string.

warn_str()

Print an warning string (yellow colored).

If the output does not support colors, just return the original string.

class avocado.core.output.Throbber

Bases: object

Produces a spinner used to notify progress in the application UI.

MOVES = ['', '', '', '']
STEPS = ['-', '\\', '|', '/']
render()
avocado.core.output.add_log_handler(logger, klass=<class 'logging.StreamHandler'>, stream=<open file '<stdout>', mode 'w'>, level=20, fmt='%(name)s: %(message)s')

Add handler to a logger.

Parameters:
  • logger_name – the name of a logging.Logger instance, that is, the parameter to logging.getLogger()
  • klass – Handler class (defaults to logging.StreamHandler)
  • stream – Logging stream, to be passed as an argument to klass (defaults to sys.stdout)
  • level – Log level (defaults to INFO`)
  • fmt – Logging format (defaults to %(name)s: %(message)s)
avocado.core.output.disable_log_handler(logger)
avocado.core.output.early_start()

Replace all outputs with in-memory handlers

avocado.core.output.reconfigure(args)

Adjust logging handlers accordingly to app args and re-log messages.

avocado.core.parser module

Avocado application command line parsing.

class avocado.core.parser.ArgumentParser(prog=None, usage=None, description=None, epilog=None, version=None, parents=[], formatter_class=<class 'argparse.HelpFormatter'>, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True)

Bases: argparse.ArgumentParser

Class to override argparse functions

error(message)
class avocado.core.parser.Parser

Bases: object

Class to Parse the command line arguments.

finish()

Finish the process of parsing arguments.

Side effect: set the final value for attribute args.

start()

Start to parsing arguments.

At the end of this method, the support for subparsers is activated. Side effect: update attribute args (the namespace).

avocado.core.remoter module

Module to provide remote operations.

class avocado.core.remoter.Remote(hostname, username=None, password=None, port=22, timeout=60, attempts=10, quiet=False)

Bases: object

Performs remote operations.

Creates an instance of Remote.

Parameters:
  • hostname – the hostname.
  • username – the username. Default: autodetect.
  • password – the password. Default: try to use public key.
  • timeout – remote command timeout, in seconds. Default: 60.
  • attempts – number of attempts to connect. Default: 10.
  • quiet – performs quiet operations. Default: True.
makedir(remote_path)

Create a directory.

Parameters:remote_path – the remote path to create.
receive_files(local_path, remote_path)

receive remote files.

Parameters:
  • local_path – the local path.
  • remote_path – the remote path.
run(command, ignore_status=False, timeout=60)

Run a remote command.

Parameters:command – the command string to execute.
Returns:the result of the remote program’s output.
Return type:avocado.utils.process.CmdResult.
Raises:fabric.exceptions.CommandTimeout – When timeout exhausted.
send_files(local_path, remote_path)

Send files to remote.

Parameters:
  • local_path – the local path.
  • remote_path – the remote path.
uptime()

Performs uptime (good to check connection).

Returns:the uptime string or empty string if fails.

avocado.core.replay module

avocado.core.replay.get_id(path, jobid)
avocado.core.replay.get_resultsdir(logdir, jobid)
avocado.core.replay.record(args, logdir, mux, urls=None)
avocado.core.replay.retrieve_args(resultsdir)
avocado.core.replay.retrieve_mux(resultsdir)
avocado.core.replay.retrieve_pwd(resultsdir)
avocado.core.replay.retrieve_replay_map(resultsdir, replay_filter)
avocado.core.replay.retrieve_urls(resultsdir)

avocado.core.result module

Contains the definition of the TestResult class, used for output in avocado.

It also contains the most basic test result class, HumanTestResult, used by the test runner.

class avocado.core.result.HumanTestResult(job)

Bases: avocado.core.result.TestResult

Human output Test result class.

end_test(state)
end_tests()

Called once after all tests are executed.

notify_progress(progress=False)
start_test(state)
start_tests()

Called once before any tests are executed.

exception avocado.core.result.InvalidOutputPlugin

Bases: exceptions.Exception

class avocado.core.result.TestResult(job)

Bases: object

Test result class, holder for test result information.

Creates an instance of TestResult.

Parameters:job – an instance of avocado.core.job.Job.
add_error(state)

Called when a test had a setup error.

Parameters:state (dict) – result of avocado.core.test.Test.get_state.
add_fail(state)

Called when a test fails.

Parameters:state (dict) – result of avocado.core.test.Test.get_state.
add_interrupt(state)

Called when a test is interrupted by the user.

Parameters:state (dict) – result of avocado.core.test.Test.get_state.
add_pass(state)

Called when a test succeeded.

Parameters:state (dict) – result of avocado.core.test.Test.get_state.
add_skip(state)

Called when a test is skipped.

Parameters:test – an instance of avocado.core.test.Test.
add_warn(state)

Called when a test had a warning.

Parameters:state (dict) – result of avocado.core.test.Test.get_state.
check_test(state)

Called once for a test to check status and report.

Parameters:test – A dict with test internal state
command_line_arg_name = None

Should be set by result plugins to inform users about output options inconsistencies given on the command line, and where these inconsistencies come from.

end_test(state)

Called when the given test has been run.

Parameters:state (dict) – result of avocado.core.test.Test.get_state.
end_tests()

Called once after all tests are executed.

start_test(state)

Called when the given test is about to run.

Parameters:state (dict) – result of avocado.core.test.Test.get_state.
start_tests()

Called once before any tests are executed.

class avocado.core.result.TestResultProxy

Bases: object

add_error(state)
add_fail(state)
add_output_plugin(plugin)
add_pass(state)
add_skip(state)
add_warn(state)
check_test(state)
end_test(state)
end_tests()
notify_progress(progress_from_test=False)
output_plugins_using_stdout()
start_test(state)
start_tests()
avocado.core.result.register_test_result_class(application_args, klass)

Register the given test result class to be loaded and enabled by the job

Parameters:
  • application_args (argparse.Namespace) – the parsed application command line arguments. This is currently being abused to hold various job settings and feature choices, such as the runner.
  • klass (a subclass of TestResult) – the test result class to enable

avocado.core.runner module

Test runner module.

class avocado.core.runner.TestRunner(job, test_result)

Bases: object

A test runner class that displays tests results.

Creates an instance of TestRunner class.

Parameters:
DEFAULT_TIMEOUT = 86400
run_suite(test_suite, mux, timeout=0, replay_map=None)

Run one or more tests and report with test result.

Parameters:
  • test_suite – a list of tests to run.
  • mux – the multiplexer.
  • timeout – maximum amount of time (in seconds) to execute.
Returns:

a list of test failures.

run_test(test_factory, queue, failures, job_deadline=0)

Run a test instance inside a subprocess.

Parameters:
  • test_factory (tuple of avocado.core.test.Test and dict.) – Test factory (test class and parameters).
  • queue (:class`multiprocessing.Queue` instance.) – Multiprocess queue.
  • failures (list.) – Store tests failed.
  • job_deadline (int.) – Maximum time to execute.
setup()

(Optional) initialization method for the test runner

tear_down()

(Optional) cleanup method for the test runner

class avocado.core.runner.TestStatus(job, queue)

Bases: object

Test status handler

Parameters:
  • job – Associated job
  • queue – test message queue
abort(proc, started, timeout, first, step)

Handle job abortion :param proc: The test’s process :param started: Time when the test started :param timeout: Timeout for waiting on status :param first: Delay before first check :param step: Step between checks for the status

early_status

Get early status

wait_for_early_status(proc, timeout)

Wait until early_status is obtained :param proc: test process :param timeout: timeout for early_state :raise exceptions.TestError: On timeout/error

avocado.core.safeloader module

Safe (AST based) test loader module utilities

avocado.core.safeloader.AVOCADO_DOCSTRING_TAG_RE = <_sre.SRE_Pattern object>

Gets the tag value from a string. Used to tag a test class in various ways

avocado.core.safeloader.find_class_and_methods(path, method_pattern=None, base_class=None)

Attempts to find methods names from a given Python source file

Parameters:
  • path (str) – path to a Python source code file
  • method_pattern – compiled regex to match against method name
  • base_class (str or None) – only consider classes that inherit from a given base class (or classes that inherit from any class if None is given)
avocado.core.safeloader.get_docstring_tag(docstring)

Returns the value of the avocado custom tag inside a docstring

Parameters:docstring (str) – the complete text used as documentation
avocado.core.safeloader.is_docstring_tag_disable(docstring)

Checks if there’s an avocado tag that disables its class as a Test class

Return type:bool
avocado.core.safeloader.is_docstring_tag_enable(docstring)

Checks if there’s an avocado tag that enables its class as a Test class

Return type:bool
avocado.core.safeloader.modules_imported_as(module)

Returns a mapping of imported module names wether using aliases or not

The goal of this utility function is to return the name of the import as used in the rest of the module, wether an aliased import was used or not.

For code such as:

>>> import foo as bar

This function should return {“foo”: “bar”}

And for code such as:

>>> import foo

It should return {“foo”: “foo”}

Please note that only global level imports are looked at. If there are imports defined, say, inside functions or class definitions, they will not be seen by this function.

Parameters:module (_ast.Module) – module, as parsed by ast.parse()
Returns:a mapping of names {<realname>: <alias>} of modules imported
Return type:dict

avocado.core.settings module

Reads the avocado settings from a .ini file (from python ConfigParser).

exception avocado.core.settings.ConfigFileNotFound(path_list)

Bases: avocado.core.settings.SettingsError

Error thrown when the main settings file could not be found.

class avocado.core.settings.Settings(config_path=None)

Bases: object

Simple wrapper around ConfigParser, with a key type conversion available.

Constructor. Tries to find the main settings file and load it.

Parameters:config_path – Path to a config file. Useful for unittesting.
get_value(section, key, key_type=<type 'str'>, default=<object object>, allow_blank=False)

Get value from key in a given config file section.

Parameters:
  • section – Config file section.
  • key – Config file key, relative to section.
  • key_type – Type of key. It can be either of: str, int, float, bool, list
  • default – Default value for the key, if none found.
  • allow_blank – Whether an empty value for the key is allowed.
Returns:

value, if one available in the config. default value, if one provided.

Raises:

SettingsError, in case no default was provided.

no_default = <object object>
process_config_path(pth)
exception avocado.core.settings.SettingsError

Bases: exceptions.Exception

Base settings error.

exception avocado.core.settings.SettingsValueError

Bases: avocado.core.settings.SettingsError

Error thrown when we could not convert successfully a key to a value.

avocado.core.settings.convert_value_type(value, value_type)

Convert a string value to a given value type.

Parameters:
  • value (str.) – Value we want to convert.
  • value_type (str or type.) – Type of the value we want to convert.
Returns:

Converted value type.

Return type:

Dependent on value_type.

Raise:

TypeError, in case it was not possible to convert values.

avocado.core.status module

Maps the different status strings in avocado to booleans.

This is used by methods and functions to return a cut and dry answer to wether a test or a job in avocado PASSed or FAILed.

avocado.core.sysinfo module

class avocado.core.sysinfo.Collectible(logf)

Bases: object

Abstract class for representing collectibles by sysinfo.

readline(logdir)

Read one line of the collectible object.

Parameters:logdir – Path to a log directory.
class avocado.core.sysinfo.Command(cmd, logf=None, compress_log=False)

Bases: avocado.core.sysinfo.Collectible

Collectible command.

Parameters:
  • cmd – String with the command.
  • logf – Basename of the file where output is logged (optional).
  • compress_logf – Wether to compress the output of the command.
run(logdir)

Execute the command as a subprocess and log its output in logdir.

Parameters:logdir – Path to a log directory.
class avocado.core.sysinfo.Daemon(cmd, logf=None, compress_log=False)

Bases: avocado.core.sysinfo.Command

Collectible daemon.

Parameters:
  • cmd – String with the daemon command.
  • logf – Basename of the file where output is logged (optional).
  • compress_logf – Wether to compress the output of the command.
run(logdir)

Execute the daemon as a subprocess and log its output in logdir.

Parameters:logdir – Path to a log directory.
stop()

Stop daemon execution.

class avocado.core.sysinfo.LogWatcher(path, logf=None)

Bases: avocado.core.sysinfo.Collectible

Keep track of the contents of a log file in another compressed file.

This object is normally used to track contents of the system log (/var/log/messages), and the outputs are gzipped since they can be potentially large, helping to save space.

Parameters:
  • path – Path to the log file.
  • logf – Basename of the file where output is logged (optional).
run(logdir)

Log all of the new data present in the log file.

class avocado.core.sysinfo.Logfile(path, logf=None)

Bases: avocado.core.sysinfo.Collectible

Collectible system file.

Parameters:
  • path – Path to the log file.
  • logf – Basename of the file where output is logged (optional).
run(logdir)

Copy the log file to the appropriate log dir.

Parameters:logdir – Log directory which the file is going to be copied to.
class avocado.core.sysinfo.SysInfo(basedir=None, log_packages=None, profiler=None)

Bases: object

Log different system properties at some key control points:

  • start_job
  • start_test
  • end_test
  • end_job

Set sysinfo collectibles.

Parameters:
  • basedir – Base log dir where sysinfo files will be located.
  • log_packages – Whether to log system packages (optional because logging packages is a costly operation). If not given explicitly, tries to look in the config files, and if not found, defaults to False.
  • profiler – Wether to use the profiler. If not given explicitly, tries to look in the config files.
add_cmd(cmd, hook)

Add a command collectible.

Parameters:
  • cmd – Command to log.
  • hook – In which hook this cmd should be logged (start job, end job).
add_file(filename, hook)

Add a system file collectible.

Parameters:
  • filename – Path to the file to be logged.
  • hook – In which hook this file should be logged (start job, end job).
add_watcher(filename, hook)

Add a system file watcher collectible.

Parameters:
  • filename – Path to the file to be logged.
  • hook – In which hook this watcher should be logged (start job, end job).
end_job_hook()

Logging hook called whenever a job finishes.

end_test_hook()

Logging hook called after a test finishes.

start_job_hook()

Logging hook called whenever a job starts.

start_test_hook()

Logging hook called before a test starts.

avocado.core.sysinfo.collect_sysinfo(args)

Collect sysinfo to a base directory.

Parameters:argsargparse.Namespace object with command line params.

avocado.core.test module

Contains the base test implementation, used as a base for the actual framework tests.

class avocado.core.test.DryRunTest(*args, **kwargs)

Bases: avocado.core.test.SkipTest

Fake test which logs itself and reports as SKIP

This class substitutes other classes. Let’s just ignore the remaining arguments and only set the ones supported by avocado.Test

setUp()
class avocado.core.test.ExternalRunnerTest(name, params=None, base_logdir=None, tag=None, job=None, external_runner=None)

Bases: avocado.core.test.SimpleTest

filename
test()
class avocado.core.test.MissingTest(methodName='test', name=None, params=None, base_logdir=None, tag=None, job=None, runner_queue=None)

Bases: avocado.core.test.Test

Handle when there is no such test module in the test directory.

Initializes the test.

Parameters:
  • methodName – Name of the main method to run. For the sake of compatibility with the original unittest class, you should not set this.
  • name – Pretty name of the test name. For normal tests, written with the avocado API, this should not be set, this is reserved for running random executables as tests.
  • base_logdir – Directory where test logs should go. If None provided, it’ll use avocado.data_dir.create_job_logs_dir().
  • tag – Tag that differentiates 2 executions of the same test name. Example: ‘long’, ‘short’, so we can differentiate ‘sleeptest.long’ and ‘sleeptest.short’.
  • job – The job that this test is part of.
test()
class avocado.core.test.NotATest(methodName='test', name=None, params=None, base_logdir=None, tag=None, job=None, runner_queue=None)

Bases: avocado.core.test.Test

The file is not a test.

Either a non executable python module with no avocado test class in it, or a regular, non executable file.

Initializes the test.

Parameters:
  • methodName – Name of the main method to run. For the sake of compatibility with the original unittest class, you should not set this.
  • name – Pretty name of the test name. For normal tests, written with the avocado API, this should not be set, this is reserved for running random executables as tests.
  • base_logdir – Directory where test logs should go. If None provided, it’ll use avocado.data_dir.create_job_logs_dir().
  • tag – Tag that differentiates 2 executions of the same test name. Example: ‘long’, ‘short’, so we can differentiate ‘sleeptest.long’ and ‘sleeptest.short’.
  • job – The job that this test is part of.
test()
class avocado.core.test.ReplaySkipTest(*args, **kwargs)

Bases: avocado.core.test.SkipTest

Skip test due to job replay filter.

This test is skipped due to a job replay filter. It will never have a chance to execute.

This class substitutes other classes. Let’s just ignore the remaining arguments and only set the ones supported by avocado.Test

class avocado.core.test.SimpleTest(name, params=None, base_logdir=None, tag=None, job=None)

Bases: avocado.core.test.Test

Run an arbitrary command that returns either 0 (PASS) or !=0 (FAIL).

filename

Returns the name of the file (path) that holds the current test

re_avocado_log = <_sre.SRE_Pattern object at 0x1e07100>
run(result=None)
test()

Run the executable, and log its detailed execution.

class avocado.core.test.SkipTest(*args, **kwargs)

Bases: avocado.core.test.Test

Class intended as generic substitute for avocado tests which fails during setUp phase using “self._skip_reason” message.

This class substitutes other classes. Let’s just ignore the remaining arguments and only set the ones supported by avocado.Test

setUp()
test()

Should not be executed

class avocado.core.test.Test(methodName='test', name=None, params=None, base_logdir=None, tag=None, job=None, runner_queue=None)

Bases: unittest.case.TestCase

Base implementation for the test class.

You’ll inherit from this to write your own tests. Typically you’ll want to implement setUp(), test*() and tearDown() methods on your own tests.

Initializes the test.

Parameters:
  • methodName – Name of the main method to run. For the sake of compatibility with the original unittest class, you should not set this.
  • name – Pretty name of the test name. For normal tests, written with the avocado API, this should not be set, this is reserved for running random executables as tests.
  • base_logdir – Directory where test logs should go. If None provided, it’ll use avocado.data_dir.create_job_logs_dir().
  • tag – Tag that differentiates 2 executions of the same test name. Example: ‘long’, ‘short’, so we can differentiate ‘sleeptest.long’ and ‘sleeptest.short’.
  • job – The job that this test is part of.
basedir

The directory where this test (when backed by a file) is located at

datadir

Returns the path to the directory that contains test data files

default_params = {}
error(message=None)

Errors the currently running test.

After calling this method a test will be terminated and have its status as ERROR.

Parameters:message (str) – an optional message that will be recorded in the logs
fail(message=None)

Fails the currently running test.

After calling this method a test will be terminated and have its status as FAIL.

Parameters:message (str) – an optional message that will be recorded in the logs
fetch_asset(name, asset_hash=None, algorithm='sha1', locations=None)

Method o call the utils.asset in order to fetch and asset file supporting hash check, caching and multiple locations.

Parameters:
  • name – the asset filename or URL
  • asset_hash – asset hash (optional)
  • algorithm – hash algorithm (optional, defaults to sha1)
  • locations – list of URLs from where the asset can be fetched (optional)
Returns:

asset file local path

filename

Returns the name of the file (path) that holds the current test

get_state()

Serialize selected attributes representing the test state

Returns:a dictionary containing relevant test state data
Return type:dict
report_state()

Send the current test state to the test runner process

run_avocado()

Wraps the run method, for execution inside the avocado runner.

Result:Unused param, compatibility with unittest.TestCase.
skip(message=None)

Skips the currently running test.

This method should only be called from a test’s setUp() method, not anywhere else, since by definition, if a test gets to be executed, it can’t be skipped anymore. If you call this method outside setUp(), avocado will mark your test status as ERROR, and instruct you to fix your test in the error message.

Parameters:message (str) – an optional message that will be recorded in the logs
srcdir = None
workdir = None
class avocado.core.test.TimeOutSkipTest(*args, **kwargs)

Bases: avocado.core.test.SkipTest

Skip test due job timeout.

This test is skipped due a job timeout. It will never have a chance to execute.

This class substitutes other classes. Let’s just ignore the remaining arguments and only set the ones supported by avocado.Test

avocado.core.tree module

Tree data strucure with nodes.

This tree structure (Tree drawing code) was inspired in the base tree data structure of the ETE 2 project:

http://pythonhosted.org/ete2/

A library for analysis of phylogenetics trees.

Explicit permission has been given by the copyright owner of ETE 2 Jaime Huerta-Cepas <jhcepas@gmail.com> to take ideas/use snippets from his original base tree code and re-license under GPLv2+, given that GPLv3 and GPLv2 (used in some avocado files) are incompatible.

class avocado.core.tree.Control(code, value=None)

Bases: object

Container used to identify node vs. control sequence

class avocado.core.tree.ListOfNodeObjects

Bases: list

Used to mark list as list of objects from whose node is going to be created

class avocado.core.tree.OutputList(values, nodes, yamls)

Bases: list

List with some debug info

class avocado.core.tree.OutputValue(value, node, srcyaml)

Bases: object

Ordinary value with some debug info

class avocado.core.tree.TreeNode(name='', value=None, parent=None, children=None)

Bases: object

Class for bounding nodes into tree-structure.

add_child(node)

Append node as child. Nodes with the same name gets merged into the existing position.

detach()

Detach this node from parent

environment

Node environment (values + preceding envs)

get_environment()

Get node environment (values + preceding envs)

get_leaves()

Get list of leaf nodes

get_node(path, create=False)
Parameters:
  • path – Path of the desired node (relative to this node)
  • create – Create the node (and intermediary ones) when not present
Returns:

the node associated with this path

Raises:

ValueError – When path doesn’t exist and create not set

get_parents()

Get list of parent nodes

get_path(sep='/')

Get node path

get_root()

Get root of this tree

is_leaf

Is this a leaf node?

iter_children_preorder()

Iterate through children

iter_leaves()

Iterate throuh leaf nodes

iter_parents()

Iterate through parent nodes to root

merge(other)

Merges other node into this one without checking the name of the other node. New values are appended, existing values overwritten and unaffected ones are kept. Then all other node children are added as children (recursively they get either appended at the end or merged into existing node in the previous position.

parents

List of parent nodes

path

Node path

root

Root of this tree

set_environment_dirty()

Set the environment cache dirty. You should call this always when you query for the environment and then change the value or structure. Otherwise you’ll get the old environment instead.

class avocado.core.tree.TreeNodeDebug(name='', value=None, parent=None, children=None, srcyaml=None)

Bases: avocado.core.tree.TreeNode

Debug version of TreeNodeDebug :warning: Origin of the value is appended to all values thus it’s not suitable for running tests.

merge(other)

Override origin with the one from other tree. Updated/Newly set values are going to use this location as origin.

class avocado.core.tree.Value

Bases: tuple

Used to mark values to simplify checking for node vs. value

class avocado.core.tree.ValueDict(srcyaml, node, values)

Bases: dict

Dict which stores the origin of the items

iteritems()

Slower implementation with the use of __getitem__

avocado.core.tree.apply_filters(tree, filter_only=None, filter_out=None)

Apply a set of filters to the tree.

The basic filtering is filter only, which includes nodes, and the filter out rules, that exclude nodes.

Note that filter_out is stronger than filter_only, so if you filter out something, you could not bypass some nodes by using a filter_only rule.

Parameters:
  • filter_only – the list of paths which will include nodes.
  • filter_out – the list of paths which will exclude nodes.
Returns:

the original tree minus the nodes filtered by the rules.

avocado.core.tree.create_from_yaml(paths, debug=False)

Create tree structure from yaml-like file :param fileobj: File object to be processed :raise SyntaxError: When yaml-file is corrupted :return: Root of the created tree structure

avocado.core.tree.get_named_tree_cls(path)

Return TreeNodeDebug class with hardcoded yaml path

avocado.core.tree.path_parent(path)

From a given path, return its parent path.

Parameters:path – the node path as string.
Returns:the parent path as string.
avocado.core.tree.tree_view(root, verbose=None, use_utf8=None)

Generate tree-view of the given node :param root: root node :param verbose: verbosity (0, 1, 2, 3) :param use_utf8: Use utf-8 encoding (None=autodetect) :return: string representing this node’s tree structure

avocado.core.version module

avocado.core.virt module

Module to provide classes for Virtual Machines.

class avocado.core.virt.Hypervisor(uri=None)

Bases: object

The Hypervisor connection class.

Creates an instance of class Hypervisor.

Parameters:uri – the connection URI.
connect()

Connect to the hypervisor.

domains

Property to get the list of all domains.

Returns:a list of instances of libvirt.virDomain.
find_domain_by_name(name)

Find domain by name.

Parameters:domain – the domain name.
Returns:an instance of libvirt.virDomain.
class avocado.core.virt.VM(hypervisor, domain)

Bases: object

The Virtual Machine handler class.

Creates an instance of VM class.

Parameters:
  • hypervisor – an instance of Hypervisor.
  • domain – an instance of libvirt.virDomain.
create_snapshot(name=None)

Creates a snapshot of kind ‘system checkpoint’.

delete_snapshot()

Delete the current snapshot.

ip_address()

Returns the IP address associated with the MAC address of this VM

Inspired from: https://raw.githubusercontent.com/mcepl/virt-addr/master/virt-addr.py

Returns:either the IP address or None if not found
Return type:str or None
is_active

Property to check if VM is active.

Returns:if VM is active.
Return type:Boolean
name

Property with the name of VM.

Returns:the name of VM.
reboot()

Reboot VM.

reset()

Reset VM.

restore_snapshot()

Revert to previous snapshot and delete the snapshot point.

resume()

Resume VM.

revert_snapshot()

Revert to previous snapshot.

setup_login(hostname, username, password=None)

Setup login on VM.

Parameters:
  • hostname – the hostname.
  • username – the username.
  • password – the password.
shutdown()

Shutdown VM.

snapshots
start()

Start VM.

state

Property with the state of VM.

Returns:current state name.
stop()

Stop VM.

suspend()

Suspend VM.

avocado.core.virt.vm_connect(domain_name, hypervisor_uri='qemu:///system')

Connect to a Virtual Machine.

Parameters:
  • domain_name – the domain name.
  • hypervisor_uri – the hypervisor connection URI.
Returns:

an instance of VM

avocado.core.xunit module

xUnit module.

class avocado.core.xunit.XmlResult

Bases: object

Handles the XML details for xUnit output.

add_error(state)

Add a testcase node of kind error.

Parameters:state (dict) – result of avocado.core.test.Test.get_state.
add_failure(state)

Add a testcase node of kind failed.

Parameters:state (dict) – result of avocado.core.test.Test.get_state.
add_skip(state)

Add a testcase node of kind skipped.

Parameters:state (dict) – result of avocado.core.test.Test.get_state.
add_success(state)

Add a testcase node of kind succeed.

Parameters:state (dict) – result of avocado.core.test.Test.get_state.
end_testsuite(tests, errors, failures, skip, total_time)

End of testsuite node.

Parameters:
  • tests – Number of tests.
  • errors – Number of test errors.
  • failures – Number of test failures.
  • skip – Number of test skipped.
  • total_time – The total time of test execution.
get_contents()
start_testsuite(timestamp)

Start a new testsuite node.

Parameters:timestamp – Timestamp string in date/time format.
class avocado.core.xunit.xUnitTestResult(job, force_xunit_file=None)

Bases: avocado.core.result.TestResult

xUnit Test Result class.

Creates an instance of xUnitTestResult.

Parameters:
  • job – an instance of avocado.core.job.Job.
  • force_xunit_file – Override the output file defined in job.args
command_line_arg_name = '--xunit'
end_test(state)

Record an end test event, accord to the given test status.

Parameters:state (dict) – result of avocado.core.test.Test.get_state.
end_tests()

Record an end tests event.

start_test(test)

Record a start test event.

start_tests()

Record a start tests event.

Module contents