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')
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- 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:
Informationwhen –help or –version used- Raises:
DataErrorwhen parsing fails
robot.utils.argumentparser module
- 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:
objectAvailable 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.
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.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.compress module
robot.utils.connectioncache module
- classrobot.utils.connectioncache.ConnectionCache(no_current_msg='Noopenconnection.')[source]
Bases:
objectCache 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 the
currentconnection.If alias is given, it must be a string. Aliases are case and spaceinsensitive.
The index of the first connection after initialization, and after
close_all()orempty_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
currentand 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 registeredconnection or
None. 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 the
identifier.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. 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 closingconnections, clients should close connections themselves and use
empty_cache()afterward.
robot.utils.dotdict module
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.encodingsniffer module
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:
objectObject 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.unescape(item)
robot.utils.etreewrapper module
robot.utils.filereader module
- classrobot.utils.filereader.FileReader(source:Path|str|TextIO,accept_text:bool=False)[source]
Bases:
objectUtility 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.Pathinstance. 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 setting
accept_text=Truewhen creating the reader.
In all cases bytes are automatically decoded to Unicode and possibleBOM removed.
- propertyname:str
robot.utils.frange module
robot.utils.htmlformatters module
- classrobot.utils.htmlformatters.RulerFormatter[source]
Bases:
_SingleLineFormatter- match(string,pos=0,endpos=9223372036854775807)
Matches zero or more characters at the beginning of the string.
- classrobot.utils.htmlformatters.HeaderFormatter[source]
Bases:
_SingleLineFormatter- match(string,pos=0,endpos=9223372036854775807)
Matches zero or more characters at the beginning of the string.
robot.utils.importer module
- classrobot.utils.importer.Importer(type=None,logger=None)[source]
Bases:
objectUtility 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
infomethod, 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 as
Pathobjects 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. 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, usingjustCommonNameis 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 like
Example:arg1:arg2, separatesplit_args_from_name_or_path()function can beused 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
Pathobjects 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. 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 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 as
Pathobjects 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
.pyand theactual 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 informationabout creating instances automatically.
robot.utils.json module
- classrobot.utils.json.JsonLoader(**config)[source]
Bases:
objectGeneric 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 for
object_pairs_hook. As a special feature, handles duplicateitems so that lists are merged.
robot.utils.markuputils module
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 use
close()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 use
close()method to close it.write_empty – Whether to write empty elements and attributes.
robot.utils.match module
- robot.utils.match.eq(str1:str,str2:str,ignore:Sequence[str]=(),caseless:bool=True,spaceless:bool=True)→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.seq2str(sequence,quote="'",sep=',',lastsep='and')[source]
Returns sequence in format‘item 1’, ‘item 2’ and ‘item 3’.
- 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.
- classrobot.utils.misc.classproperty(fget,fset=None,fdel=None,doc=None)[source]
Bases:
propertyProperty 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.
robot.utils.normalizing module
- robot.utils.normalizing.normalize(string:str,ignore:Sequence[str]=(),caseless:bool=True,spaceless:bool=True)→str[source]
Normalize the
stringaccording 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 themin
ignorelist.
- 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 the
normalize()function.- propertynormalized_keys:tuple[str,...]
robot.utils.notset module
- classrobot.utils.notset.NotSet[source]
Bases:
objectRepresents value that is not set.
Can be used instead of the standard
Nonein cases whereNoneitself is a valid value.robot.utils.NOT_SETis 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.recommendations module
robot.utils.restreader module
robot.utils.robotenv module
robot.utils.robotinspect module
robot.utils.robotio module
robot.utils.robotpath module
- robot.utils.robotpath.normpath(path,case_normalize=False)[source]
Replacement for os.path.normpath with some enhancements.
Convert non-Unicode paths to Unicode using the file system encoding.
NFC normalize Unicode paths (affects mainly OSX).
Optionally lower-case paths on case-insensitive file systems.That includes Windows and also OSX in default configuration.
Turn
c: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.
Non-Unicode paths are converted to Unicode using file system encoding.
Optionally lower-case paths on case-insensitive file systems.That includes Windows and also OSX in default configuration.
Turn
c:intoc:\on Windows instead ofc:\current\path.
- robot.utils.robotpath.get_link_path(target,base)[source]
Returns a relative path to
targetfrombase.If
baseis an existing file, then its parent directory is considered tobe the base. Otherwisebaseis 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.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 a
datetime.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 to
datetime.fromisoformat, but a little less strict.The standard function is recommended if the input format is known to beaccepted.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:
Numbers are interpreted as time since epoch directly. It is possible touse also ints and floats, not only strings containing numbers.
Valid timestamp (‘YYYY-MM-DD hh:mm:ss’ and ‘YYYYMMDD hhmmss’).
‘NOW’ (case-insensitive) is the current local time.
‘UTC’ (case-insensitive) is the current time in UTC.
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.Use
seconds=Trueto 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 a
timedeltaand thesecondsargument are new in Robot Framework 7.0.
robot.utils.robottypes module
- 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_argscan 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 also
is_falsy().
- robot.utils.robottypes.is_falsy(item)[source]
Opposite of
is_truthy().
robot.utils.secret module
- classrobot.utils.secret.Secret(value:str)[source]
Bases:
objectEncapsulates secrets to avoid them being shown in Robot Framework logs.
The typical usage is using this class in library keyword type hints toindicate that only
Secretvalues are accepted. How to create theseobjects in data and elsewhere is explained in theUser Guide.The encapsulated value is available in the
valueattribute, 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 the
robot.api.typesmodule.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 standard
propertyasfollows. The main benefit of usingsetteris 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 using
setterwith__slots__, the special_setter__xxxattributes needs to be added to__slots__as well. The providedSetterAwareTypemetaclass can take care of that automatically.
robot.utils.sortable module
robot.utils.text module
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
- classrobot.utils.unic.PrettyRepr(indent=1,width=80,depth=None,stream=None,*,compact=False,sort_dicts=True,underscore_numbers=False)[source]
Bases:
PrettyPrinterHandle 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.