robot.utils package

Various generic utility functions and classes.

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

All utilities are exposed via therobot.utils package, and should beused either like:

fromrobotimportutilsassertutils.Matcher('H?llo').match('Hillo')

or:

fromrobot.utilsimportMatcherassertMatcher('H?llo').match('Hillo')
robot.utils.read_rest_data(rstfile)[source]
robot.utils.unic(item)[source]

Submodules

robot.utils.application module

classrobot.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]
classrobot.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]
classrobot.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 thewhole 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. Valueis a string for those options that can be given only one time (if theyare given multiple times the last value is used) or None if the optionis 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 givenvalues and is empty if options are not used. Options not takenarguments 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 thatcorrect 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 automaticallyif defined in the usage and given from the command line:

–argumentfile can be used to automatically read arguments froma specified file. When –argumentfile is used, the parser alwaysallows using it multiple times. Adding ‘*’ to denote that is thusrecommend. A special value ‘stdin’ can be used to read arguments fromstdin 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 thegiven version. Both help and version are wrapped to Informationexception.

classrobot.utils.argumentparser.ArgLimitValidator(arg_limits)[source]

Bases:object

classrobot.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 youonly need convenient asserts is not so nice)

  • Saved typing and shorter lines because no need to have ‘self.’ beforeasserts. These are static functions after all so that is OK.

  • All ‘equals’ methods (by default) report given values even if optionalmessage given. This behavior can be controlled with the optional valuesargument.

Drawbacks:
  • unittest is not able to filter as much non-interesting traceback awayas with its own methods because AssertionErrors occur outside.

Most of the functions are copied more or less directly from unittest.TestCasewhich comes with the following license. Further information about unittest ingeneral can be found fromhttp://pyunit.sourceforge.net/. This module can beused freely in same terms as unittest.

unittest license:

Copyright(c)1999-2003StevePurcellThismoduleisfreesoftware,andyoumayredistributeitand/ormodifyitunderthesametermsasPythonitself,solongasthiscopyrightmessageanddisclaimerareretainedintheiroriginalform.INNOEVENTSHALLTHEAUTHORBELIABLETOANYPARTYFORDIRECT,INDIRECT,SPECIAL,INCIDENTAL,ORCONSEQUENTIALDAMAGESARISINGOUTOFTHEUSEOFTHISCODE,EVENIFTHEAUTHORHASBEENADVISEDOFTHEPOSSIBILITYOFSUCHDAMAGE.THEAUTHORSPECIFICALLYDISCLAIMSANYWARRANTIES,INCLUDING,BUTNOTLIMITEDTO,THEIMPLIEDWARRANTIESOFMERCHANTABILITYANDFITNESSFORAPARTICULARPURPOSE.THECODEPROVIDEDHEREUNDERISONAN"AS IS"BASIS,ANDTHEREISNOOBLIGATIONWHATSOEVERTOPROVIDEMAINTENANCE,SUPPORT,UPDATES,ENHANCEMENTS,ORMODIFICATIONS.

Examples:

importunittestfromrobot.utils.assertsimportassert_equalclassMyTests(unittest.TestCase):deftest_old_style(self):self.assertEqual(1,2,'my msg')deftest_new_style(self):assert_equal(1,2,'my msg')

Example output:

FF======================================================================FAIL:test_old_style(example.MyTests)----------------------------------------------------------------------Traceback(mostrecentcalllast):File"example.py",line7,intest_old_styleself.assertEqual(1,2,'my msg')AssertionError:mymsg======================================================================FAIL:test_new_style(example.MyTests)----------------------------------------------------------------------Traceback(mostrecentcalllast):File"example.py",line10,intest_new_styleassert_equal(1,2,'my msg')File"/path/to/robot/utils/asserts.py",line181,inassert_equal_report_inequality_failure(first,second,msg,values,'!=')File"/path/to/robot/utils/asserts.py",line229,in_report_inequality_failureraiseAssertionError(msg)AssertionError:mymsg:1!=2----------------------------------------------------------------------Ran2testsin0.000sFAILED(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 argumentskwargs. If a different type of exception is thrown, it will not becaught, and the test case will be deemed to have suffered anerror, exactly as for an unexpected exception.

If a correct exception is raised, the exception instance is returnedby 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=<functionsafe_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=<functionsafe_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 thegiven number of decimal places (default 7) and comparing to zero.Note that decimal places (from zero) are usually not the same assignificant 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 thegiven number of decimal places (default 7) and comparing to zero.Note that decimal places (from zero) are usually not the same assignificant 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 combiningcharacters 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

classrobot.utils.connectioncache.ConnectionCache(no_current_msg='Noopenconnection.')[source]

Bases:object

Cache for libraries to use with concurrent connections, processes, etc.

The cache stores the registered connections (or other objects) and allowsswitching between them using generated indices, user given aliases orconnection objects themselves. This is useful with any library having a needfor 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.

propertycurrent_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 thecurrent connection.

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

The index of the first connection after initialization, and afterclose_all() orempty_cache(), is 1, second is 2, etc.

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

Switches to the connection specified using theidentifier.

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

Updatescurrent and also returns its new value.

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

Returns the connection specified using theidentifier.

Identifier can be an index (integer or string), an alias, a registeredconnection orNone. If the identifier isNone, returns thecurrent 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 theidentifier.

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

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

resolve_alias_or_index(alias_or_index)[source]

Deprecated in RF 7.0. Useget_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 closingconnections, clients should close connections themselves and useempty_cache() afterward.

empty_cache()[source]

Empties the connection cache.

Indexes of the new connections starts from 1 after this.

classrobot.utils.connectioncache.NoConnection(message)[source]

Bases:object

raise_error()[source]

robot.utils.dotdict module

classrobot.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 configuredusing theencoding argument. In addition to the normal encodings,it is possible to use case-insensitive valuesCONSOLE andSYSTEM touse the system console and system encoding, respectively.

Ifstring is already Unicode, it is returned as-is.

robot.utils.encoding.console_encode(string,encoding=None,errors='replace',stream=<_io.TextIOWrappername='<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 systemconfiguration. In addition to the normal encodings, it is possible to usecase-insensitive valuesCONSOLE andSYSTEM to use the system consoleand system encoding, respectively.

Decodes bytes back to Unicode by default, because Python 3 APIs in generalwork with strings. Useforce=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 itMUST be used to get messages from all exceptions originating outside theframework.

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

Returns error message and details of the last occurred exception.

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

Bases:object

Object wrapping the last occurred exception.

It has attributesmessage,traceback, anderror, wheremessage containsthe message with possible generic exception name removed,traceback containsthe traceback anderror contains the original error instance.

propertymessage
propertytraceback

robot.utils.escaping module

robot.utils.escaping.escape(item)[source]
robot.utils.escaping.glob_escape(item)[source]
classrobot.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

classrobot.utils.etreewrapper.ETSource(source)[source]

Bases:object

robot.utils.filereader module

classrobot.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 apathlib.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 eitherUnicode text or UTF-8 encoded bytes.

  • The third options is giving the source as Unicode text directly.This requires settingaccept_text=True when creating the reader.

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

propertyname:str
read()str[source]
readlines()Iterator[str][source]

robot.utils.frange module

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

Likerange() but accepts float arguments.

robot.utils.htmlformatters module

classrobot.utils.htmlformatters.LinkFormatter[source]

Bases:object

format_url(text)[source]
format_link(text)[source]
classrobot.utils.htmlformatters.LineFormatter[source]

Bases:object

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

Bases:object

format(text)[source]
classrobot.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]
classrobot.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]
classrobot.utils.htmlformatters.ParagraphFormatter(other_formatters)[source]

Bases:_Formatter

format(lines)[source]
classrobot.utils.htmlformatters.TableFormatter[source]

Bases:_Formatter

format(lines)[source]
classrobot.utils.htmlformatters.PreformattedFormatter[source]

Bases:_Formatter

format(lines)[source]
classrobot.utils.htmlformatters.ListFormatter[source]

Bases:_Formatter

format(lines)[source]

robot.utils.importer module

classrobot.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 theinfo method, but other level specificmethods 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 asa string, it must be absolute. Paths given asPath objects can berelative starting from Robot Framework 7.3.

  • instantiate_with_args – When arguments are given, imported classes are automatically initializedusing them.

  • return_source – When true, returns a tuple containing the imported module or classand 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 whichcase it must be in the module search path, or as a path to the file ordirectory implementing the module. Seeimport_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 likemodulename.ClassName. If the class name and module name are same, usingjustCommonName is enough. When importing a class by a path, the classname 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 aresupported (e.g.['positional','name=value']) and arguments are convertedautomatically based on type hints and default values.

If arguments needed when creating an instance are initially embedded intothe name or path likeExample:arg1:arg2, separatesplit_args_from_name_or_path() function can beused to split them before calling this method.

Useimport_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 asPath objects can be relativestarting from Robot Framework 7.3.

The module to import can be specified either as a name, in whichcase it must be in the module search path, or as a path to the file ordirectory implementing the module. Seeimport_class_or_module_by_path()for more information about importing modules by path.

Useimport_class_or_module() if it is desired to get a classfrom 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 asPath objects can be relativestarting from Robot Framework 7.3.

  • instantiate_with_args – When arguments are given, imported classes are automatically initializedusing them.

When importing a Python file, the path must end with.py and theactual file must also exist.

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

classrobot.utils.importer.ByPathImporter(logger,library_import=False)[source]

Bases:_Importer

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

Bases:_Importer

handles(name)[source]
import_(name,get_class=True)[source]
classrobot.utils.importer.DottedImporter(logger,library_import=False)[source]

Bases:_Importer

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

classrobot.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 underlyingjson.loadexcept forobject_pairs_hook. As a special feature, handles duplicateitems so that lists are merged.

load(source:str|bytes|TextIO|Path)Dict[str,object][source]
classrobot.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 underlyingjson.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

classrobot.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 thedesired output file. In the latter case, the file is createdand clients should useclose() method to close it.

  • write_empty – Whether to write empty elements and attributes.

classrobot.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 thedesired output file. In the latter case, the file is createdand clients should useclose() 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]
classrobot.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]
classrobot.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]
classrobot.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 giventext depending onrpa.

If given text istest,test ortask is returned directly. Otherwise,pattern{test} is searched from the text and occurrences replaced withtest ortask.

In both cases matching the wordtest is case-insensitive and the returnedtest ortask has exactly same case as the original.

robot.utils.misc.isatty(stream)[source]
robot.utils.misc.parse_re_flags(flags=None)[source]
classrobot.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 dueto 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 thestring according to the given spec.

By default, string is turned to lower case (actually case-folded) and allwhitespace is removed. Additional characters can be removed by giving theminignore list.

robot.utils.normalizing.normalize_whitespace(string)[source]
classrobot.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/valuepairs.

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

propertynormalized_keys:tuple[str,...]
copy()Self[source]
clear()None. RemoveallitemsfromD.[source]

robot.utils.notset module

classrobot.utils.notset.NotSet[source]

Bases:object

Represents value that is not set.

Can be used instead of the standardNone in cases whereNoneitself is a valid value.

robot.utils.NOT_SET is an instance of this class, but it in same casesit 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

classrobot.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 toname fromcandidates.

format(message,recommendations)[source]

Add recommendations to the given message.

The recommendation string looks like:

<message>Didyoumean:<recommendations[0]><recommendations[1]><recommendations[2]>

robot.utils.restreader module

classrobot.utils.restreader.RobotDataStorage(doctree)[source]

Bases:object

add_data(rows)[source]
get_data()[source]
has_data()[source]
classrobot.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. Turnc: intoc:\ on Windows instead of keeping it asc:.

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. Turnc: intoc:\ on Windows instead ofc:\current\path.

robot.utils.robotpath.get_link_path(target,base)[source]

Returns a relative path totarget frombase.

Ifbase is an existing file, then its parent directory is considered tobe the base. Otherwisebase is assumed to be a directory.

The returned path is URL encoded. On Windows returns an absolute path withfile: 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 atimedelta instance.

The result is rounded according to theround_to argument.Useround_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='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 isdetermined based on the given ‘format’ string as follows. Note that allchecks are case-insensitive.

  • If ‘format’ contains word ‘epoch’ the time is returned in seconds afterthe 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 returnedparts 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 informat ‘2006-02-24 15:08:31’

robot.utils.robottime.parse_timestamp(timestamp:str|datetime)datetime[source]

Parse timestamp in ISO 8601-like formats into adatetime.

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

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

Examples:

2023-09-08T14:34:42.1234562023-09-0814:34:42.123202309081434422023_09_08

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

If the input is adatetime, 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 touse 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/UTCtime 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 bemilliseconds, but that will be changed to seconds in Robot Framework 8.0.Useseconds=True to change the behavior already now and to avoid thedeprecation warning. An alternative is giving the elapsed time asatimedelta.

Ifinclude_millis is True, ‘.mil’ part is omitted.

Support for giving the elapsed time as atimedelta and thesecondsargument 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]

ReturnsTrue orFalse 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 standardbool() function.

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

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

Opposite ofis_truthy().

robot.utils.secret module

classrobot.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 toindicate that onlySecret values are accepted. How to create theseobjects in data and elsewhere is explained in theUser Guide.

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

The string representation of this class does not disclose encapsulatedvalues, so they are not visible in logs even if these objects themselvesare logged. Notice, though, that if a keyword passes the actual valuefurther, it may be logged or otherwise disclosed later.

This class should be imported via therobot.api.types module.

fromrobot.api.typesimportSecretdefexample(username:str,password:Secret):user=authenticate(username,password.value)...

New in Robot Framework 7.4.

robot.utils.setter module

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

@setterdefsource(self,source:str|Path)->Path:returnsourceifisinstance(source,Path)elsePath(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 isreturned.

The above example is equivalent to using the standardproperty asfollows. The main benefit of usingsetter is that it avoids a dummygetter method:

@propertydefsource(self)->Path:returnself._source@source.setterdefsource(self,source:src|Path):self._source=sourceifisinstance(source,Path)elsePath(source)

When usingsetter with__slots__, the special_setter__xxxattributes needs to be added to__slots__ as well. The providedSetterAwareType metaclass can take care of that automatically.

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

Bases:type

Metaclass for adding attributes used bysetter to__slots__.

robot.utils.sortable module

classrobot.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 likeExample: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.typehints module

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

A decorator that applies the signature ofT to any function that it decoratesseehttps://github.com/python/typing/issues/270#issuecomment-555966301 for sourceand discussion.

robot.utils.unic module

robot.utils.unic.safe_str(item)[source]
robot.utils.unic.prepr(item,width=80,sort_dicts=False)[source]
classrobot.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 ofconfigured 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 standardoutput 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 stringand flags indicating whether the representation is ‘readable’and whether the object represents a recursive construct.