virttest package

Subpackages

Submodules

virttest.RFBDes module

virttest.arch module

virttest.asset module

virttest.base_installer module

virttest.bootstrap module

virttest.build_helper module

virttest.cartesian_config module

Cartesian configuration format file parser.

Filter syntax:

  • , means OR
  • .. means AND
  • . means IMMEDIATELY-FOLLOWED-BY
  • (xx=yy) where xx=VARIANT_NAME and yy=VARIANT_VALUE

Example:

qcow2..(guest_os=Fedora).14, RHEL.6..raw..boot, smp2..qcow2..migrate..ide

means match all dicts whose names have:

(qcow2 AND ((guest_os=Fedora) IMMEDIATELY-FOLLOWED-BY 14)) OR
((RHEL IMMEDIATELY-FOLLOWED-BY 6) AND raw AND boot) OR
(smp2 AND qcow2 AND migrate AND ide)

Note:

  • qcow2..Fedora.14 is equivalent to Fedora.14..qcow2.
  • qcow2..Fedora.14 is not equivalent to qcow2..14.Fedora.
  • ide, scsi is equivalent to scsi, ide.

Filters can be used in 3 ways:

only <filter>
no <filter>
<filter>:

The last one starts a conditional block.

Formal definition: Regexp come from python. They’re not deterministic, but more readable for people. Spaces between terminals and nonterminals are only for better reading of definitions.

The base of the definitions come verbatim as follows:

E = {\n, #, :, "-", =, +=, <=, ?=, ?+=, ?<=, !, < , del, @, variants, include, only, no, name, value}

N = {S, DEL, FILTER, FILTER_NAME, FILTER_GROUP, PN_FILTER_GROUP, STAT, VARIANT, VAR-TYPE, VAR-NAME, VAR-NAME-F, VAR, COMMENT, TEXT, DEPS, DEPS-NAME-F, META-DATA, IDENTIFIER}``


I = I^n | n in N              // indentation from start of line
                              // where n is indentation length.
I = I^n+x | n,x in N          // indentation with shift

start symbol = S
end symbol = eps

S -> I^0+x STATV | eps

I^n    STATV
I^n    STATV

I^n STATV -> I^n STATV \n I^n STATV | I^n STAT | I^n variants VARIANT
I^n STAT -> I^n STAT \n I^n STAT | I^n COMMENT | I^n include INC
I^n STAT -> I^n del DEL | I^n FILTER

DEL -> name \n

I^n STAT -> I^n name = VALUE | I^n name += VALUE | I^n name <= VALUE
I^n STAT -> I^n name ?= VALUE | I^n name ?+= VALUE | I^n name ?<= VALUE

VALUE -> TEXT \n | 'TEXT' \n | "TEXT" \n

COMMENT_BLOCK -> #TEXT | //TEXT
COMMENT ->  COMMENT_BLOCK\n
COMMENT ->  COMMENT_BLOCK\n

TEXT = [^\n] TEXT            //python format regexp

I^n    variants VAR #comments:             add possibility for comment
I^n+x       VAR-NAME: DEPS
I^n+x+x2        STATV
I^n         VAR-NAME:

IDENTIFIER -> [A-Za-z0-9][A-Za-z0-9_-]*

VARIANT -> VAR COMMENT_BLOCK\n I^n+x VAR-NAME
VAR -> VAR-TYPE: | VAR-TYPE META-DATA: | :         // Named | unnamed variant

VAR-TYPE -> IDENTIFIER

variants _name_ [xxx] [zzz=yyy] [uuu]:

META-DATA -> [IDENTIFIER] | [IDENTIFIER=TEXT] | META-DATA META-DATA

I^n VAR-NAME -> I^n VAR-NAME \n I^n VAR-NAME | I^n VAR-NAME-N \n I^n+x STATV
VAR-NAME-N -> - @VAR-NAME-F: DEPS | - VAR-NAME-F: DEPS
VAR-NAME-F -> [a-zA-Z0-9\._-]+                  // Python regexp

DEPS -> DEPS-NAME-F | DEPS-NAME-F,DEPS
DEPS-NAME-F -> [a-zA-Z0-9\._- ]+                // Python regexp

INC -> name \n


FILTER_GROUP: STAT
    STAT

I^n STAT -> I^n PN_FILTER_GROUP | I^n ! PN_FILTER_GROUP

PN_FILTER_GROUP -> FILTER_GROUP: \n I^n+x STAT
PN_FILTER_GROUP -> FILTER_GROUP: STAT \n I^n+x STAT

only FILTER_GROUP
no FILTER_GROUP

FILTER -> only FILTER_GROUP \n | no FILTER_GROUP \n

FILTER_GROUP -> FILTER_NAME
FILTER_GROUP -> FILTER_GROUP..FILTER_GROUP
FILTER_GROUP -> FILTER_GROUP,FILTER_GROUP

FILTER_NAME -> FILTER_NAME.FILTER_NAME
FILTER_NAME -> VAR-NAME-F | (VAR-NAME-F=VAR-NAME-F)
copyright:Red Hat 2008-2013
class virttest.cartesian_config.BlockFilter(blocked)

Bases: object

apply_to_dict(d)
blocked
class virttest.cartesian_config.Condition(lfilter, line)

Bases: virttest.cartesian_config.NoFilter

content
class virttest.cartesian_config.FileReader(filename)

Bases: virttest.cartesian_config.StrReader

Preprocess an input file for easy reading.

Initialize the reader.

Parse filename:The name of the input file.
class virttest.cartesian_config.Filter(lfilter)

Bases: object

filter
match(ctx, ctx_set)
might_match(ctx, ctx_set, descendant_labels)
class virttest.cartesian_config.JoinFilter(lfilter, line)

Bases: virttest.cartesian_config.NoOnlyFilter

class virttest.cartesian_config.LAnd

Bases: virttest.cartesian_config.Token

identifier = '..'
class virttest.cartesian_config.LAppend

Bases: virttest.cartesian_config.LOperators

apply_to_dict(d)
identifier = '+='
class virttest.cartesian_config.LApplyPreDict

Bases: virttest.cartesian_config.LOperators

apply_to_dict(d)
identifier = 'apply_pre_dict'
set_operands(name, value)
class virttest.cartesian_config.LCoc

Bases: virttest.cartesian_config.Token

identifier = '.'
class virttest.cartesian_config.LColon

Bases: virttest.cartesian_config.Token

identifier = ':'
class virttest.cartesian_config.LComa

Bases: virttest.cartesian_config.Token

identifier = ','
class virttest.cartesian_config.LCond

Bases: virttest.cartesian_config.Token

identifier = ''
class virttest.cartesian_config.LDefault

Bases: virttest.cartesian_config.Token

identifier = '@'
class virttest.cartesian_config.LDel

Bases: virttest.cartesian_config.LOperators

apply_to_dict(d)
identifier = 'del'
class virttest.cartesian_config.LDot

Bases: virttest.cartesian_config.Token

identifier = '.'
class virttest.cartesian_config.LEndBlock(length)

Bases: virttest.cartesian_config.LIndent

class virttest.cartesian_config.LEndL

Bases: virttest.cartesian_config.Token

identifier = 'endl'
class virttest.cartesian_config.LIdentifier

Bases: str

checkAlpha()

Check if string contain only chars

checkChar(chars)
checkCharAlpha(chars)

Check if string contain only chars

checkCharAlphaNum(chars)

Check if string contain only chars

checkCharNumeric(chars)

Check if string contain only chars

checkNumbers()

Check if string contain only chars

identifier = 'Identifier re([A-Za-z0-9][A-Za-z0-9_-]*)'
class virttest.cartesian_config.LInclude

Bases: virttest.cartesian_config.Token

identifier = 'include'
class virttest.cartesian_config.LIndent(length)

Bases: virttest.cartesian_config.Token

identifier = 'indent'
length
class virttest.cartesian_config.LJoin

Bases: virttest.cartesian_config.Token

identifier = 'join'
class virttest.cartesian_config.LLBracket

Bases: virttest.cartesian_config.Token

identifier = '['
class virttest.cartesian_config.LLRBracket

Bases: virttest.cartesian_config.Token

identifier = '('
class virttest.cartesian_config.LNo

Bases: virttest.cartesian_config.Token

identifier = 'no'
class virttest.cartesian_config.LNotCond

Bases: virttest.cartesian_config.Token

identifier = '!'
class virttest.cartesian_config.LOnly

Bases: virttest.cartesian_config.Token

identifier = 'only'
class virttest.cartesian_config.LOperators

Bases: virttest.cartesian_config.Token

function = None
identifier = ''
name
set_operands(name, value)
value
class virttest.cartesian_config.LOr

Bases: virttest.cartesian_config.Token

identifier = ','
class virttest.cartesian_config.LPrepend

Bases: virttest.cartesian_config.LOperators

apply_to_dict(d)
identifier = '<='
class virttest.cartesian_config.LRBracket

Bases: virttest.cartesian_config.Token

identifier = ']'
class virttest.cartesian_config.LRRBracket

Bases: virttest.cartesian_config.Token

identifier = ')'
class virttest.cartesian_config.LRegExpAppend

Bases: virttest.cartesian_config.LOperators

apply_to_dict(d)
identifier = '?+='
class virttest.cartesian_config.LRegExpPrepend

Bases: virttest.cartesian_config.LOperators

apply_to_dict(d)
identifier = '?<='
class virttest.cartesian_config.LRegExpSet

Bases: virttest.cartesian_config.LOperators

apply_to_dict(d)
identifier = '?='
class virttest.cartesian_config.LRegExpStart

Bases: virttest.cartesian_config.Token

identifier = '${'
class virttest.cartesian_config.LRegExpStop

Bases: virttest.cartesian_config.Token

identifier = '}'
class virttest.cartesian_config.LSet

Bases: virttest.cartesian_config.LOperators

apply_to_dict(d)
Parameters:d – Dictionary for apply value
identifier = '='
class virttest.cartesian_config.LString

Bases: virttest.cartesian_config.LIdentifier

identifier = 'String re(.+)'
class virttest.cartesian_config.LSuffix

Bases: virttest.cartesian_config.Token

identifier = 'suffix'
class virttest.cartesian_config.LUpdateFileMap

Bases: virttest.cartesian_config.LOperators

apply_to_dict(d)
dest
identifier = 'update_file_map'
set_operands(filename, name, dest='_name_map_file')
shortname
class virttest.cartesian_config.LVariant

Bases: virttest.cartesian_config.Token

identifier = '-'
class virttest.cartesian_config.LVariants

Bases: virttest.cartesian_config.Token

identifier = 'variants'
class virttest.cartesian_config.LWhite

Bases: virttest.cartesian_config.LIdentifier

identifier = 'WhiteSpace re(\\s)'
class virttest.cartesian_config.Label(name, next_name=None)

Bases: object

hash_name()
hash_val
hash_var
hash_variant()
long_name
name
var_name
class virttest.cartesian_config.Lexer(reader)

Bases: object

check_token(token, lType)
flush_until(end_tokens=None)
get_lexer()
get_next_check(lType)
get_next_check_nw(lType)
get_until(end_tokens=None)
get_until_check(lType, end_tokens=None)

Read tokens from iterator until get end_tokens or type of token not match ltype

Parameters:
  • lType – List of allowed tokens
  • end_tokens – List of tokens for end reading
Returns:

List of readed tokens.

get_until_gen(end_tokens=None)
get_until_no_white(end_tokens=None)

Read tokens from iterator until get one of end_tokens and strip LWhite

Parameters:end_tokens – List of tokens for end reading
Returns:List of readed tokens.
match(line, pos)
rest_line()
rest_line_as_LString()
rest_line_gen()
rest_line_no_white()
set_fast()
set_prev_indent(prev_indent)
set_strict()
exception virttest.cartesian_config.LexerError(msg, line=None, filename=None, linenum=None)

Bases: virttest.cartesian_config.ParserError

exception virttest.cartesian_config.MissingIncludeError(line, filename, linenum)

Bases: exceptions.Exception

class virttest.cartesian_config.NegativeCondition(lfilter, line)

Bases: virttest.cartesian_config.OnlyFilter

content
class virttest.cartesian_config.NoFilter(lfilter, line)

Bases: virttest.cartesian_config.NoOnlyFilter

is_irrelevant(ctx, ctx_set, descendant_labels)
might_pass(failed_ctx, failed_ctx_set, ctx, ctx_set, descendant_labels)
requires_action(ctx, ctx_set, descendant_labels)
class virttest.cartesian_config.NoOnlyFilter(lfilter, line)

Bases: virttest.cartesian_config.Filter

line
class virttest.cartesian_config.Node

Bases: object

append_to_shortname
children
content
default
dep
dump(indent, recurse=False)
failed_cases
filename
labels
name
q_dict
var_name
class virttest.cartesian_config.OnlyFilter(lfilter, line)

Bases: virttest.cartesian_config.NoOnlyFilter

is_irrelevant(ctx, ctx_set, descendant_labels)
might_pass(failed_ctx, failed_ctx_set, ctx, ctx_set, descendant_labels)
requires_action(ctx, ctx_set, descendant_labels)
class virttest.cartesian_config.Parser(filename=None, defaults=False, expand_defaults=[], debug=False)

Bases: object

assign(key, value)

Apply a only filter programatically and keep track of it.

Equivalent to parse a “key = value” line.

Parameters:variant – String with the variant name.
drop_suffixes(d)
get_dicts(node=None, ctx=[], content=[], shortname=[], dep=[])

Process ‘join’ entry, unpack join filter for node ctx - node labels/names content - previous content in plain Return: dictionary

get_dicts_plain(node=None, ctx=[], content=[], shortname=[], dep=[])

Generate dictionaries from the code parsed so far. This should be called after parsing something.

Returns:A dict generator.
mk_name(n1, n2)
multiply_join(onlys, node=None, ctx=[], content=[], shortname=[], dep=[])
no_filter(variant)

Apply a only filter programatically and keep track of it.

Equivalent to parse a “no variant” line.

Parameters:variant – String with the variant name.
only_filter(variant)

Apply a only filter programatically and keep track of it.

Equivalent to parse a “only variant” line.

Parameters:variant – String with the variant name.
parse_file(filename)

Parse a file.

Parameters:filename – Path of the configuration file.
parse_string(s)

Parse a string.

Parameters:s – String to parse.
exception virttest.cartesian_config.ParserError(msg, line=None, filename=None, linenum=None)

Bases: exceptions.Exception

class virttest.cartesian_config.StrReader(s)

Bases: object

Preprocess an input string for easy reading.

Initialize the reader.

Parameters:s – The string to parse.
get_next_line(prev_indent)

Get the next line in the current block.

Parameters:prev_indent – The indentation level of the previous block.
Returns:(line, indent, linenum), where indent is the line’s indentation level. If no line is available, (None, -1, -1) is returned.
set_next_line(line, indent, linenum)

Make the next call to get_next_line() return the given line instead of the real next line.

class virttest.cartesian_config.Suffix

Bases: virttest.cartesian_config.LOperators

apply_to_dict(d)
identifier = 'apply_suffix'
class virttest.cartesian_config.Token

Bases: object

identifier = ''
virttest.cartesian_config.apply_predict(lexer, node, pre_dict)
virttest.cartesian_config.cmd_tokens(tokens1, tokens2)
virttest.cartesian_config.compare_string(str1, str2)

Compare two int string and return -1, 0, 1. It can compare two memory value even in sufix

Parameters:
  • str1 – The first string
  • str2 – The second string
Return:

Rteurn -1, when str1< str2 0, when str1 = str2 1, when str1> str2

virttest.cartesian_config.convert_data_size(size, default_sufix='B')

Convert data size from human readable units to an int of arbitrary size.

Parameters:
  • size – Human readable data size representation (string).
  • default_sufix – Default sufix used to represent data.
Returns:

Int with data size in the appropriate order of magnitude.

virttest.cartesian_config.next_nw(gener)
virttest.cartesian_config.parse_filter(lexer, tokens)
Returns:Parsed filter
virttest.cartesian_config.postfix_parse(dic)
virttest.cartesian_config.print_dicts(options, dicts)
virttest.cartesian_config.print_dicts_default(options, dicts)

Print dictionaries in the default mode

virttest.cartesian_config.print_dicts_repr(options, dicts)

virttest.ceph module

virttest.data_dir module

virttest.defaults module

virttest.defaults.get_default_guest_os_info()

Gets the default asset and variant information TODO: Check for the ARCH and choose corresponding default asset

virttest.element_path module

class virttest.element_path.Path(path)
find(element)
findall(element)
findtext(element, default=None)
virttest.element_path.find(element, path)
virttest.element_path.findall(element, path)
virttest.element_path.findtext(element, path, default=None)
class virttest.element_path.xpath_descendant_or_self
virttest.element_path.xpath_tokenizer()

findall(string[, pos[, endpos]]) –> list. Return a list of all non-overlapping matches of pattern in string.

virttest.element_tree module

virttest.element_tree.Comment(text=None)
virttest.element_tree.dump(elem)
virttest.element_tree.Element(tag, attrib={}, **extra)
class virttest.element_tree.ElementTree(element=None, file=None)

Bases: object

find(path)
findall(path)
findtext(path, default=None)
getiterator(tag=None)
getroot()
parse(source, parser=None)
write(file, encoding='us-ascii')
virttest.element_tree.fromstring(text)
virttest.element_tree.iselement(element)
class virttest.element_tree.iterparse(source, events=None)

Bases: object

next()
virttest.element_tree.parse(source, parser=None)
virttest.element_tree.PI(target, text=None)
virttest.element_tree.ProcessingInstruction(target, text=None)
class virttest.element_tree.QName(text_or_uri, tag=None)

Bases: object

virttest.element_tree.SubElement(parent, tag, attrib={}, text=None, **extra)
virttest.element_tree.tostring(element, encoding=None)
class virttest.element_tree.TreeBuilder(element_factory=None)

Bases: object

close()
data(data)
end(tag)
start(tag, attrs)
virttest.element_tree.XML(text)
virttest.element_tree.XMLParser

alias of XMLTreeBuilder

class virttest.element_tree.XMLTreeBuilder(html=0, target=None)

Bases: object

close()
doctype(name, pubid, system)
feed(data)

virttest.env_process module

virttest.error_context module

virttest.error_context.format_error()
virttest.error_context.context_aware(fn)

A decorator that must be applied to functions that call context().

virttest.error_context.context(s='', log=None)

Set the context for the currently executing function and optionally log it.

Parameters:
  • s – A string. If not provided, the context for the current function will be cleared.
  • log – A logging function to pass the context message to. If None, no function will be called.
virttest.error_context.get_context()

Return the current context (or None if none is defined).

virttest.error_context.exception_context(e)

Return the context of a given exception (or None if none is defined).

virttest.funcatexit module

virttest.gluster module

virttest.guest_agent module

virttest.http_server module

class virttest.http_server.HTTPRequestHandler(request, client_address, server)

Bases: SimpleHTTPServer.SimpleHTTPRequestHandler

address_string()

This HTTP server does not care about name resolution for the requests

The first reason is that most of the times our clients are going to be virtual machines without a proper name resolution setup. Also, by not resolving names, we should be a bit faster and be resilient about misconfigured or resilient name servers.

copyfile_range(source_file, output_file, range_begin, range_end)

Copies a range of a file to destination.

do_GET()

Serve a GET request.

log_message(fmt, *args)
parse_header_byte_range()
send_head_range(range_begin, range_end)
translate_path(path)

Translate a /-separated PATH to the local filename syntax.

Components that mean special things to the local file system (e.g. drive or directory names) are ignored. (XXX They should probably be diagnosed.)

virttest.http_server.http_server(port=8000, cwd=None, terminate_callable=None)

virttest.installer module

virttest.iscsi module

virttest.libvirt_storage module

virttest.libvirt_vm module

virttest.lvm module

virttest.lvsb module

Higher order classes and functions for Libvirt Sandbox (lxc) container testing

copyright:2013 Red Hat Inc.
class virttest.lvsb.TestBaseSandboxes(params, env)

Bases: virttest.lvsb_base.TestSandboxes

Simplistic sandbox aggregate manager

Initialize to run, all SandboxCommandBase’s

command_suffixes()

Append command after a –

results(each_timeout=5)

Run sandboxe(s), allowing each_timeout to complete, return output list

class virttest.lvsb.TestComplexSandboxes(params, env)

Bases: virttest.lvsb.TestBaseSandboxes

Executes a command with complex options

class virttest.lvsb.TestSimpleSandboxes(params, env)

Bases: virttest.lvsb.TestBaseSandboxes

Executes a command with simple options

Initialize to run, all SandboxCommandBase’s

virttest.lvsb.make_sandboxes(params, env, extra_ns=None)

Return list of instantiated lvsb_testsandboxes classes from params

Parameters:
  • params – an undiluted Params instance
  • env – the current env instance
  • extra_ns – An extra, optional namespace to search for classes

virttest.lvsb_base module

Base classes supporting Libvirt Sandbox (lxc) container testing

copyright:2013 Red Hat Inc.
class virttest.lvsb_base.SandboxBase(params)

Bases: object

Base operations for sandboxed command

Create a new sandbox interface instance based on this type from params

auto_clean(boolean)

Change behavior of asynchronous background sandbox process on __del__

exit_code()

Block until asynchronous background sandbox process ends, returning code

fini()

Finalize asynchronous background sandbox process (destroys state!)

instances = None
make_sandbox_command_line(extra=None)

Return the fully formed command-line for the sandbox using self.options

recv()

Return stdout and stderr from asynchronous background sandbox process

recverr()

return only stderr from asynchronous background sandbox process

recvout()

Return only stdout from asynchronous background sandbox process

run(extra=None)

Launch new sandbox as asynchronous background sandbox process

Parameters:extra – String of extra command-line to use but not store
running()

Return True/False if asynchronous background sandbox process executing

send(data)

Send data to asynchronous background sandbox process

stop()

Destroy but don’t finalize asynchronous background sandbox process

class virttest.lvsb_base.SandboxCommandBase(params, name=None)

Bases: virttest.lvsb_base.SandboxBase

Connection to a single new or existing sandboxed command

Initialize sandbox-command with params and name, autogenerate if None

BINARY_PATH_PARAM = 'virt_sandbox_binary'
add_flag(option)

Add a flag into the list of command line options

add_mm()

Append a – to the end of the current option list

add_optarg(option, argument)

Add an option with an argument into the list of command line options

add_pos(argument)

Add a positional option into the list of command line options

static flaten_options(options)

Convert a list of tuples into space-seperated options+argument string

list_flags()

Return a list of all flags (options without arguments)

list_long_options()

Return a list of all long options with an argument

list_pos()

Return a list of all positional arguments

list_short_options()

Return a list of all short options with an argument

make_sandbox_command_line(extra=None)

Return entire command-line string needed to start sandbox

name

Represent a unique sandbox name generated from class and identifier

exception virttest.lvsb_base.SandboxException(message)

Bases: exceptions.Exception

Basic exception class for problems occurring in SandboxBase or subclasses

class virttest.lvsb_base.SandboxSession

Bases: object

Connection instance to asynchronous I/O redirector process

auto_clean(boolean)

Make session cleanup on GC if True

close_session(warn_if_nonexist=True)

Finalize assigned opaque session object

connected

Represents True/False value if background process was created/opened

exit_code()

Block, and return exit code from session

is_running()

Return True if exit_code() would block

kill_session(sig=15)

Send a signal to the opaque session object

new_session(command)

Create and set new opaque session object

open_session(a_id)

Restore connection to existing session identified by a_id

recv()

Return combined stdout/stderr output received so far

recverr()

Return just stderr output

recvout()

Return just stdout output

send(a_string)

Send a_string to session

session_id

Returns unique & persistent identifier for the background process

used = False
class virttest.lvsb_base.TestSandboxes(params, env)

Bases: object

Aggregate manager class of SandboxCommandBase or subclass instances

Create instance(s) of sandbox from a command

SANDBOX_TYPE

alias of SandboxCommandBase

are_failed()

Return the number of sandbox processes with non-zero exit codes

are_running()

Return the number of sandbox processes still running

for_each(do_something, *args, **dargs)

Iterate over all sandboxes, calling do_something on each

Parameters:do_sometihng – Called with the item and *args, **dargs
init_sandboxes()

Create self.count Sandbox instances

virttest.lvsbs module

virttest.nfs module

virttest.openvswitch module

virttest.ovirt module

virttest.ovs_utils module

virttest.passfd module

virttest.passfd_setup module

virttest.postprocess_iozone module

virttest.ppm_utils module

Utility functions to deal with ppm (qemu screendump format) files.

copyright:Red Hat 2008-2009
virttest.ppm_utils.cal_hamming_distance(h1, h2)

Calculate the hamming distance

virttest.ppm_utils.find_id_for_screendump(md5sum, data_dir)

Search dir for a PPM file whose name ends with md5sum.

Parameters:
  • md5sum – md5 sum string
  • dir – Directory that holds the PPM files.
Returns:

The file’s basename without any preceding path, e.g. 20080101_120000_d41d8cd98f00b204e9800998ecf8427e.ppm

virttest.ppm_utils.generate_id_for_screendump(md5sum, data_dir)

Generate a unique filename using the given MD5 sum.

Returns:Only the file basename, without any preceding path. The filename consists of the current date and time, the MD5 sum and a .ppm extension, e.g. 20080101_120000_d41d8cd98f00b204e9800998ecf8427e.ppm.
virttest.ppm_utils.get_data_dir(steps_filename)

Return the data dir of the given steps filename.

virttest.ppm_utils.get_region_md5sum(width, height, data, x1, y1, dx, dy, cropped_image_filename=None)

Return the md5sum of a cropped region.

Parameters:
  • width – Original image width
  • height – Original image height
  • data – Image data
  • x1 – Desired x coord of the cropped region
  • y1 – Desired y coord of the cropped region
  • dx – Desired width of the cropped region
  • dy – Desired height of the cropped region
  • cropped_image_filename – if not None, write the resulting cropped image to a file with this name
virttest.ppm_utils.have_similar_img(base_img, comp_img_path, threshold=10)

Check whether comp_img_path have a image looks like base_img.

virttest.ppm_utils.image_average_hash(image, img_wd=8, img_ht=8)

Resize and convert the image, then get image data as sequence object, calculate the average hash :param image: an image path or an opened image object

virttest.ppm_utils.image_comparison(width, height, data1, data2)

Generate a green-red comparison image from two given images.

Parameters:
  • width – Width of both images
  • height – Height of both images
  • data1 – Data of first image
  • data2 – Data of second image
Returns:

A 3-element tuple containing the width, height and data of the generated comparison image.

Note:

Input images must be the same size.

virttest.ppm_utils.image_crop(width, height, data, x1, y1, dx, dy)

Crop an image.

Parameters:
  • width – Original image width
  • height – Original image height
  • data – Image data
  • x1 – Desired x coordinate of the cropped region
  • y1 – Desired y coordinate of the cropped region
  • dx – Desired width of the cropped region
  • dy – Desired height of the cropped region
Returns:

A 3-tuple containing the width, height and data of the cropped image.

virttest.ppm_utils.image_crop_save(image, new_image, box=None)

Crop an image and save it to a new image.

Parameters:
  • image – Full path of the original image
  • new_image – Full path of the cropped image
  • box – A 4-tuple defining the left, upper, right, and lower pixel coordinate.
Returns:

True if crop and save image succeed

virttest.ppm_utils.image_fuzzy_compare(width, height, data1, data2)

Return the degree of equality of two given images.

Parameters:
  • width – Width of both images
  • height – Height of both images
  • data1 – Data of first image
  • data2 – Data of second image
Returns:

Ratio equal_pixel_count / total_pixel_count.

Note:

Input images must be the same size.

virttest.ppm_utils.image_histogram_compare(image_a, image_b, size=(0, 0))

Compare the histogram of two images and return similar degree.

Parameters:
  • image_a – Full path of the first image
  • image_b – Full path of the second image
  • size – Convert image to size(width, height), and if size=(0, 0), the function will convert the big size image align with the small one.
virttest.ppm_utils.image_md5sum(width, height, data)

Return the md5sum of an image.

Parameters:
  • width – PPM file width
  • height – PPM file height
  • data – PPM file data
virttest.ppm_utils.image_read_from_ppm_file(filename)

Read a PPM image.

Returns:A 3 element tuple containing the width, height and data of the image.
virttest.ppm_utils.image_verify_ppm_file(filename)

Verify the validity of a PPM file.

Parameters:filename – Path of the file being verified.
Returns:True if filename is a valid PPM image file. This function reads only the first few bytes of the file so it should be rather fast.
virttest.ppm_utils.image_write_to_ppm_file(filename, width, height, data)

Write a PPM image with the given width, height and data.

Parameters:
  • filename – PPM file path
  • width – PPM file width (pixels)
  • height – PPM file height (pixels)
virttest.ppm_utils.img_ham_distance(base_img, comp_img)

Calculate two images hamming distance

virttest.ppm_utils.img_similar(base_img, comp_img, threshold=10)

check whether two images are similar by hamming distance

virttest.ppm_utils.md5eval(data)

Returns a md5 hash evaluator. This function is implemented in order to encapsulate objects in a way that is compatible with python 2.4 and python 2.6 without warnings.

Parameters:data – Optional input string that will be used to update the object.

virttest.propcan module

Class which allows property and dict-like access to a fixed set of instance attributes. Attributes are locked by __slots__, however accessor methods may be created/removed on instances, or defined by the subclass. An INITIALIZED attribute is provided to signel completion of __init__() for use by accessor methods (i.e. so they know when __init__ may be setting values).

Subclasses must define a __slots__ class attribute containing the list of attribute names to reserve. All additional subclass descendents must explicitly copy __slots__ from the parent in their definition.

Users of subclass instances are expected to get/set/del attributes only via the standard object or dict-like interface. i.e.

instance.attribute = whatever or instance[‘attribute’] = whatever

Internally, methods are free to call the accessor methods. Only accessor methods should use the special __dict_*__() and __super_*__() methods. These are there to allow convenient access to the internal dictionary values and subclass-defined attributes (such as __slots__).

example:

class A(PropCan):
   # Class with *attributes*
    __slots__ = ('a', 'b')
    # 'a' has defined a set/get/del by definition of method with prefix
    #     set_a, get_a, del_a
    # 'b' doesn't have defined set/get/del then classic set/get/del will be
    #     called instead.


    def __init__(self, a=1, b='b'):
       super(A, self).__init__(a, b)


    def set_a(self, value)
        # If is_instance(obj, A) then obj.a = "val" call this method.
        self.__dict_set__("a", value)


    def get_a(self, value)
        # If is_instance(obj, A) then xx = obj.a call this method.
        return self.__dict_get__("a")


    def del_a(self, value)
        # If is_instance(obj, A) then del obj.a call this method.
        self.__dict_del__("a")


class B(PropCan):
   # Class without *attributes*
   # ***** Even if class doesn't have attributes there should be
   # defined __slots__ = []. Because it is preferred by new style of class.
   # *****
    __slots__ = []


    def __init__(self):
       super(B, self).__init__()
class virttest.propcan.PropCan(*args, **dargs)

Bases: virttest.propcan.PropCanBase

Special value handling on retrieval of None values

Initialize contents directly or by way of accessors

Parameters:
  • args – Initial values for __slots__ keys, same as dict.
  • dargs – Initial values for __slots__ keys, same as dict.
has_key(key)
items()
keys()
set_if_none(key, value)

Set the value of key, only if it’s not set or None

set_if_value_not_none(key, value)

Set the value of key, only if value is not None

values()
class virttest.propcan.PropCanBase(*args, **dargs)

Bases: dict, virttest.propcan.PropCanInternal

Objects with optional accessor methods and dict-like access to fixed set of keys

Initialize contents directly or by way of accessors

Parameters:
  • args – Initial values for __slots__ keys, same as dict.
  • dargs – Initial values for __slots__ keys, same as dict.
INITIALIZED = False
copy()

Copy properties by value, not by reference.

update(other=None, excpt=<type 'exceptions.AttributeError'>, **kwargs)

Update properties in __all_slots__ with another dict.

class virttest.propcan.PropCanInternal

Bases: object

Semi-private methods for use only by PropCanBase subclasses (NOT instances)

class virttest.propcan.classproperty

Bases: property

virttest.qemu_installer module

virttest.qemu_io module

virttest.qemu_monitor module

virttest.qemu_qtree module

virttest.qemu_storage module

virttest.qemu_virtio_port module

virttest.qemu_vm module

virttest.remote module

virttest.remote_build module

virttest.rss_client module

Client for file transfer services offered by RSS (Remote Shell Server).

author:Michael Goldish (mgoldish@redhat.com)
copyright:2008-2010 Red Hat Inc.
class virttest.rss_client.FileDownloadClient(address, port, log_func=None, timeout=20)

Bases: virttest.rss_client.FileTransferClient

Connect to a RSS (remote shell server) and download files or directory trees.

Connect to a server.

Parameters:
  • address – The server’s address
  • port – The server’s port
  • log_func – If provided, transfer stats will be passed to this function during the transfer
  • timeout – Time duration to wait for connection to succeed
Raises:
download(src_pattern, dst_path, timeout=600)

Receive files or directory trees from the server. The semantics of src_pattern and dst_path are similar to those of scp.

For example, the following are OK:

src_pattern='C:\foo.txt', dst_path='/tmp'
    (downloads a single file)
src_pattern='C:\Windows', dst_path='/tmp'
    (downloads a directory tree recursively)
src_pattern='C:\Windows\*', dst_path='/tmp'
    (downloads all files and directory trees under C:\Windows)

The following is not OK:

src_pattern='C:\Windows', dst_path='/tmp/*'
    (wildcards are only allowed in src_pattern)
Parameters:
  • src_pattern – A path or wildcard pattern specifying the files or directories, in the server’s filesystem, that will be sent to the client
  • dst_path – A path in the local filesystem where the files will be saved
  • timeout – Time duration in seconds to wait for the transfer to complete
Raises:
Note:

Other exceptions can be raised.

class virttest.rss_client.FileTransferClient(address, port, log_func=None, timeout=20)

Bases: object

Connect to a RSS (remote shell server) and transfer files.

Connect to a server.

Parameters:
  • address – The server’s address
  • port – The server’s port
  • log_func – If provided, transfer stats will be passed to this function during the transfer
  • timeout – Time duration to wait for connection to succeed
Raises:

FileTransferConnectError – Raised if the connection fails

close()

Close the connection.

exception virttest.rss_client.FileTransferConnectError(msg, e=None, filename=None)

Bases: virttest.rss_client.FileTransferError

exception virttest.rss_client.FileTransferError(msg, e=None, filename=None)

Bases: exceptions.Exception

exception virttest.rss_client.FileTransferNotFoundError(msg, e=None, filename=None)

Bases: virttest.rss_client.FileTransferError

exception virttest.rss_client.FileTransferProtocolError(msg, e=None, filename=None)

Bases: virttest.rss_client.FileTransferError

exception virttest.rss_client.FileTransferServerError(errmsg)

Bases: virttest.rss_client.FileTransferError

exception virttest.rss_client.FileTransferSocketError(msg, e=None, filename=None)

Bases: virttest.rss_client.FileTransferError

exception virttest.rss_client.FileTransferTimeoutError(msg, e=None, filename=None)

Bases: virttest.rss_client.FileTransferError

class virttest.rss_client.FileUploadClient(address, port, log_func=None, timeout=20)

Bases: virttest.rss_client.FileTransferClient

Connect to a RSS (remote shell server) and upload files or directory trees.

Connect to a server.

Parameters:
  • address – The server’s address
  • port – The server’s port
  • log_func – If provided, transfer stats will be passed to this function during the transfer
  • timeout – Time duration to wait for connection to succeed
Raises:
upload(src_pattern, dst_path, timeout=600)

Send files or directory trees to the server.

The semantics of src_pattern and dst_path are similar to those of scp. For example, the following are OK:

src_pattern='/tmp/foo.txt', dst_path='C:\'
    (uploads a single file)
src_pattern='/usr/', dst_path='C:\Windows\'
    (uploads a directory tree recursively)
src_pattern='/usr/*', dst_path='C:\Windows\'
    (uploads all files and directory trees under /usr/)

The following is not OK:

src_pattern='/tmp/foo.txt', dst_path='C:\Windows\*'
    (wildcards are only allowed in src_pattern)
Parameters:
  • src_pattern – A path or wildcard pattern specifying the files or directories to send to the server
  • dst_path – A path in the server’s filesystem where the files will be saved
  • timeout – Time duration in seconds to wait for the transfer to complete
Raises:
Note:

Other exceptions can be raised.

virttest.rss_client.download(address, port, src_pattern, dst_path, log_func=None, timeout=60, connect_timeout=20)

Connect to server and upload files.

:see:: FileDownloadClient

virttest.rss_client.main()
virttest.rss_client.upload(address, port, src_pattern, dst_path, log_func=None, timeout=60, connect_timeout=20)

Connect to server and upload files.

:see:: FileUploadClient

virttest.scan_autotest_results module

Program that parses the autotest results and return a nicely printed final test result.

copyright:Red Hat 2008-2009
virttest.scan_autotest_results.main(resfiles)
virttest.scan_autotest_results.parse_results(text)

Parse text containing Autotest results.

Returns:A list of result 4-tuples.
virttest.scan_autotest_results.print_result(result, name_width)

Nicely print a single Autotest result.

Parameters:
  • result – a 4-tuple
  • name_width – test name maximum width

virttest.scheduler module

virttest.ssh_key module

virttest.standalone_test module

virttest.step_editor module

virttest.storage module

virttest.syslog_server module

class virttest.syslog_server.RequestHandler(request, client_address, server)

Bases: SocketServer.BaseRequestHandler

A request handler that relays all received messages as DEBUG

FACILITY_NAMES = {0: 'kern', 1: 'user', 2: 'mail', 3: 'daemon', 4: 'security', 5: 'syslog', 6: 'lpr', 7: 'news', 8: 'uucp', 9: 'cron', 10: 'authpriv', 11: 'ftp', 16: 'local0', 17: 'local1', 18: 'local2', 19: 'local3', 20: 'local4', 21: 'local5', 22: 'local6', 23: 'local7'}
LOG_ALERT = 1
LOG_AUTH = 4
LOG_AUTHPRIV = 10
LOG_CRIT = 2
LOG_CRON = 9
LOG_DAEMON = 3
LOG_DEBUG = 7
LOG_EMERG = 0
LOG_ERR = 3
LOG_FTP = 11
LOG_INFO = 6
LOG_KERN = 0
LOG_LOCAL0 = 16
LOG_LOCAL1 = 17
LOG_LOCAL2 = 18
LOG_LOCAL3 = 19
LOG_LOCAL4 = 20
LOG_LOCAL5 = 21
LOG_LOCAL6 = 22
LOG_LOCAL7 = 23
LOG_LPR = 6
LOG_MAIL = 2
LOG_NEWS = 7
LOG_NOTICE = 5
LOG_SYSLOG = 5
LOG_USER = 1
LOG_UUCP = 8
LOG_WARNING = 4
PRIORITY_NAMES = {0: 'emerg', 1: 'alert', 2: 'critical', 3: 'err', 4: 'warning', 5: 'notice', 6: 'info', 7: 'debug'}
RECORD_RE = <_sre.SRE_Pattern object>
decodeFacilityPriority(priority)

Decode both the facility and priority embedded in a syslog message

Parameters:priority (integer) – an integer with facility and priority encoded
Returns:a tuple with two strings
log(data, message_format=None)

Logs the received message as a DEBUG message

class virttest.syslog_server.RequestHandlerTcp(request, client_address, server)

Bases: virttest.syslog_server.RequestHandler

handle()

Handles a single request

class virttest.syslog_server.RequestHandlerUdp(request, client_address, server)

Bases: virttest.syslog_server.RequestHandler

handle()

Handles a single request

class virttest.syslog_server.SysLogServerTcp(address)

Bases: SocketServer.TCPServer

class virttest.syslog_server.SysLogServerUdp(address)

Bases: SocketServer.UDPServer

virttest.syslog_server.get_default_format()

Returns the current default message format

virttest.syslog_server.set_default_format(message_format)

Changes the default message format

Parameters:message_format (string) – a message format string with 3 placeholders: facility, priority and message.
virttest.syslog_server.syslog_server(address='', port=514, tcp=True, terminate_callable=None)

virttest.test_setup module

virttest.utils_config module

exception virttest.utils_config.ConfigError(msg)

Bases: exceptions.Exception

exception virttest.utils_config.ConfigNoOptionError(option, path)

Bases: virttest.utils_config.ConfigError

class virttest.utils_config.LibvirtConfigCommon(path='')

Bases: virttest.utils_config.SectionlessConfig

A abstract class to manipulate options of a libvirt related configure files in a property’s way.

Variables “__option_types__” and “conf_path” must be setup in the inherented classes before use.

“__option_types__” is a dict contains every possible option as keys and their type (“boolean”, “int”, “string”, “float” or “list”) as values.

Basic usage: 1) Create a config file object: >>> # LibvirtdConfig is a subclass of LibvirtConfigCommon. >>> config = LibvirtdConfig()

2) Set or update an option: >>> config.listen_tcp = True >>> config.listen_tcp = 1 >>> config.listen_tcp = “1” # All three have the same effect.

>>> # If the setting value don't meet the specified type.
>>> config.listen_tcp = "invalid"
>>> # It'll thown an warning message and set a raw string instead.
>>> # Use set_* methods when need to customize the result.
>>> config.set_raw("'1'")

3) Get an option: >>> is_listening = config.listen_tcp >>> print is_listening True

4) Delete an option from the config file: >>> del config.listen_tcp

5) Make the changes take effect in libvirt by restart libvirt daemon. >>> from virttest import utils_libvirtd >>> utils_libvirtd.Libvirtd().restart()

6) Restore the content of the config file. >>> config.restore()

conf_path = ''
exception virttest.utils_config.LibvirtConfigUnknownKeyError(key)

Bases: virttest.utils_config.ConfigError

exception virttest.utils_config.LibvirtConfigUnknownKeyTypeError(key, key_type)

Bases: virttest.utils_config.ConfigError

class virttest.utils_config.LibvirtGuestsConfig(path='')

Bases: virttest.utils_config.LibvirtConfigCommon

Class for sysconfig libvirt-guests config file.

conf_path = '/etc/sysconfig/libvirt-guests'
class virttest.utils_config.LibvirtQemuConfig(path='')

Bases: virttest.utils_config.LibvirtConfigCommon

Class for libvirt qemu config file.

conf_path = '/etc/libvirt/qemu.conf'
class virttest.utils_config.LibvirtdConfig(path='')

Bases: virttest.utils_config.LibvirtConfigCommon

Class for libvirt daemon config file.

conf_path = '/etc/libvirt/libvirtd.conf'
class virttest.utils_config.LibvirtdSysConfig(path='')

Bases: virttest.utils_config.LibvirtConfigCommon

Class for sysconfig libvirtd config file.

conf_path = '/etc/default/libvirtd'
distro = ('Ubuntu', '16.04', 'xenial')
class virttest.utils_config.SectionlessConfig(path)

Bases: object

This is a wrapper class for python’s internal library ConfigParser except allows manipulating sectionless configuration file with a dict-like way.

Example config file test.conf:

># This is a comment line. >a = 1 >b = [hi, there] >c = hello >d = “hi, there” >e = [hi, > there]

Example script using try...finally... statement:

>>> from virttest import utils_config
>>> config = utils_config.SectionlessConfig('test.conf')
>>> try:
...     print len(config)
...     print config
...     print config['a']
...     del config['a']
...     config['f'] = 'test'
...     print config
... finally:
...     config.restore()

Example script using with statement:

>>> from virttest import utils_config
>>> with utils_config.SectionlessConfig('test.conf') as config:
...     print len(config)
...     print config
...     print config['a']
...     del config['a']
...     config['f'] = 'test'
...     print config
get_boolean(option)
get_float(option)
get_int(option)
get_list(option)
get_raw(option)
get_string(option)
restore()
set_boolean(option, value)
set_float(option, value)
set_int(option, value)
set_list(option, value)
set_raw(option, value)
set_string(option, value)

virttest.utils_conn module

virttest.utils_disk module

virttest.utils_env module

virttest.utils_gdb module

virttest.utils_iptables module

virttest.utils_libguestfs module

virttest.utils_libvirtd module

virttest.utils_misc module

virttest.utils_net module

virttest.utils_netperf module

virttest.utils_npiv module

virttest.utils_package module

virttest.utils_params module

virttest.utils_sasl module

virttest.utils_selinux module

virttest.utils_spice module

virttest.utils_v2v module

virttest.utils_virtio_port module

virttest.version module

virttest.versionable_class module

class virttest.versionable_class.Manager(name, wrapper=None)

Bases: object

Manager for module.

Parameters:
  • name (string) – Name of module.
  • wrapper – Module dictionary wrapper. Should be None.
factory(_class, *args, **kargs)

Create new class with right version of subclasses.

Goes through class structure and search subclasses with right version.

Parameters:
  • _class (class.) – Class which should be prepared.
  • args – Params for _is_right_ver function.
Params kargs:

Params for _is_right_ver function.

getcls(cls, orig_class)

Return class correspond class and original class.

Parameters:
  • cls (class) – class for which should be found derived alternative.
  • orig_class (class) – Original class
Returns:

Derived alternative class

Return type:

class

class virttest.versionable_class.ModuleWrapper(wrapped)

Bases: object

Wrapper around module.

Necessary for pickling of dynamic class.

Parameters:wrapped (Module.) – module for wrapping.
class virttest.versionable_class.VersionableClass

Bases: object

Class used for marking of mutable class.

If this method is invoked it means that something went wrong because this class should be replaced by Manager factory.

virttest.versionable_class.factory(orig_cls, *args, **kargs)

Create class with specific version.

Parameters:
  • orig_class – Class from which should be derived good version.
  • args – list of parameters for _ir_right_ver
Params kargs:

dict of named parameters for _ir_right_ver

Returns:

params specific class.

Return type:

class

virttest.versionable_class.isclass(obj)
Parameters:obj – Object for inspection if obj is class.
Returns:true if the object is a class.

virttest.video_maker module

Video Maker transforms screenshots taken during a test into a HTML 5 compatible video, so that one can watch the screen activity of the whole test from inside your own browser.

This relies on generally available multimedia libraries, frameworks and tools.

virttest.video_maker.get_video_maker_klass()
virttest.video_maker.video_maker(input_dir, output_file)

Instantiates the encoder and encodes the input dir.

virttest.virsh module

virttest.virt_admin module

virttest.virt_vm module

virttest.xml_utils module

Utility module standardized on ElementTree 2.6 to minimize dependencies in python 2.4 systems.

Often operations on XML files suggest making a backup copy first is a prudent measure. However, it’s easy to loose track of these temporary files and they can quickly leave a mess behind. The TempXMLFile class helps by trying to clean up the temporary file whenever the instance is deleted, goes out of scope, or an exception is thrown.

The XMLBackup class extends the TempXMLFile class by basing its file- like instances off of an automatically created TempXMLFile instead of pointing at the source. Methods are provided for overwriting the backup copy from the source, or restoring the source from the backup. Similar to TempXMLFile, the temporary backup files are automatically removed. Access to the original source is provided by the sourcefilename attribute.

An interface for querying and manipulating XML data is provided by the XMLTreeFile class. Instances of this class are BOTH file-like and ElementTree-like objects. Whether or not they are constructed from a file or a string, the file-like instance always represents a temporary backup copy. Access to the source (even when itself is temporary) is provided by the sourcefilename attribute, and a (closed) file object attribute sourcebackupfile. See the ElementTree documentation for methods provided by that class.

Finally, the TemplateXML class represents XML templates that support dynamic keyword substitution based on a dictionary. Substitution keys in the XML template (string or file) follow the ‘bash’ variable reference style ($foo or ${bar}). Extension of the parser is possible by subclassing TemplateXML and overriding the ParserClass class attribute. The parser class should be an ElementTree.TreeBuilder class or subclass. Instances of XMLTreeFile are returned by the parse method, which are themselves temporary backups of the parsed content. See the xml_utils_unittest module for examples.

class virttest.xml_utils.Sub(**mapping)

Bases: object

String substituter using string.Template

Initialize substitution mapping.

substitute(text)

Use string.safe_substitute on text and return the result

Parameters:text – string to substitute
class virttest.xml_utils.TempXMLFile(suffix='.xml', prefix='xml_utils_temp_', mode='wb+', buffsz=1)

Bases: file

Temporary XML file auto-removed on instance del / module exit.

Initialize temporary XML file removed on instance destruction.

param: suffix: temporary file’s suffix param: prefix: temporary file’s prefix param: mode: second parameter to file()/open() param: buffer: third parameter to file()/open()

Unconditionally delete file, ignoring related exceptions

class virttest.xml_utils.TemplateXML(xml, **mapping)

Bases: virttest.xml_utils.XMLTreeFile

Template-sourced XML ElementTree backed by temporary file.

Initialize from a XML string or filename, and string.template mapping.

Parameters:
  • xml – A filename or string containing XML
  • mapping – keys/values to feed with XML to string.template
ParserClass

alias of TemplateXMLTreeBuilder

parse(source, parser=None)

Parse source XML file or filename using TemplateXMLTreeBuilder

Parameters:
  • source – XML file or filename
  • parser – ignored
restore()

Raise an IOError to protect the original template source.

class virttest.xml_utils.TemplateXMLTreeBuilder(**mapping)

Bases: virttest.element_tree.XMLTreeBuilder, virttest.xml_utils.Sub

Resolve XML templates into temporary file-backed ElementTrees

Initialize parser that substitutes keys with values in data

Parameters:mapping – values to be substituted for ${key} in XML input
BuilderClass

alias of TreeBuilder

feed(data)
class virttest.xml_utils.XMLBackup(sourcefilename)

Bases: virttest.xml_utils.TempXMLFile

Backup file copy of XML data, automatically removed on instance destruction.

Initialize a temporary backup from sourcefilename.

backup()

Overwrite temporary backup with contents of original source.

restore()

Overwrite original source with contents of temporary backup

sourcefilename = None
class virttest.xml_utils.XMLTreeFile(xml)

Bases: virttest.element_tree.ElementTree, virttest.xml_utils.XMLBackup

Combination of ElementTree root and auto-cleaned XML backup file.

Initialize from a string or filename containing XML source.

param: xml: A filename or string containing XML

backup()

Overwrite original source from current tree

backup_copy()

Return a copy of instance, including copies of files

create_by_xpath(xpath)

Creates all elements in simplistic xpath from root if not exist

get_element_string(xpath)

Returns the string for the element on xpath.

get_parent(element, relative_root=None)

Return the parent node of an element or None

param: element: Element to retrieve parent of param: relative_root: Search only below this element

get_parent_map(element=None)

Return a child to parent mapping dictionary

param: element: Search only below this element

get_xpath(element)

Return the XPath string formed from first-match tag names

read(xml)
remove(element)

Removes a matching subelement.

Parameters:element – element to be removed.
remove_by_xpath(xpath, remove_all=False)

Remove an element found by xpath

Parameters:xpath – element name or path to remove
reroot(xpath)

Return a copy of instance, re-rooted onto xpath

restore()

Overwrite and reparse current tree from original source

sourcebackupfile = None
write(filename=None, encoding='UTF-8')

Write current XML tree to filename, or self.name if None.

virttest.yumrepo module

This module implements classes that allow a user to create, enable and disable YUM repositories on the system.

class virttest.yumrepo.YumRepo(name, baseurl, path=None)

Bases: object

Represents a YUM repository

The goal of this class is not to give access to all features of a YUM Repository, but to provide a simple way to configure a valid one during a test run.

Sample usage:
>>> mainrepo = YumRepo("main", "http://download.project.org/repo",
                       "/etc/yum.repos.d/main.repo")
Or to use a default path:
>>> mainrepo = YumRepo("main", 'http://download.project.org/repo')
And then:
>>> mainrepo.save()

When it comes to the repo URL, currently there’s no support for setting a mirrorlist, only a baseurl.

Initilizes a new YumRepo object

If path is not given, it is assumed to be “$(name)s.repo” at the default YUM repo directory.

Parameters:
  • name – the repository name
  • path – the full path of the file that defines this repository
remove()

Removes the repo file

render()

Renders the repo file

Yes, we could use ConfigParser for this, but it produces files with spaces between keys and values, which look akward by YUM defaults.

save()

Saves the repo file

Module contents