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

For more details about East Asian characters and the associated problems see: https://github.com/robotframework/robotframework/issues/604

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: str = 'No open connection.')[source]

Bases: Generic[C]

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.

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

Bases: object

raise_error() NoReturn[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: IO | Path | str | bytes | bytearray)[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

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

Bases: object

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

Bases: _SingleLineFormatter

match(string, 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(string, 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: str | Path, instantiate_with_args: Sequence | None = None, return_source: bool = 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. If a path is given as a string, it must be absolute. Paths given as Path objects can be relative starting from Robot Framework 7.3.

  • 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: str | Path)[source]

Imports Python module based on the given name or path.

Parameters:

name_or_path – Name or path of the module to import. If a path is given as a string, it must be absolute. Paths given as Path objects can be relative starting from Robot Framework 7.3.

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: str | Path, instantiate_with_args: Sequence | None = None)[source]

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

Parameters:
  • path – Path to the module or class to import. If a path is given as a string, it must be absolute. Paths given as Path objects can be relative starting from Robot Framework 7.3.

  • 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, library_import=False)[source]

Bases: _Importer

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

Bases: _Importer

handles(name)[source]
import_(name, get_class=True)[source]
class robot.utils.importer.DottedImporter(logger, library_import=False)[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.json module

class robot.utils.json.JsonLoader(**config)[source]

Bases: object

Generic JSON object loader.

JSON source can be a string or bytes, a path or an open file object. The top level JSON item must always be a dictionary.

Supports the same configuration parameters as the underlying json.load except for object_pairs_hook. As a special feature, handles duplicate items so that lists are merged.

load(source: str | bytes | TextIO | Path) Dict[str, object][source]
class robot.utils.json.JsonDumper(**config)[source]

Bases: object

Generic JSON dumper.

JSON can be written to a file given as a path or as an open file object. If no output is given, JSON is returned as a string.

Supports the same configuration as the underlying json.dump.

dump(data: Dict[str, object], output: None = None) str[source]
dump(data: Dict[str, object], output: TextIO | Path | str) None

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: str | None = None) int[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

class robot.utils.restreader.RobotDataStorage(doctree)[source]

Bases: object

add_data(rows)[source]
get_data()[source]
has_data()[source]
class robot.utils.restreader.RobotCodeBlock(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)[source]

Bases: CodeBlock

run()[source]
robot.utils.restreader.docutils_config()[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_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: Path | str, usage=None)[source]

robot.utils.robotpath module

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: timedelta | int | float | str, round_to: int | None = 3) float[source]

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

Time can also be given as an integer or float or, starting from RF 6.0.1, as a timedelta instance.

The result is rounded according to the round_to argument. Use round_to=None to disable rounding altogether.

robot.utils.robottime.secs_to_timestr(secs: int | float | timedelta, compact=False) str[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 maximum 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]

Deprecated in Robot Framework 7.0. Will be removed in Robot Framework 8.0.

robot.utils.robottime.get_time(format: str = 'timestamp', time_: float | None = None) int | str | list[str][source]

Return the given or current time in requested format.

If time is not given, current time is used. How time is returned is determined 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_timestamp(timestamp: str | datetime) datetime[source]

Parse timestamp in ISO 8601-like formats into a datetime.

Months, days, hours, minutes and seconds must use two digits and year must use four. Microseconds can use up to six digits. All time parts can be omitted.

Separators ‘-’, ‘_’, ‘ ‘, ‘T’, ‘:’ and ‘.’ between date and time components. Separators can also be omitted altogether.

Examples:

2023-09-08T14:34:42.123456
2023-09-08 14:34:42.123
20230908 143442
2023_09_08

This is similar to datetime.fromisoformat, but a little less strict. The standard function is recommended if the input format is known to be accepted.

If the input is a datetime, it is returned as-is.

New in Robot Framework 7.0.

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]

Deprecated in Robot Framework 7.0. Will be removed in Robot Framework 8.0.

robot.utils.robottime.timestamp_to_secs(timestamp, seps=None)[source]

Deprecated in Robot Framework 7.0. Will be removed in Robot Framework 8.0.

robot.utils.robottime.secs_to_timestamp(secs, seps=None, millis=False)[source]

Deprecated in Robot Framework 7.0. Will be removed in Robot Framework 8.0.

robot.utils.robottime.get_elapsed_time(start_time, end_time)[source]

Deprecated in Robot Framework 7.0. Will be removed in Robot Framework 8.0.

robot.utils.robottime.elapsed_time_to_string(elapsed: int | float | timedelta, include_millis: bool = True, seconds: bool = False)[source]

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

Elapsed time as an integer or as a float is currently considered to be milliseconds, but that will be changed to seconds in Robot Framework 8.0. Use seconds=True to change the behavior already now and to avoid the deprecation warning. An alternative is giving the elapsed time as a timedelta.

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

Support for giving the elapsed time as a timedelta and the seconds argument are new in Robot Framework 7.0.

robot.utils.robottypes module

robot.utils.robottypes.is_list_like(item)[source]
robot.utils.robottypes.is_dict_like(item)[source]
robot.utils.robottypes.is_union(item)[source]
robot.utils.robottypes.type_name(item, capitalize=False)[source]

Return “non-technical” type name for objects and types.

For example, ‘integer’ instead of ‘int’ and ‘file’ instead of ‘TextIOWrapper’.

robot.utils.robottypes.type_repr(typ, nested=True)[source]

Return string representation for types.

Aims to look as much as the source code as possible. For example, ‘List[Any]’ instead of ‘typing.List[typing.Any]’.

robot.utils.robottypes.has_args(type)[source]

Helper to check has type valid __args__.

Deprecated in Robot Framework 7.3 and will be removed in Robot Framework 8.0. typing.get_args can be used instead.

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

Returns True or False depending on 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.secret module

class robot.utils.secret.Secret(value: str)[source]

Bases: object

Encapsulates secrets to avoid them being shown in Robot Framework logs.

The typical usage is using this class in library keyword type hints to indicate that only Secret values are accepted. How to create these objects in the data and elsewhere is explained in the User Guide.

The encapsulated value is available in the value attribute, and it is mainly meant to be accessed by library keywords. Values are not hidden or encrypted, so they are available for all code that can access these objects directly or indirectly via Robot Framework APIs.

The string representation of these objects does not disclose encapsulated values, so they are not visible in logs even if these objects themselves are logged. Notice, though, that if a keyword passes the actual value further, it may be logged or otherwise disclosed later.

This class should be imported via the robot.api.types module.

from robot.api.types import Secret


def example(username: str, password: Secret):
    user = authenticate(username, password.value)
    ...

New in Robot Framework 7.4.

robot.utils.setter module

class robot.utils.setter.setter(method: Callable[[T, V], A])[source]

Bases: Generic[T, V, A]

Modify instance attributes only when they are set, not when they are get.

Usage:

@setter
def source(self, source: str|Path) -> Path:
    return source if isinstance(source, Path) else Path(source)

The setter method is called when the attribute is assigned like:

instance.source = 'example.txt'

and the returned value is stored in the instance in an attribute like _setter__source. When the attribute is accessed, the stored value is returned.

The above example is equivalent to using the standard property as follows. The main benefit of using setter is that it avoids a dummy getter method:

@property
def source(self) -> Path:
    return self._source

@source.setter
def source(self, source: src|Path):
    self._source = source if isinstance(source, Path) else Path(source)

When using setter with __slots__, the special _setter__xxx attributes needs to be added to __slots__ as well. The provided SetterAwareType metaclass can take care of that automatically.

class robot.utils.setter.SetterAwareType(name, bases, dct)[source]

Bases: type

Metaclass for adding attributes used by setter to __slots__.

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, items=None, 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.expand_variables(string, mapping=None)[source]

Expands variables in the string based on the mapping.

If mapping is not given, defaults to using os.environ. Variable names are limited to ASCII letters, numbers and underscores, and they cannot start with a number.

This is similar to os.path.expandvars, but there are certain differences:

  • Only $NAME and ${NAME} styles are supported, %NAME% is not.

  • Non-existing variables cause a ValueError.

  • Escaping is possible by doubling the dollar sign like $$XXX.

  • Default values are supported with syntax ${NAME=default}.

New in Robot Framework 7.4.

class robot.utils.text.TemplateWithDefaults(template)[source]

Bases: Template

braceidpattern = '(?a:[_a-z][_a-z0-9]*(=[^}]*)?)'
substitute(mapping=None, /, **kwds)[source]
safe_substitute(mapping=None, /, **kwds)[source]
flags = 2
pattern = re.compile('\n            \\$(?:\n              (?P<escaped>\\$)  |   # Escape sequence of two delimiters\n              (?P<named>(?a:[_a-z][_a-z0-9]*))       |   # delimiter and a Python identifier\n          , re.IGNORECASE|re.VERBOSE)
class robot.utils.text.NamespaceWithDefaults(data=None, /, **extra)[source]

Bases: Mapping

robot.utils.typehints module

robot.utils.typehints.copy_signature(target: T) Callable[[...], T][source]

A decorator that applies the signature of T to any function that it decorates see https://github.com/python/typing/issues/270#issuecomment-555966301 for source and discussion.

robot.utils.unic module

robot.utils.unic.safe_str(item)[source]
robot.utils.unic.prepr(item, width=80, sort_dicts=False)[source]
class robot.utils.unic.PrettyRepr(indent=1, width=80, depth=None, stream=None, *, compact=False, sort_dicts=True, underscore_numbers=False)[source]

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

compact

If true, several items will be combined in one line.

sort_dicts

If true, dict keys are sorted.

underscore_numbers

If true, digit groups are separated with underscores.

format(object, context, maxlevels, level)[source]

Format object for a specific context, returning a string and flags indicating whether the representation is ‘readable’ and whether the object represents a recursive construct.