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')

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_escape=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:

–escape option can be used to automatically unescape problematic characters given in an escaped format.

–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. Possible <–ESCAPES–> is replaced with available escapes so that they are wrapped to multiple lines but take the same amount of horizontal space as <—ESCAPES—>. 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)[source]

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

robot.utils.asserts.assert_not_equal(first, second, msg=None, values=True)[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 signficant 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.py2to3(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.

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

Initialize an ordered dictionary. The signature is the same as regular dictionaries, but keyword arguments are not recommended because their insertion order is arbitrary.

clear() → None. Remove all items from od.
copy() → a shallow copy of od
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.

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.unescape(item)[source]
class robot.utils.escaping.Unescaper[source]

Bases: object

unescape(string)[source]
class robot.utils.escaping.EscapeFinder(string)[source]

Bases: object

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

robot.utils.etreewrapper module

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

Bases: object

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

import_class_or_module(name, instantiate_with_args=None, return_source=False)[source]

Imports Python class/module or Java class with given name.

Class can either live in a module/package or be standalone Java class. In the former case the name is something like ‘MyClass’ and in the latter it could be ‘your.package.YourLibrary’. Python classes always live in a module, but if the module name is exactly same as the class name then simple ‘MyLibrary’ will import a class.

Python modules can be imported both using format ‘MyModule’ and ‘mymodule.submodule’.

name can also be a path to the imported file/directory. In that case importing is done using import_class_or_module_by_path method.

If instantiate_with_args is not None, imported classes are instantiated with the specified arguments automatically.

import_class_or_module_by_path(path, instantiate_with_args=None)[source]

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

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 class file must exist in both cases and in the former case also the source file must exist.

If instantiate_with_args is not None, imported classes are instantiated with the specified arguments 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]

robot.utils.markuputils module

robot.utils.markuputils.html_escape(text)[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)[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, replace_newlines=False)
end(name, newline=True)
start(name, attrs=None, newline=True)
class robot.utils.markupwriters.XmlWriter(output, write_empty=True)[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, replace_newlines=False)
end(name, newline=True)
start(name, attrs=None, newline=True)
class robot.utils.markupwriters.NullMarkupWriter(*args, **kwargs)[source]

Bases: object

Null implementation of the _MarkupWriter interface.

start(*args, **kwargs)
content(*args, **kwargs)
element(*args, **kwargs)
end(*args, **kwargs)
close(*args, **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.getdoc(item)[source]

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.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()[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.ordereddict module

class robot.utils.ordereddict.OrderedDict(*args, **kwds)[source]

Bases: dict, UserDict.DictMixin

clear()[source]
popitem(last=True)[source]
keys()[source]
setdefault(key, default=None)
update(other=None, **kwargs)
pop(key, *args)
values()
items()
iterkeys()
itervalues()
iteritems()
copy()[source]
classmethod fromkeys(iterable, value=None)[source]
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
viewitems() → a set-like object providing a view on D's items
viewkeys() → a set-like object providing a view on D's keys
viewvalues() → an object providing a view on D's values

robot.utils.platform module

robot.utils.recommendations module

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

Bases: object

find_recommendations(name, candidates, max_matches=10)[source]

Return a list of close matches to name from candidates.

static format_recommendations(msg, recommendations)[source]

Add recommendations to the given message.

The recommendation string looks like:
<msg> Did you mean: <recommendations[0]> <recommendations[1]> <recommendations[2]>

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.robotio module

robot.utils.robotio.file_writer(path=None, encoding='UTF-8', newline=None)[source]
robot.utils.robotio.binary_file_writer(path=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.
  4. Handle non-ASCII characters on working directory with Python < 2.6.5: http://bugs.python.org/issue3426

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, gmtsep=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 True if it is not FALSE, NO or and empty string, case-insensitively.
  • 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() and is_noney().

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

Opposite of is_truthy().

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

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

Validation rules:

  • If the value is a string, it is considered None if it is equal to NONE, case-insensitively.
  • Otherwise the value is considerd None only if it is the actual None.

Designed to be used also by external test libraries that want to handle NONE similarly as Robot Framework itself. New in Robot Framework 3.0.3. See also is_truthy() and is_falsy().

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_list_like(item)[source]
robot.utils.robottypes2.is_dict_like(item)[source]
robot.utils.robottypes2.type_name(item)[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.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]
robot.utils.text.split_tags_from_doc(doc)[source]

robot.utils.unic module

robot.utils.unic.unic(item)[source]
robot.utils.unic.prepr(item, width=400)[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)

robot.utils.utf8reader module

class robot.utils.utf8reader.Utf8Reader(path_or_file)[source]

Bases: object

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