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]
robot.utils.unic(item)[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='DEPRECATED', 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. This functionality was deprecated in Robot Framework 5.0.

–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=<function safe_str>)[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=<function safe_str>)[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.

Python’s unicodedata module was not used here because importing it took several seconds on Jython. That could possibly be changed now.

[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.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 libraries to use with concurrent connections, processes, etc.

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

This class is used also outside the core framework by SeleniumLibrary, SSHLibrary, etc. Backwards compatibility is thus important when doing changes.

current

Current active connection.

property current_index: int | None
register(connection: Any, alias: str | None = 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(identifier: int | str | Any) Any[source]

Switches to the connection specified using the identifier.

Identifier can be an index, an alias, or a registered connection. Raises an error if no matching connection is found.

Updates current and also returns its new value.

get_connection(identifier: int | str | Any | None = None) Any[source]

Returns the connection specified using the identifier.

Identifier can be an index (integer or string), an alias, a registered connection or None. If the identifier is None, returns the current connection if it is active and raises an error if it is not. Raises an error also if no matching connection is found.

get_connection_index(identifier: int | str | Any) int[source]

Returns the index of the connection specified using the identifier.

Identifier can be an index (integer or string), an alias, or a registered connection.

New in Robot Framework 7.0. resolve_alias_or_index() can be used with earlier versions.

resolve_alias_or_index(alias_or_index)[source]

Deprecated in RF 7.0. Use get_connection_index() instead.

close_all(closer_method: str = 'close')[source]

Closes connections using the specified 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() afterward.

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: OrderedDict

robot.utils.encoding module

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

Decodes bytes from console encoding to Unicode.

Uses the system console encoding by default, 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.

If string is already Unicode, it is returned as-is.

robot.utils.encoding.console_encode(string, encoding=None, errors='replace', stream=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, force=False)[source]

Encodes the given string so that it can be used in the console.

If encoding is not given, determines it based on the given stream and system configuration. 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.

Decodes bytes back to Unicode by default, because Python 3 APIs in general work with strings. Use force=True if that is not desired.

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

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(full_traceback=True, exclude_robot_traces=True)[source]

Returns error message and details of the last occurred exception.

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

Bases: object

Object wrapping the last occurred exception.

It has attributes message, traceback, and error, where message contains the message with possible generic exception name removed, traceback contains the traceback and error contains the original error instance.

property message
property 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.unescape(item)
robot.utils.escaping.split_from_equals(value)[source]

robot.utils.etreewrapper module

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

Bases: object

robot.utils.filereader module

class robot.utils.filereader.FileReader(source: Path | str | TextIO, accept_text: bool = False)[source]

Bases: object

Utility to ease reading different kind of source 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. 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.

property name: str
read() str[source]
readlines() Iterator[str][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: _SingleLineFormatter

match(pos=0, endpos=9223372036854775807)

Matches zero or more characters at the beginning of the string.

format_line(line)[source]
class robot.utils.htmlformatters.HeaderFormatter[source]

Bases: _SingleLineFormatter

match(pos=0, endpos=9223372036854775807)

Matches zero or more characters at the beginning of the string.

format_line(line)[source]
class robot.utils.htmlformatters.ParagraphFormatter(other_formatters)[source]

Bases: _Formatter

format(lines)[source]
class robot.utils.htmlformatters.TableFormatter[source]

Bases: _Formatter

format(lines)[source]
class robot.utils.htmlformatters.PreformattedFormatter[source]

Bases: _Formatter

format(lines)[source]
class robot.utils.htmlformatters.ListFormatter[source]

Bases: _Formatter

format(lines)[source]

robot.utils.importer module

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

Use import_module() if only a module needs to be imported.

import_module(name_or_path)[source]

Imports Python module based on the given name or path.

Parameters:

name_or_path – Name or path of the module to import.

The 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 modules by path.

Use import_class_or_module() if it is desired to get a class from the imported module automatically.

New in Robot Framework 6.0.

import_class_or_module_by_path(path, instantiate_with_args=None)[source]

Import a Python module or 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.

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: _Importer

handles(path)[source]
import_(path, get_class=True)[source]
class robot.utils.importer.NonDottedImporter(logger)[source]

Bases: _Importer

handles(name)[source]
import_(name, get_class=True)[source]
class robot.utils.importer.DottedImporter(logger)[source]

Bases: _Importer

handles(name)[source]
import_(name, get_class=True)[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, preamble=True)[source]

Bases: _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.

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

Bases: _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, write_empty=None)[source]
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: str, str2: str, ignore: Sequence[str] = (), caseless: bool = True, spaceless: bool = True) bool[source]
class robot.utils.match.Matcher(pattern: str, ignore: Sequence[str] = (), caseless: bool = True, spaceless: bool = True, regexp: bool = False)[source]

Bases: object

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

Bases: Iterable[Matcher]

match(string: str) bool[source]
match_any(strings: Iterable[str]) bool[source]

robot.utils.misc module

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: str, rpa: bool)[source]

Replace ‘test’ with ‘task’ in the given text depending on rpa.

If given text is test, test or task is returned directly. Otherwise, pattern {test} is searched from the text and occurrences replaced with test or task.

In both cases matching the word test is case-insensitive and the returned test or task has exactly same case as the original.

robot.utils.misc.isatty(stream)[source]
robot.utils.misc.parse_re_flags(flags=None)[source]
class robot.utils.misc.classproperty(fget, fset=None, fdel=None, doc=None)[source]

Bases: property

Property that works with classes in addition to instances.

Only supports getters. Setters and deleters cannot work with classes due to how the descriptor protocol works, and they are thus explicitly disabled. Metaclasses must be used if they are needed.

setter(fset)[source]

Descriptor to obtain a copy of the property with a different setter.

deleter(fset)[source]

Descriptor to obtain a copy of the property with a different deleter.

robot.utils.normalizing module

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

Normalize the string according to the given spec.

By default, string is turned to lower case (actually case-folded) and all whitespace is removed. Additional characters can be removed by giving them in ignore list.

robot.utils.normalizing.normalize_whitespace(string)[source]
class robot.utils.normalizing.NormalizedDict(initial: Mapping[str, V] | Iterable[tuple[str, V]] | None = None, ignore: Sequence[str] = (), caseless: bool = True, spaceless: bool = True)[source]

Bases: MutableMapping[str, V]

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.

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

property normalized_keys: tuple[str, ...]
copy() Self[source]
clear() None.  Remove all items from D.[source]

robot.utils.notset module

class robot.utils.notset.NotSet[source]

Bases: object

Represents value that is not set.

Can be used instead of the standard None in cases where None itself is a valid value.

robot.utils.NOT_SET is an instance of this class, but it in same cases it is better to create a separate instance.

New in Robot Framework 7.0.

robot.utils.platform module

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

robot.utils.recommendations module

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

Bases: object

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

Return a list of close matches to name from candidates.

format(message, recommendations)[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

robot.utils.robotenv module

robot.utils.robotinspect module

robot.utils.robotio module

robot.utils.robotpath module

robot.utils.robottime module

robot.utils.robottypes module

robot.utils.setter module

robot.utils.sortable module

robot.utils.text module

robot.utils.typehints module

robot.utils.unic module