robot.utils package

Various generic utility functions and classes.

Utilities are mainly for internal usage, but external libraries and tools may find some of them useful. Utilities are generally stable, but absolute backwards compatibility between major versions is not guaranteed.

All utilities are exposed via the robot.utils package, and should be used either like:

from robot import utils

assert utils.Matcher('H?llo').match('Hillo')

or:

from robot.utils import Matcher

assert Matcher('H?llo').match('Hillo')
robot.utils.read_rest_data(rstfile)[source]

Submodules

robot.utils.application module

class robot.utils.application.Application(usage, name=None, version=None, arg_limits=None, env_options=None, logger=None, **auto_options)[source]

Bases: object

main(arguments, **options)[source]
validate(options, arguments)[source]
execute_cli(cli_arguments, exit=True)[source]
console(msg)[source]
parse_arguments(cli_args)[source]

Public interface for parsing command line arguments.

Parameters:cli_args – Command line arguments as a list
Returns:options (dict), arguments (list)
Raises:Information when –help or –version used
Raises:DataError when parsing fails
execute(*arguments, **options)[source]
class robot.utils.application.DefaultLogger[source]

Bases: object

info(message)[source]
error(message)[source]
close()[source]

robot.utils.argumentparser module

robot.utils.argumentparser.cmdline2list(args, escaping=False)[source]
class robot.utils.argumentparser.ArgumentParser(usage, name=None, version=None, arg_limits=None, validator=None, env_options=None, auto_help=True, auto_version=True, auto_pythonpath=True, auto_argumentfile=True)[source]

Bases: object

Available options and tool name are read from the usage.

Tool name is got from the first row of the usage. It is either the whole row or anything before first ‘ – ‘.

parse_args(args)[source]

Parse given arguments and return options and positional arguments.

Arguments must be given as a list and are typically sys.argv[1:].

Options are returned as a dictionary where long options are keys. Value is a string for those options that can be given only one time (if they are given multiple times the last value is used) or None if the option is not used at all. Value for options that can be given multiple times (denoted with ‘*’ in the usage) is a list which contains all the given values and is empty if options are not used. Options not taken arguments have value False when they are not set and True otherwise.

Positional arguments are returned as a list in the order they are given.

If ‘check_args’ is True, this method will automatically check that correct number of arguments, as parsed from the usage line, are given. If the last argument in the usage line ends with the character ‘s’, the maximum number of arguments is infinite.

Possible errors in processing arguments are reported using DataError.

Some options have a special meaning and are handled automatically if defined in the usage and given from the command line:

–argumentfile can be used to automatically read arguments from a specified file. When –argumentfile is used, the parser always allows using it multiple times. Adding ‘*’ to denote that is thus recommend. A special value ‘stdin’ can be used to read arguments from stdin instead of a file.

–pythonpath can be used to add extra path(s) to sys.path.

–help and –version automatically generate help and version messages. Version is generated based on the tool name and version – see __init__ for information how to set them. Help contains the whole usage given to __init__. Possible <VERSION> text in the usage is replaced with the given version. Both help and version are wrapped to Information exception.

class robot.utils.argumentparser.ArgLimitValidator(arg_limits)[source]

Bases: object

class robot.utils.argumentparser.ArgFileParser(options)[source]

Bases: object

process(args)[source]

robot.utils.asserts module

Convenience functions for testing both in unit and higher levels.

Benefits:
  • Integrates 100% with unittest (see example below)
  • Can be easily used without unittest (using unittest.TestCase when you only need convenient asserts is not so nice)
  • Saved typing and shorter lines because no need to have ‘self.’ before asserts. These are static functions after all so that is OK.
  • All ‘equals’ methods (by default) report given values even if optional message given. This behavior can be controlled with the optional values argument.
Drawbacks:
  • unittest is not able to filter as much non-interesting traceback away as with its own methods because AssertionErrors occur outside.

Most of the functions are copied more or less directly from unittest.TestCase which comes with the following license. Further information about unittest in general can be found from http://pyunit.sourceforge.net/. This module can be used freely in same terms as unittest.

unittest license:

Copyright (c) 1999-2003 Steve Purcell
This module is free software, and you may redistribute it and/or modify
it under the same terms as Python itself, so long as this copyright message
and disclaimer are retained in their original form.

IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF
THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.

THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE.  THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS,
AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

Examples:

import unittest
from robot.utils.asserts import assert_equal

class MyTests(unittest.TestCase):

    def test_old_style(self):
        self.assertEqual(1, 2, 'my msg')

    def test_new_style(self):
        assert_equal(1, 2, 'my msg')

Example output:

FF
======================================================================
FAIL: test_old_style (example.MyTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "example.py", line 7, in test_old_style
    self.assertEqual(1, 2, 'my msg')
AssertionError: my msg

======================================================================
FAIL: test_new_style (example.MyTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "example.py", line 10, in test_new_style
    assert_equal(1, 2, 'my msg')
  File "/path/to/robot/utils/asserts.py", line 181, in assert_equal
    _report_inequality_failure(first, second, msg, values, '!=')
  File "/path/to/robot/utils/asserts.py", line 229, in _report_inequality_failure
    raise AssertionError(msg)
AssertionError: my msg: 1 != 2

----------------------------------------------------------------------
Ran 2 tests in 0.000s

FAILED (failures=2)
robot.utils.asserts.fail(msg=None)[source]

Fail test immediately with the given message.

robot.utils.asserts.assert_false(expr, msg=None)[source]

Fail the test if the expression is True.

robot.utils.asserts.assert_true(expr, msg=None)[source]

Fail the test unless the expression is True.

robot.utils.asserts.assert_not_none(obj, msg=None, values=True)[source]

Fail the test if given object is None.

robot.utils.asserts.assert_none(obj, msg=None, values=True)[source]

Fail the test if given object is not None.

robot.utils.asserts.assert_raises(exc_class, callable_obj, *args, **kwargs)[source]

Fail unless an exception of class exc_class is thrown by callable_obj.

callable_obj is invoked with arguments args and keyword arguments kwargs. If a different type of exception is thrown, it will not be caught, and the test case will be deemed to have suffered an error, exactly as for an unexpected exception.

If a correct exception is raised, the exception instance is returned by this method.

robot.utils.asserts.assert_raises_with_msg(exc_class, expected_msg, callable_obj, *args, **kwargs)[source]

Similar to fail_unless_raises but also checks the exception message.

robot.utils.asserts.assert_equal(first, second, msg=None, values=True, formatter=None)[source]

Fail if given objects are unequal as determined by the ‘==’ operator.

robot.utils.asserts.assert_not_equal(first, second, msg=None, values=True, formatter=None)[source]

Fail if given objects are equal as determined by the ‘==’ operator.

robot.utils.asserts.assert_almost_equal(first, second, places=7, msg=None, values=True)[source]

Fail if the two objects are unequal after rounded to given places.

inequality is determined by object’s difference rounded to the given number of decimal places (default 7) and comparing to zero. Note that decimal places (from zero) are usually not the same as significant digits (measured from the most significant digit).

robot.utils.asserts.assert_not_almost_equal(first, second, places=7, msg=None, values=True)[source]

Fail if the two objects are unequal after rounded to given places.

Equality is determined by object’s difference rounded to to the given number of decimal places (default 7) and comparing to zero. Note that decimal places (from zero) are usually not the same as significant digits (measured from the most significant digit).

robot.utils.charwidth module

A module to handle different character widths on the console.

Some East Asian characters have width of two on console, and combining characters themselves take no extra space.

See issue 604 [1] for more details about East Asian characters. The issue also contains generate_wild_chars.py script that was originally used to create _EAST_ASIAN_WILD_CHARS mapping. An updated version of the script is attached to issue 1096. Big thanks for xieyanbo for the script and the original patch.

Note that Python’s unicodedata module is not used here because importing it takes several seconds on Jython.

[1] https://github.com/robotframework/robotframework/issues/604 [2] https://github.com/robotframework/robotframework/issues/1096

robot.utils.charwidth.get_char_width(char)[source]

robot.utils.compat module

robot.utils.compat.unwrap(func)[source]
robot.utils.compat.unicode_to_str(self)[source]
robot.utils.compat.py2to3(cls)[source]

Deprecated since RF 4.0. Use ‘py3to2’ instead.

robot.utils.compat.py3to2(cls)[source]
robot.utils.compat.with_metaclass(meta, *bases)[source]

Create a base class with a metaclass.

robot.utils.compat.isatty(stream)[source]

robot.utils.compress module

robot.utils.compress.compress_text(text)[source]

robot.utils.connectioncache module

class robot.utils.connectioncache.ConnectionCache(no_current_msg='No open connection.')[source]

Bases: object

Cache for test libs to use with concurrent connections, processes, etc.

The cache stores the registered connections (or other objects) and allows switching between them using generated indices or user given aliases. This is useful with any test library where there’s need for multiple concurrent connections, processes, etc.

This class can, and is, used also outside the core framework by SSHLibrary, Selenium(2)Library, etc. Backwards compatibility is thus important when doing changes.

current = None

Current active connection.

current_index
register(connection, alias=None)[source]

Registers given connection with optional alias and returns its index.

Given connection is set to be the current connection.

If alias is given, it must be a string. Aliases are case and space insensitive.

The index of the first connection after initialization, and after close_all() or empty_cache(), is 1, second is 2, etc.

switch(alias_or_index)[source]

Switches to the connection specified by the given alias or index.

Updates current and also returns its new value.

Alias is whatever was given to register() method and indices are returned by it. Index can be given either as an integer or as a string that can be converted to an integer. Raises an error if no connection with the given index or alias found.

get_connection(alias_or_index=None)[source]

Get the connection specified by the given alias or index..

If alias_or_index is None, returns the current connection if it is active, or raises an error if it is not.

Alias is whatever was given to register() method and indices are returned by it. Index can be given either as an integer or as a string that can be converted to an integer. Raises an error if no connection with the given index or alias found.

close_all(closer_method='close')[source]

Closes connections using given closer method and empties cache.

If simply calling the closer method is not adequate for closing connections, clients should close connections themselves and use empty_cache() afterwards.

empty_cache()[source]

Empties the connection cache.

Indexes of the new connections starts from 1 after this.

resolve_alias_or_index(alias_or_index)[source]
class robot.utils.connectioncache.NoConnection(message)[source]

Bases: object

raise_error()[source]

robot.utils.dotdict module

class robot.utils.dotdict.DotDict(*args, **kwds)[source]

Bases: collections.OrderedDict

clear() → None. Remove all items from od.
copy() → a shallow copy of od
classmethod fromkeys(S[, v]) → New ordered dictionary with keys from S.

If not specified, the value defaults to None.

get(k[, d]) → D[k] if k in D, else d. d defaults to None.
has_key(k) → True if D has a key k, else False
items() → list of (key, value) pairs in od
iteritems()

od.iteritems -> an iterator over the (key, value) pairs in od

iterkeys() → an iterator over the keys in od
itervalues()

od.itervalues -> an iterator over the values in od

keys() → list of keys in od
pop(k[, d]) → v, remove specified key and return the corresponding

value. If key is not found, d is returned if given, otherwise KeyError is raised.

popitem() → (k, v), return and remove a (key, value) pair.

Pairs are returned in LIFO order if last is true or FIFO order if false.

setdefault(k[, d]) → od.get(k,d), also set od[k]=d if k not in od
update([E, ]**F) → None. Update D from mapping/iterable E and F.

If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v

values() → list of values in od
viewitems() → a set-like object providing a view on od's items
viewkeys() → a set-like object providing a view on od's keys
viewvalues() → an object providing a view on od's values

robot.utils.encoding module

robot.utils.encoding.console_decode(string, encoding='UTF-8', force=False)[source]

Decodes bytes from console encoding to Unicode.

By default uses the system console encoding, but that can be configured using the encoding argument. In addition to the normal encodings, it is possible to use case-insensitive values CONSOLE and SYSTEM to use the system console and system encoding, respectively.

By default returns Unicode strings as-is. The force argument can be used on IronPython where all strings are unicode and caller knows decoding is needed.

robot.utils.encoding.console_encode(string, errors='replace', stream=<open file '<stdout>', mode 'w'>)[source]

Encodes Unicode to bytes in console or system encoding.

Determines the encoding to use based on the given stream and system configuration. On Python 3 and IronPython returns Unicode, otherwise returns bytes.

robot.utils.encoding.system_decode(string)[source]

Decodes bytes from system (e.g. cli args or env vars) to Unicode.

Depending on the usage, at least cli args may already be Unicode.

robot.utils.encoding.system_encode(string, errors='replace')[source]

Encodes Unicode to system encoding (e.g. cli args and env vars).

Non-Unicode values are first converted to Unicode.

robot.utils.encodingsniffer module

robot.utils.encodingsniffer.get_system_encoding()[source]
robot.utils.encodingsniffer.get_console_encoding()[source]

robot.utils.error module

robot.utils.error.get_error_message()[source]

Returns error message of the last occurred exception.

This method handles also exceptions containing unicode messages. Thus it MUST be used to get messages from all exceptions originating outside the framework.

robot.utils.error.get_error_details(exclude_robot_traces=True)[source]

Returns error message and details of the last occurred exception.

robot.utils.error.ErrorDetails(exc_info=None, exclude_robot_traces=True)[source]

This factory returns an object that wraps the last occurred exception

It has attributes message, traceback and error, where message contains type and message of the original error, traceback contains the traceback/stack trace and error contains the original error instance.

class robot.utils.error.PythonErrorDetails(exc_type, exc_value, exc_traceback, exclude_robot_traces=True)[source]

Bases: robot.utils.error._ErrorDetails

message
traceback
class robot.utils.error.JavaErrorDetails(exc_type, exc_value, exc_traceback, exclude_robot_traces=True)[source]

Bases: robot.utils.error._ErrorDetails

message
traceback

robot.utils.escaping module

robot.utils.escaping.escape(item)[source]
robot.utils.escaping.glob_escape(item)[source]
class robot.utils.escaping.Unescaper[source]

Bases: object

unescape(item)[source]
robot.utils.escaping.split_from_equals(string)[source]

robot.utils.etreewrapper module

class robot.utils.etreewrapper.ETSource(source)[source]

Bases: object

robot.utils.filereader module

class robot.utils.filereader.FileReader(source, accept_text=False)[source]

Bases: object

Utility to ease reading different kind of files.

Supports different sources where to read the data:

  • The source can be a path to a file, either as a string or as a pathlib.Path instance in Python 3. The file itself must be UTF-8 encoded.
  • Alternatively the source can be an already opened file object, including a StringIO or BytesIO object. The file can contain either Unicode text or UTF-8 encoded bytes.
  • The third options is giving the source as Unicode text directly. This requires setting accept_text=True when creating the reader.

In all cases bytes are automatically decoded to Unicode and possible BOM removed.

read()[source]
readlines()[source]

robot.utils.frange module

robot.utils.frange.frange(*args)[source]

Like range() but accepts float arguments.

robot.utils.htmlformatters module

class robot.utils.htmlformatters.LinkFormatter[source]

Bases: object

format_url(text)[source]
class robot.utils.htmlformatters.LineFormatter[source]

Bases: object

handles(line)
newline = '\n'
format(line)[source]
class robot.utils.htmlformatters.HtmlFormatter[source]

Bases: object

format(text)[source]
class robot.utils.htmlformatters.RulerFormatter[source]

Bases: robot.utils.htmlformatters._SingleLineFormatter

match()

match(string[, pos[, endpos]]) –> match object or None. Matches zero or more characters at the beginning of the string

format_line(line)[source]
add(line)
end()
format(lines)
handles(line)
class robot.utils.htmlformatters.HeaderFormatter[source]

Bases: robot.utils.htmlformatters._SingleLineFormatter

match()

match(string[, pos[, endpos]]) –> match object or None. Matches zero or more characters at the beginning of the string

format_line(line)[source]
add(line)
end()
format(lines)
handles(line)
class robot.utils.htmlformatters.ParagraphFormatter(other_formatters)[source]

Bases: robot.utils.htmlformatters._Formatter

format(lines)[source]
add(line)
end()
handles(line)
class robot.utils.htmlformatters.TableFormatter[source]

Bases: robot.utils.htmlformatters._Formatter

format(lines)[source]
add(line)
end()
handles(line)
class robot.utils.htmlformatters.PreformattedFormatter[source]

Bases: robot.utils.htmlformatters._Formatter

format(lines)[source]
add(line)
end()
handles(line)
class robot.utils.htmlformatters.ListFormatter[source]

Bases: robot.utils.htmlformatters._Formatter

format(lines)[source]
add(line)
end()
handles(line)

robot.utils.importer module

robot.utils.importer.invalidate_import_caches()
class robot.utils.importer.Importer(type=None, logger=None)[source]

Bases: object

Utility that can import modules and classes based on names and paths.

Imported classes can optionally be instantiated automatically.

Parameters:
  • type – Type of the thing being imported. Used in error and log messages.
  • logger – Logger to be notified about successful imports and other events. Currently only needs the info method, but other level specific methods may be needed in the future. If not given, logging is disabled.
import_class_or_module(name_or_path, instantiate_with_args=None, return_source=False)[source]

Imports Python class/module or Java class based on the given name or path.

Parameters:
  • name_or_path – Name or path of the module or class to import.
  • instantiate_with_args – When arguments are given, imported classes are automatically initialized using them.
  • return_source – When true, returns a tuple containing the imported module or class and a path to it. By default returns only the imported module or class.

The class or module to import can be specified either as a name, in which case it must be in the module search path, or as a path to the file or directory implementing the module. See import_class_or_module_by_path() for more information about importing classes and modules by path.

Classes can be imported from the module search path using name like modulename.ClassName. If the class name and module name are same, using just CommonName is enough. When importing a class by a path, the class name and the module name must match.

Optional arguments to use when creating an instance are given as a list. Starting from Robot Framework 4.0, both positional and named arguments are supported (e.g. ['positional', 'name=value']) and arguments are converted automatically based on type hints and default values.

If arguments needed when creating an instance are initially embedded into the name or path like Example:arg1:arg2, separate split_args_from_name_or_path() function can be used to split them before calling this method.

import_class_or_module_by_path(path, instantiate_with_args=None)[source]

Import a Python module or Java class using a file system path.

Parameters:
  • path – Path to the module or class to import.
  • instantiate_with_args – When arguments are given, imported classes are automatically initialized using them.

When importing a Python file, the path must end with .py and the actual file must also exist. When importing Java classes, the path must end with .java or .class. The Java class file must exist in both cases and in the former case also the source file must exist.

Use import_class_or_module() to support importing also using name, not only path. See the documentation of that function for more information about creating instances automatically.

class robot.utils.importer.ByPathImporter(logger)[source]

Bases: robot.utils.importer._Importer

handles(path)[source]
import_(path)[source]
class robot.utils.importer.NonDottedImporter(logger)[source]

Bases: robot.utils.importer._Importer

handles(name)[source]
import_(name)[source]
class robot.utils.importer.DottedImporter(logger)[source]

Bases: robot.utils.importer._Importer

handles(name)[source]
import_(name)[source]
class robot.utils.importer.NoLogger[source]

Bases: object

error(*args, **kws)
warn(*args, **kws)
info(*args, **kws)
debug(*args, **kws)
trace(*args, **kws)

robot.utils.markuputils module

robot.utils.markuputils.html_escape(text, linkify=True)[source]
robot.utils.markuputils.xml_escape(text)[source]
robot.utils.markuputils.html_format(text)[source]
robot.utils.markuputils.attribute_escape(attr)[source]

robot.utils.markupwriters module

class robot.utils.markupwriters.HtmlWriter(output, write_empty=True, usage=None)[source]

Bases: robot.utils.markupwriters._MarkupWriter

Parameters:
  • output – Either an opened, file like object, or a path to the desired output file. In the latter case, the file is created and clients should use close() method to close it.
  • write_empty – Whether to write empty elements and attributes.
close()

Closes the underlying output file.

content(content=None, escape=True, newline=False)
element(name, content=None, attrs=None, escape=True, newline=True)
end(name, newline=True)
start(name, attrs=None, newline=True)
class robot.utils.markupwriters.XmlWriter(output, write_empty=True, usage=None)[source]

Bases: robot.utils.markupwriters._MarkupWriter

Parameters:
  • output – Either an opened, file like object, or a path to the desired output file. In the latter case, the file is created and clients should use close() method to close it.
  • write_empty – Whether to write empty elements and attributes.
element(name, content=None, attrs=None, escape=True, newline=True)[source]
close()

Closes the underlying output file.

content(content=None, escape=True, newline=False)
end(name, newline=True)
start(name, attrs=None, newline=True)
class robot.utils.markupwriters.NullMarkupWriter(**kwargs)[source]

Bases: object

Null implementation of the _MarkupWriter interface.

start(**kwargs)
content(**kwargs)
element(**kwargs)
end(**kwargs)
close(**kwargs)

robot.utils.match module

robot.utils.match.eq(str1, str2, ignore=(), caseless=True, spaceless=True)[source]
class robot.utils.match.Matcher(pattern, ignore=(), caseless=True, spaceless=True, regexp=False)[source]

Bases: object

match(string)[source]
match_any(strings)[source]
class robot.utils.match.MultiMatcher(patterns=None, ignore=(), caseless=True, spaceless=True, match_if_no_patterns=False, regexp=False)[source]

Bases: object

match(string)[source]
match_any(strings)[source]

robot.utils.misc module

robot.utils.misc.roundup(number, ndigits=0, return_type=None)[source]

Rounds number to the given number of digits.

Numbers equally close to a certain precision are always rounded away from zero. By default return value is float when ndigits is positive and int otherwise, but that can be controlled with return_type.

With the built-in round() rounding equally close numbers as well as the return type depends on the Python version.

robot.utils.misc.printable_name(string, code_style=False)[source]

Generates and returns printable name from the given string.

Examples: ‘simple’ -> ‘Simple’ ‘name with spaces’ -> ‘Name With Spaces’ ‘more spaces’ -> ‘More Spaces’ ‘Cases AND spaces’ -> ‘Cases AND Spaces’ ‘’ -> ‘’

If ‘code_style’ is True:

‘mixedCAPSCamel’ -> ‘Mixed CAPS Camel’ ‘camelCaseName’ -> ‘Camel Case Name’ ‘under_score_name’ -> ‘Under Score Name’ ‘under_and space’ -> ‘Under And Space’ ‘miXed_CAPS_nAMe’ -> ‘MiXed CAPS NAMe’ ‘’ -> ‘’

robot.utils.misc.plural_or_not(item)[source]
robot.utils.misc.seq2str(sequence, quote="'", sep=', ', lastsep=' and ')[source]

Returns sequence in format ‘item 1’, ‘item 2’ and ‘item 3’.

robot.utils.misc.seq2str2(sequence)[source]

Returns sequence in format [ item 1 | item 2 | … ].

robot.utils.misc.test_or_task(text, rpa=False)[source]

Replaces {test} in text with test or task depending on rpa.

robot.utils.normalizing module

robot.utils.normalizing.normalize(string, ignore=(), caseless=True, spaceless=True)[source]

Normalizes given string according to given spec.

By default string is turned to lower case and all whitespace is removed. Additional characters can be removed by giving them in ignore list.

robot.utils.normalizing.normalize_whitespace(string)[source]
robot.utils.normalizing.lower(string)[source]
class robot.utils.normalizing.NormalizedDict(initial=None, ignore=(), caseless=True, spaceless=True)[source]

Bases: _abcoll.MutableMapping

Custom dictionary implementation automatically normalizing keys.

Initialized with possible initial value and normalizing spec.

Initial values can be either a dictionary or an iterable of name/value pairs. In the latter case items are added in the given order.

Normalizing spec has exact same semantics as with the normalize() function.

copy()[source]
clear() → None. Remove all items from D.[source]
get(k[, d]) → D[k] if k in D, else d. d defaults to None.
items() → list of D's (key, value) pairs, as 2-tuples
iteritems() → an iterator over the (key, value) items of D
iterkeys() → an iterator over the keys of D
itervalues() → an iterator over the values of D
keys() → list of D's keys
pop(k[, d]) → v, remove specified key and return the corresponding value.

If key is not found, d is returned if given, otherwise KeyError is raised.

popitem() → (k, v), remove and return some (key, value) pair

as a 2-tuple; but raise KeyError if D is empty.

setdefault(k[, d]) → D.get(k,d), also set D[k]=d if k not in D
update([E, ]**F) → None. Update D from mapping/iterable E and F.

If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v

values() → list of D's values

robot.utils.platform module

robot.utils.recommendations module

class robot.utils.recommendations.RecommendationFinder(normalizer=None)[source]

Bases: object

find_and_format(name, candidates, message, max_matches=10)[source]
find(name, candidates, max_matches=10)[source]

Return a list of close matches to name from candidates.

format(message, recommendations=None)[source]

Add recommendations to the given message.

The recommendation string looks like:

<message> Did you mean:
    <recommendations[0]>
    <recommendations[1]>
    <recommendations[2]>

robot.utils.restreader module

class robot.utils.restreader.CaptureRobotData(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)[source]

Bases: docutils.parsers.rst.directives.body.CodeBlock

run()[source]
add_name(node)

Append self.options[‘name’] to node[‘names’] if it exists.

Also normalize the name string and register it as explicit target.

assert_has_content()

Throw an ERROR-level DirectiveError if the directive doesn’t have contents.

debug(message)
directive_error(level, message)

Return a DirectiveError suitable for being thrown as an exception.

Call “raise self.directive_error(level, message)” from within a directive implementation to return one single system message at level level, which automatically gets the directive block and the line number added.

Preferably use the debug, info, warning, error, or severe wrapper methods, e.g. self.error(message) to generate an ERROR-level directive error.

error(message)
final_argument_whitespace = False
has_content = True
info(message)
option_spec = {'class': <function class_option>, 'name': <function unchanged>, 'number-lines': <function unchanged>}
optional_arguments = 1
required_arguments = 0
severe(message)
warning(message)
class robot.utils.restreader.RobotDataStorage(doctree)[source]

Bases: object

add_data(rows)[source]
get_data()[source]
has_data()[source]
robot.utils.restreader.read_rest_data(rstfile)[source]

robot.utils.robotenv module

robot.utils.robotenv.get_env_var(name, default=None)[source]
robot.utils.robotenv.set_env_var(name, value)[source]
robot.utils.robotenv.del_env_var(name)[source]
robot.utils.robotenv.get_env_vars(upper=False)[source]

robot.utils.robotinspect module

robot.utils.robotinspect.is_java_init(init)[source]
robot.utils.robotinspect.is_java_method(method)[source]
robot.utils.robotinspect.is_init(method)[source]

robot.utils.robotio module

robot.utils.robotio.file_writer(path=None, encoding='UTF-8', newline=None, usage=None)[source]
robot.utils.robotio.binary_file_writer(path=None)[source]
robot.utils.robotio.create_destination_directory(path, usage=None)[source]

robot.utils.robotpath module

robot.utils.robotpath.path_to_url(path)[source]
robot.utils.robotpath.normpath(path, case_normalize=False)[source]

Replacement for os.path.normpath with some enhancements.

  1. Convert non-Unicode paths to Unicode using the file system encoding.
  2. NFC normalize Unicode paths (affects mainly OSX).
  3. Optionally lower-case paths on case-insensitive file systems. That includes Windows and also OSX in default configuration.
  4. Turn c: into c:\ on Windows instead of keeping it as c:.
robot.utils.robotpath.abspath(path, case_normalize=False)[source]

Replacement for os.path.abspath with some enhancements and bug fixes.

  1. Non-Unicode paths are converted to Unicode using file system encoding.
  2. Optionally lower-case paths on case-insensitive file systems. That includes Windows and also OSX in default configuration.
  3. Turn c: into c:\ on Windows instead of c:\current\path.

Returns a relative path to target from base.

If base is an existing file, then its parent directory is considered to be the base. Otherwise base is assumed to be a directory.

The returned path is URL encoded. On Windows returns an absolute path with file: prefix if the target is on a different drive.

robot.utils.robotpath.find_file(path, basedir='.', file_type=None)[source]

robot.utils.robottime module

robot.utils.robottime.timestr_to_secs(timestr, round_to=3)[source]

Parses time like ‘1h 10s’, ‘01:00:10’ or ‘42’ and returns seconds.

robot.utils.robottime.secs_to_timestr(secs, compact=False)[source]

Converts time in seconds to a string representation.

Returned string is in format like ‘1 day 2 hours 3 minutes 4 seconds 5 milliseconds’ with following rules:

  • Time parts having zero value are not included (e.g. ‘3 minutes 4 seconds’ instead of ‘0 days 0 hours 3 minutes 4 seconds’)
  • Hour part has a maximun of 23 and minutes and seconds both have 59 (e.g. ‘1 minute 40 seconds’ instead of ‘100 seconds’)

If compact has value ‘True’, short suffixes are used. (e.g. 1d 2h 3min 4s 5ms)

robot.utils.robottime.format_time(timetuple_or_epochsecs, daysep='', daytimesep=' ', timesep=':', millissep=None)[source]

Returns a timestamp formatted from given time using separators.

Time can be given either as a timetuple or seconds after epoch.

Timetuple is (year, month, day, hour, min, sec[, millis]), where parts must be integers and millis is required only when millissep is not None. Notice that this is not 100% compatible with standard Python timetuples which do not have millis.

Seconds after epoch can be either an integer or a float.

robot.utils.robottime.get_time(format='timestamp', time_=None)[source]

Return the given or current time in requested format.

If time is not given, current time is used. How time is returned is is deternined based on the given ‘format’ string as follows. Note that all checks are case insensitive.

  • If ‘format’ contains word ‘epoch’ the time is returned in seconds after the unix epoch.
  • If ‘format’ contains any of the words ‘year’, ‘month’, ‘day’, ‘hour’, ‘min’ or ‘sec’ only selected parts are returned. The order of the returned parts is always the one in previous sentence and order of words in ‘format’ is not significant. Parts are returned as zero padded strings (e.g. May -> ‘05’).
  • Otherwise (and by default) the time is returned as a timestamp string in format ‘2006-02-24 15:08:31’
robot.utils.robottime.parse_time(timestr)[source]

Parses the time string and returns its value as seconds since epoch.

Time can be given in five different formats:

  1. Numbers are interpreted as time since epoch directly. It is possible to use also ints and floats, not only strings containing numbers.
  2. Valid timestamp (‘YYYY-MM-DD hh:mm:ss’ and ‘YYYYMMDD hhmmss’).
  3. ‘NOW’ (case-insensitive) is the current local time.
  4. ‘UTC’ (case-insensitive) is the current time in UTC.
  5. Format ‘NOW - 1 day’ or ‘UTC + 1 hour 30 min’ is the current local/UTC time plus/minus the time specified with the time string.

Seconds are rounded down to avoid getting times in the future.

robot.utils.robottime.get_timestamp(daysep='', daytimesep=' ', timesep=':', millissep='.')[source]
robot.utils.robottime.timestamp_to_secs(timestamp, seps=None)[source]
robot.utils.robottime.secs_to_timestamp(secs, seps=None, millis=False)[source]
robot.utils.robottime.get_elapsed_time(start_time, end_time)[source]

Returns the time between given timestamps in milliseconds.

robot.utils.robottime.elapsed_time_to_string(elapsed, include_millis=True)[source]

Converts elapsed time in milliseconds to format ‘hh:mm:ss.mil’.

If include_millis is True, ‘.mil’ part is omitted.

class robot.utils.robottime.TimestampCache[source]

Bases: object

get_timestamp(daysep='', daytimesep=' ', timesep=':', millissep='.')[source]

robot.utils.robottypes module

robot.utils.robottypes.is_truthy(item)[source]

Returns True or False depending is the item considered true or not.

Validation rules:

  • If the value is a string, it is considered false if it is ‘FALSE’, ‘NO’, ‘OFF’, ‘0’, ‘NONE’ or ‘’, case-insensitively.
  • Other strings are considered true.
  • Other values are handled by using the standard bool() function.

Designed to be used also by external test libraries that want to handle Boolean values similarly as Robot Framework itself. See also is_falsy().

robot.utils.robottypes.is_falsy(item)[source]

Opposite of is_truthy().

robot.utils.robottypes2 module

robot.utils.robottypes2.is_integer(item)[source]
robot.utils.robottypes2.is_number(item)[source]
robot.utils.robottypes2.is_bytes(item)[source]
robot.utils.robottypes2.is_string(item)[source]
robot.utils.robottypes2.is_unicode(item)[source]
robot.utils.robottypes2.is_pathlike(item)[source]
robot.utils.robottypes2.is_list_like(item)[source]
robot.utils.robottypes2.is_dict_like(item)[source]
robot.utils.robottypes2.type_name(item, capitalize=False)[source]

robot.utils.robottypes3 module

robot.utils.setter module

class robot.utils.setter.setter(method)[source]

Bases: object

class robot.utils.setter.SetterAwareType[source]

Bases: type

mro() → list

return a type’s method resolution order

robot.utils.sortable module

class robot.utils.sortable.Sortable[source]

Bases: object

Base class for sorting based self._sort_key

robot.utils.text module

robot.utils.text.cut_long_message(msg)[source]
robot.utils.text.format_assign_message(variable, value, cut_long=True)[source]
robot.utils.text.cut_assign_value(value)[source]
robot.utils.text.get_console_length(text)[source]
robot.utils.text.pad_console_length(text, width)[source]
robot.utils.text.split_args_from_name_or_path(name)[source]

Split arguments embedded to name or path like Example:arg1:arg2.

The separator can be either colon : or semicolon ;. If both are used, the first one is considered to be the separator.

robot.utils.text.split_tags_from_doc(doc)[source]
robot.utils.text.getdoc(item)[source]
robot.utils.text.getshortdoc(doc_or_item, linesep='\n')[source]
robot.utils.text.rstrip(string)[source]

robot.utils.unic module

robot.utils.unic.unic(item)[source]
robot.utils.unic.prepr(item, width=80)[source]
class robot.utils.unic.PrettyRepr(indent=1, width=80, depth=None, stream=None)[source]

Bases: pprint.PrettyPrinter

Handle pretty printing operations onto a stream using a set of configured parameters.

indent
Number of spaces to indent for each level of nesting.
width
Attempted maximum number of columns in the output.
depth
The maximum depth to print out nested structures.
stream
The desired output stream. If omitted (or false), the standard output stream available at construction will be used.
format(object, context, maxlevels, level)[source]
isreadable(object)
isrecursive(object)
pformat(object)
pprint(object)