robot.libraries package
Package hosting Robot Framework standard test libraries.
Libraries are mainly used externally in the test data, but they can be
also used by custom test libraries if there is a need. Especially
the BuiltIn library is often useful
when there is a need to interact with the framework.
Because libraries are documented using Robot Framework’s own documentation syntax, the generated API docs are not that well formed. It is thus better to find the generated library documentations, for example, via the http://robotframework.org web site.
Submodules
robot.libraries.BuiltIn module
- class robot.libraries.BuiltIn.Expression[source]
Bases:
objectAn expression evaluated in Python.
Expressions are evaluated using Python’s [http://docs.python.org/library/functions.html#eval|eval] function so that all Python built-ins like
len()andint()are available. In addition to that, all unrecognized variables are considered to be modules that are automatically imported. It is possible to use all available Python modules, including the standard modules and the installed third party modules.When a variable is used in the expressing using the normal
${variable}syntax, its value is replaced before the expression is evaluated. This means that the value used in the expression will be the string representation of the variable value, not the variable value itself. This is not a problem with numbers and other objects that have a string representation that can be evaluated directly, but with other objects the behavior depends on the string representation. Most importantly, strings must always be quoted, and if they can contain newlines, they must be triple quoted.Actual variables values are also available in the evaluation namespace. They can be accessed using special variable syntax without the curly braces like
$variable. These variables should never be quoted.
- class robot.libraries.BuiltIn.BuiltIn[source]
Bases:
_Verify,_Converter,_Variables,_RunKeyword,_Control,_MiscAn always available standard library with often needed keywords.
BuiltInis Robot Framework’s standard library that provides a set of generic keywords needed often. It is imported automatically and thus always available. The provided keywords can be used, for example, for verifications (e.g. Should Be Equal, Should Contain), conversions (e.g. Convert To Integer) and for various other purposes (e.g. Log, Sleep, Run Keyword If, Set Global Variable).== Table of contents ==
%TOC%
= Controlling failure messages =
== Overriding default error message ==
Various validation keywords accept
msgandvaluesarguments that can be used to override keyword specific default failure messages.If
msgis given andvaluesgets a true value (default), the failure message is<msg>: <default-message>.If
msgis given andvaluesgets a false value, the message is simply<msg>.
== HTML messages ==
It is possible to use HTML formatting in failure messages by prefixing messages with
*HTML*. Notice that this is not limited to the BuiltIn library, but works with any error message.= String and bytes normalization =
Various validation keywords accept
ignore_case,strip_spacesandcollapse_spacesarguments that make it possible to normalize strings and bytes before comparison. They are allFalseby default, which means that no normalization is done, but they can be individually enabled.If
ignore_caseis given a true value, comparison is case-insensitive.If
strip_spacesis given a valueLEADINGorTRAILING(case-insensitive), leading or trailing spaces, respectively, are removed before comparison. This includes all white space characters such as newlines and tabs.If
strip_spacesis given any other true value, both leading and trailing white space is removed.If
collapse_spacesis given a true value, white space characters are normalized to ASCII spaces and consecutive spaces are collapsed into a single space.
If validated items are collections like lists or dictionaries, string and bytes normalization is done recursively.
Support bytes normalization and recursive normalization with collectins are new in Robot Framework 7.4.
= String representations =
Several keywords log values explicitly (e.g. Log) or implicitly (e.g. Should Be Equal when there are failures). By default, keywords log values using human-readable string representation, which means that strings like
Helloand numbers like42are logged as-is. Most of the time this is the desired behavior, but there are some problems as well:It is not possible to see difference between different objects that have the same string representation like string
42and integer42. Should Be Equal and some other keywords add the type information to the error message in these cases, though.Non-printable characters such as the null byte are not visible.
Trailing whitespace is not visible.
Different newlines (
\r\non Windows,\nelsewhere) cannot be separated from each others.There are several Unicode characters that are different but look the same. One example is the Latin
a(\u0061) and the Cyrillicа(\u0430). Error messages likea != аare not very helpful.Some Unicode characters can be represented using [https://en.wikipedia.org/wiki/Unicode_equivalence|different forms]. For example,
äcan be represented either as a single code point\u00e4or using two combined code points\u0061and\u0308. Such forms are considered canonically equivalent, but strings containing them are not considered equal when compared in Python. Error messages likeä != äare not that helpful either.Containers such as lists and dictionaries are formatted into a single line making it hard to see individual items they contain.
To overcome the above problems, some keywords such as Log and Should Be Equal have an optional
formatterargument that can be used to configure the string representation. The supported values arestr(default),repr, andasciithat work similarly as [https://docs.python.org/library/functions.html|Python built-in functions] with same names. More detailed semantics are explained below.== str ==
Use the human-readable string representation. Equivalent to using
str()in Python. This is the default.== repr ==
Use the machine-readable string representation. Similar to using
repr()in Python, which means that strings likeHelloare logged like'Hello', newlines and non-printable characters are escaped like\nand\x00, and so on. Non-ASCII characters are shown as-is likeä.In this mode bigger lists, dictionaries and other collections are pretty-printed so that there is one item per row.
== ascii ==
Same as using
ascii()in Python. Similar to usingreprexplained above but with the following differences:Non-ASCII characters are escaped like
\xe4instead of showing them as-is likeä. This makes it easier to see differences between Unicode characters that are not equal but look the same.Collections are not pretty-printed.
= Evaluating expressions =
Many keywords, such as Evaluate, Run Keyword If and Should Be True, accept an expression that is evaluated in Python.
== Evaluation namespace ==
Expressions are evaluated using Python’s [http://docs.python.org/library/functions.html#eval|eval] function so that all Python built-ins like
len()andint()are available. In addition to that, all unrecognized variables are considered to be modules that are automatically imported. It is possible to use all available Python modules, including the standard modules and the installed third party modules.Evaluate also allows configuring the execution namespace with a custom namespace and with custom modules to be imported. The latter functionality is useful in special cases where the automatic module import does not work such as when using nested modules like
rootmod.submodor list comprehensions. See the documentation of the Evaluate keyword for mode details.== Variables in expressions ==
When a variable is used in the expressing using the normal
${variable}syntax, its value is replaced before the expression is evaluated. This means that the value used in the expression will be the string representation of the variable value, not the variable value itself. This is not a problem with numbers and other objects that have a string representation that can be evaluated directly, but with other objects the behavior depends on the string representation. Most importantly, strings must always be quoted, and if they can contain newlines, they must be triple quoted.Actual variables values are also available in the evaluation namespace. They can be accessed using special variable syntax without the curly braces like
$variable. These variables should never be quoted.Using the
$variablesyntax slows down expression evaluation a little. This should not typically matter, but should be taken into account if complex expressions are evaluated often and there are strict time constrains.Notice that instead of creating complicated expressions, it is often better to move the logic into a library. That eases maintenance and can also enhance execution speed.
= Using variables with keywords creating or accessing variables =
This library has special keywords Set Global Variable, Set Suite Variable, Set Test Variable and Set Local Variable for creating variables in different scopes. These keywords take the variable name and its value as arguments. The name can be given using the normal
${variable}syntax or in escaped format either like$variableor\${variable}. For example, these are typically equivalent and create new suite level variable${name}with valuevalue:A problem with using the normal
${variable}syntax is that these keywords cannot easily know is the idea to create a variable with exactly that name or does that variable actually contain the name of the variable to create. If the variable does not initially exist, it will always be created. If it exists and its value is a variable name either in the normal or in the escaped syntax, variable with _that_ name is created instead. For example, if${name}variable would exist and contain value$example, these examples would create different variables:Because the behavior when using the normal
${variable}syntax depends on the possible existing value of the variable, it is highly recommended to use the escaped ``$variable`` or ``${variable}`` format instead.This same problem occurs also with special keywords for accessing variables Get Variable Value, Variable Should Exist and Variable Should Not Exist.
NOTE: It is recommended to use the
VARsyntax introduced in Robot Framework 7.0 for creating variables in different scopes instead of the Set Global/Suite/Test/Local Variable keywords. It makes creating variables uniform and avoids all the problems discussed above.= Pattern matching =
Many keywords accept arguments as either glob or regular expression patterns.
== Glob patterns ==
Some keywords, for example Should Match, support so called [http://en.wikipedia.org/wiki/Glob_(programming)|glob patterns] where:
Unlike with glob patterns normally, path separator characters
/and\and the newline character\nare matches by the above wildcards.== Regular expressions ==
Some keywords, for example Should Match Regexp, support [http://en.wikipedia.org/wiki/Regular_expression|regular expressions] that are more powerful but also more complicated that glob patterns. The regular expression support is implemented using Python’s [http://docs.python.org/library/re.html|re module] and its documentation should be consulted for more information about the syntax.
Because the backslash character (
\) is an escape character in Robot Framework test data, possible backslash characters in regular expressions need to be escaped with another backslash like\\d\\w+. Strings that may contain special characters but should be handled as literal strings, can be escaped with the Regexp Escape keyword.= Multiline string comparison =
Should Be Equal and Should Be Equal As Strings report the failures using [http://en.wikipedia.org/wiki/Diff_utility#Unified_format|unified diff format] if both strings have more than two lines.
Results in the following error message:
- ROBOT_LIBRARY_SCOPE = 'GLOBAL'
- ROBOT_LIBRARY_VERSION = '7.4.2'
- ROBOT_AUTO_KEYWORDS = True
- ROBOT_LIBRARY_CONVERTERS = {<class 'robot.api.types.KeywordArgument'>: <function <lambda>>, <class 'robot.api.types.KeywordName'>: <function <lambda>>, <class 'robot.libraries.BuiltIn.Expression'>: <function <lambda>>}
- exception robot.libraries.BuiltIn.RobotNotRunningError[source]
Bases:
AttributeErrorUsed when something cannot be done because Robot is not running.
Based on AttributeError to be backwards compatible with RF < 2.8.5. May later be based directly on Exception, so new code should except this exception explicitly.
- robot.libraries.BuiltIn.register_run_keyword(library, keyword, args_to_process=0, deprecation_warning=True)[source]
Tell Robot Framework that this keyword runs other keywords internally.
NOTE: This API will change in the future. For more information see https://github.com/robotframework/robotframework/issues/2190.
- Parameters:
library – Name of the library the keyword belongs to.
keyword – Name of the keyword itself.
args_to_process – How many arguments to process normally before passing them to the keyword. Other arguments are not touched at all.
deprecation_warning – Set to ``False```to avoid the warning.
Registered keywords are handled specially by Robot so that:
Their arguments are not resolved normally (use
args_to_processto control that). This basically means not replacing variables or handling escapes.They are not stopped by timeouts. Prior to Robot Framework 7.3, timeouts occurring when these keywords were executing other keywords could corrupt output files. That bug has been fixed, so this use case why to register keywords as run keyword variants is not relevant anymore.
If there are conflicts with keyword names, these keywords have lower precedence than other keywords.
Main use cases are:
Library keyword is using BuiltIn.run_keyword internally to execute other keywords. Registering the caller as a “run keyword variant” avoids variables and escapes in arguments being resolved multiple times. All arguments passed to run_keyword can and should be left unresolved.
Keyword has some need to not resolve variables in arguments. This way variable values are not logged anywhere by Robot automatically.
As mentioned above, this API will likely be reimplemented in the future or there could be new API for library keywords to execute other keywords. External libraries can nevertheless use this API if they really need it and are aware of the possible breaking changes in the future.
from robot.libraries.BuiltIn import BuiltIn, register_run_keyword
register_run_keyword(__name__, ‘My Run Keyword’)
from robot.libraries.BuiltIn import BuiltIn, register_run_keyword
- class MyLibrary:
# Process one argument normally to get expression resolved. register_run_keyword(‘MyLibrary’, ‘my_run_keyword_if’, args_to_process=1)
robot.libraries.Collections module
- class robot.libraries.Collections.Collections[source]
Bases:
_List,_DictionaryA library providing keywords for handling lists and dictionaries.
Collectionsis Robot Framework’s standard library that provides a set of keywords for handling Python lists and dictionaries. This library has keywords, for example, for modifying and getting values from lists and dictionaries (e.g. Append To List, Get From Dictionary) and for verifying their contents (e.g. Lists Should Be Equal, Dictionary Should Contain Value).== Table of contents ==
%TOC%
= Related keywords in BuiltIn =
Following keywords in the BuiltIn library can also be used with lists and dictionaries:
= Using with list-like and dictionary-like objects =
List related keywords can in general be used with tuples and other sequences, not only with
listobjects. List keywords that validate something typically even work with sets and mappings (with mappings they look only at keys). If keywords that modify lists are used with immutable sequences such as tuples, values are automatically converted to lists. In such cases the original value obviously is not mutated, but these keywords also return the modified value and that can be used instead.Dictionary related keywords also generally work with any mapping, not only with
dictobjects. If keywords that modify dictionaries are used with immutable mappings, values are automatically converted to dictionaries. Original values cannot be modified in these cases either, but modified values are returned and can be used instead.What values each keyword actually accepts can be seen from argument types and keyword documentation.
Returning values from keywords that modify lists or dictionaries is new in Robot Framework 7.4. With earlier version these keywords could only be used with mutable values.
= Ignore case =
Various keywords support ignoring case in comparisons by using the optional
ignore_caseargument. Case-insensitivity can be enabled by usingignore_case=Trueand it works recursively.With dictionaries, it is also possible to use special values
KEYSandVALUESto normalize only keys or values, respectively. These options themselves are case-insensitive and also singular formsKEYandVALUEare supported.If a dictionary contains keys that normalize to the same value, e.g.
{'a': 1, 'A': 2}, normalizing keys causes an error.Notice that some keywords accept also an older
case_insensitiveargument in addition toignore_case. The latter is new in Robot Framework 7.0 and should be used unless there is a need to support older versions. The old argument is considered deprecated and will eventually be removed.Starting from Robot Framework 7.4, case-insensitivity works also with bytes, not only with strings.
= Data in examples =
List related keywords use variables in format
${Lx}in their examples. They mean lists with as many alphabetic characters as specified byx. For example,${L1}means['a']and${L3}means['a', 'b', 'c'].Dictionary keywords use similar
${Dx}variables. For example,${D1}means{'a': 1}and${D3}means{'a': 1, 'b': 2, 'c': 3}.- ROBOT_LIBRARY_SCOPE = 'GLOBAL'
- ROBOT_LIBRARY_VERSION = '7.4.2'
- should_contain_match(list: Sequence | Mapping | Set, pattern: str, msg: str | None = None, case_insensitive: bool | None = None, whitespace_insensitive: bool | None = None, ignore_case: bool = False, ignore_whitespace: bool = False)[source]
Fails if
patternis not found inlist.By default, pattern matching is similar to matching files in a shell and is case-sensitive and whitespace-sensitive. In the pattern syntax,
*matches to anything and?matches to any single character. You can also prependglob=to your pattern to explicitly use this pattern matching behavior.If you prepend
regexp=to your pattern, your pattern will be used according to the Python [http://docs.python.org/library/re.html|re module] regular expression syntax. Notice that the backslash character often used with regular expressions is an escape character in Robot Framework data and needs to be escaped with another backslash likeregexp=\\d{6}. See BuiltIn.Should Match Regexp for more details.Matching is case-sensitive by default, but that can be changed by giving the
ignore_caseargument a true value. This argument is new in Robot Framework 7.0, but with earlier versions it is possible to usecase_insensitivefor the same purpose.It is possible to ignore all whitespace by giving the
ignore_whitespaceargument a true value. This argument is new in Robot Framework 7.0 as well, and with earlier versions it is possible to usewhitespace_insensitive.Notice that both
case_insensitiveandwhitespace_insensitiveare considered deprecated. They will eventually be removed.Non-string values in lists are ignored when matching patterns.
Use the
msgargument to override the default error message.
- should_not_contain_match(list: Sequence | Mapping | Set, pattern: str, msg: str | None = None, case_insensitive: bool | None = None, whitespace_insensitive: bool | None = None, ignore_case: bool = False, ignore_whitespace: bool = False)[source]
Fails if
patternis found inlist.Exact opposite of Should Contain Match keyword. See that keyword for information about arguments and usage in general.
- get_matches(list: Sequence | Mapping | Set, pattern: str, case_insensitive: bool | None = None, whitespace_insensitive: bool | None = None, ignore_case: bool = False, ignore_whitespace: bool = False) list[str][source]
Returns a list of matches to
patterninlist.For more information on
pattern,case_insensitive/ignore_case, andwhitespace_insensitive/ignore_whitespace, see Should Contain Match.
- get_match_count(list: Sequence | Mapping | Set, pattern: str, case_insensitive: bool | None = None, whitespace_insensitive: bool | None = None, ignore_case: bool = False, ignore_whitespace: bool = False) int[source]
Returns the count of matches to
patterninlist.For more information on
pattern,case_insensitive/ignore_case, andwhitespace_insensitive/ignore_whitespace, see Should Contain Match.
robot.libraries.DateTime module
A library for handling date and time values.
DateTime is a Robot Framework standard library that supports creating and
converting date and time values (e.g. Get Current Date, Convert Time),
as well as doing simple calculations with them (e.g. Subtract Time From Date,
Add Time To Time). It supports dates and times in various formats, and can
also be used by other libraries programmatically.
== Table of contents ==
%TOC%
= Terminology =
In the context of this library, date and time generally have the following
meanings:
date: An entity with both date and time components but without anytime zone information. For example,
2014-06-11 10:07:42.
time: A time interval. For example,1 hour 20 minutesor01:20:00.
This terminology differs from what Python’s standard
[http://docs.python.org/library/datetime.html|datetime] module uses.
Basically its
[http://docs.python.org/library/datetime.html#datetime-objects|datetime] and
[http://docs.python.org/library/datetime.html#timedelta-objects|timedelta]
objects match date and time as defined by this library.
= Date formats =
Dates can be given to and received from keywords in timestamp, custom timestamp, Python datetime and epoch time formats. These formats are discussed thoroughly in subsequent sections.
Input format is determined automatically based on the given date except when
using custom timestamps, in which case it needs to be given using
date_format argument. Default result format is timestamp, but it can
be overridden using result_format argument.
== Timestamp ==
If a date is given as a string, it is always considered to be a timestamp.
If no custom formatting is given using date_format argument, the timestamp
is expected to be in [http://en.wikipedia.org/wiki/ISO_8601|ISO 8601] like
format YYYY-MM-DD hh:mm:ss.mil, where any non-digit character can be used
as a separator or separators can be omitted altogether. Additionally,
only the date part is mandatory, all possibly missing time components are
considered to be zeros.
Dates can also be returned in the same YYYY-MM-DD hh:mm:ss.mil format by
using timestamp value with result_format argument. This is also the
default format that keywords returning dates use. Milliseconds can be excluded
using exclude_millis as explained in Millisecond handling section.
== Custom timestamp ==
It is possible to use custom timestamps in both input and output.
The custom format is same as accepted by Python’s
[http://docs.python.org/library/datetime.html#strftime-strptime-behavior|
datetime.strptime] function. For example, the default timestamp discussed
in the previous section would match %Y-%m-%d %H:%M:%S.%f.
When using a custom timestamp in input, it must be specified using
date_format argument. The actual input value must be a string that matches
the specified format exactly. When using a custom timestamp in output, it must
be given using result_format argument.
== Python datetime ==
Python’s standard
[https://docs.python.org/library/datetime.html#datetime.datetime|datetime]
objects can be used both in input and output. In input, they are recognized
automatically, and in output it is possible to get them by using the datetime
value with the result_format argument.
One nice benefit with datetime objects is that they have different time components available as attributes that can be easily accessed using the extended variable syntax.
== Python date ==
Python’s standard [https://docs.python.org/library/datetime.html#datetime.date|date]
objects are automatically recognized in input starting from Robot Framework 7.0.
They are not supported in output, but datetime objects can be converted
to date objects if needed:
== Epoch time ==
Epoch time is the time in seconds since the
[http://en.wikipedia.org/wiki/Unix_time|UNIX epoch] i.e. 00:00:00.000 (UTC)
January 1, 1970. To give a date as an epoch time, it must be given as a number
(integer or float), not as a string. To return a date as an epoch time,
it is possible to use epoch value with result_format argument.
Epoch times are returned as floating point numbers.
Notice that epoch times are independent on time zones and thus same
around the world at a certain time. For example, epoch times returned
by Get Current Date are not affected by the time_zone argument.
What local time a certain epoch time matches then depends on the time zone.
Following examples demonstrate using epoch times. They are tested in Finland, and due to the reasons explained above they would fail on other time zones.
== Earliest supported date ==
The earliest date that is supported depends on the date format and to some extent on the platform:
Timestamps support year 1900 and above.
Python datetime objects support year 1 and above.
Epoch time supports 1970 and above on Windows.
On other platforms epoch time supports 1900 and above or even earlier.
= Time formats =
Similarly as dates, times can be given to and received from keywords in various different formats. Supported formats are number, time string (verbose and compact), timer string and Python timedelta.
Input format for time is always determined automatically based on the input.
Result format is number by default, but it can be customised using
result_format argument.
== Number ==
Time given as a number is interpreted to be seconds. It can be given either as an integer or a float, or it can be a string that can be converted to a number.
To return a time as a number, result_format argument must have value
number, which is also the default. Returned number is always a float.
== Time string ==
Time strings are strings in format like 1 minute 42 seconds or 1min 42s.
The basic idea of this format is having first a number and then a text
specifying what time that number represents. Numbers can be either
integers or floating point numbers, the whole format is case and space
insensitive, and it is possible to add a minus prefix to specify negative
times. The available time specifiers are:
weeks,week,w(new in RF 7.1)days,day,dhours,hour,hminutes,minute,mins,min,mseconds,second,secs,sec,smilliseconds,millisecond,millis,msmicroseconds,microsecond,us,μs(new in RF 6.0)nanoseconds,nanosecond,ns(new in RF 6.0)
When returning a time string, it is possible to select between verbose
and compact representations using result_format argument. The verbose
format uses long specifiers week, day, hour, minute, second and
millisecond, and adds s at the end when needed. The compact format uses
shorter specifiers w, d, h, min, s and ms, and even drops
the space between the number and the specifier.
== Timer string ==
Timer string is a string given in timer like format hh:mm:ss.mil. In this
format both hour and millisecond parts are optional, leading and trailing
zeros can be left out when they are not meaningful, and negative times can
be represented by adding a minus prefix.
To return a time as timer string, result_format argument must be given
value timer. Timer strings are by default returned in full hh:mm:ss.mil
format, but milliseconds can be excluded using exclude_millis as explained
in Millisecond handling section.
== Python timedelta ==
Python’s standard
[http://docs.python.org/library/datetime.html#datetime.timedelta|timedelta]
objects are also supported both in input and in output. In input they are
recognized automatically, and in output it is possible to receive them by
giving timedelta value to result_format argument.
= Millisecond handling =
This library handles dates and times internally using the precision of the given input. With timestamp, time string, and timer string result formats seconds are, however, rounded to millisecond accuracy. Milliseconds may also be included even if there would be none.
All keywords returning dates or times have an option to leave milliseconds out
by giving a true value to exclude_millis argument. If the argument is given
as a string, it is considered true unless it is empty or case-insensitively
equal to false, none or no. Other argument types are tested using
same [http://docs.python.org/library/stdtypes.html#truth|rules as in
Python].
When milliseconds are excluded, seconds in returned dates and times are rounded to the nearest full second. With timestamp and timer string result formats, milliseconds will also be removed from the returned string altogether.
= Programmatic usage =
In addition to be used as normal library, this library is intended to provide a stable API for other libraries to use if they want to support same date and time formats as this library. All the provided keywords are available as functions that can be easily imported:
Additionally, helper classes Date and Time can be used directly:
- robot.libraries.DateTime.add_time_to_date(date: datetime | date | float | int | str, time: timedelta | float | int | str, result_format: Literal['timestamp', 'datetime', 'epoch'] | str = 'timestamp', exclude_millis: bool = False, date_format: str | None = None) datetime | float | str[source]
Adds time to date and returns the resulting date.
Arguments: -
date:Date to add time to in one of the supporteddate formats.
time:Time that is added in one of the supportedtime formats.
result_format:Format of the returned date.exclude_millis:When set to any true value, rounds and dropsmilliseconds as explained in millisecond handling.
date_format:Possible custom timestamp format ofdate.
- robot.libraries.DateTime.add_time_to_time(time1: timedelta | float | int | str, time2: timedelta | float | int | str, result_format: Literal['number', 'verbose', 'compact', 'timer', 'timedelta'] = 'number', exclude_millis: bool = False) timedelta | float | str[source]
Adds time to another time and returns the resulting time.
Arguments: -
time1:First time in one of the supported time formats. -time2:Second time in one of the supported time formats. -result_format:Format of the returned time. -exclude_millis:When set to any true value, rounds and dropsmilliseconds as explained in millisecond handling.
- robot.libraries.DateTime.convert_date(date: datetime | date | float | int | str, result_format: Literal['timestamp', 'datetime', 'epoch'] | str = 'timestamp', exclude_millis: bool = False, date_format: str | None = None) datetime | float | str[source]
Converts between supported date formats.
Arguments: -
date:Date in one of the supported date formats. -result_format:Format of the returned date. -exclude_millis:When set to any true value, rounds and dropsmilliseconds as explained in millisecond handling.
date_format:Specifies possible custom timestamp format.
- robot.libraries.DateTime.convert_time(time: timedelta | float | int | str, result_format: Literal['number', 'verbose', 'compact', 'timer', 'timedelta'] = 'number', exclude_millis: bool = False) timedelta | float | str[source]
Converts between supported time formats.
Arguments: -
time:Time in one of the supported time formats. -result_format:Format of the returned time. -exclude_millis:When set to any true value, rounds and dropsmilliseconds as explained in millisecond handling.
- robot.libraries.DateTime.get_current_date(time_zone: Literal['local', 'UTC'] = 'local', increment: timedelta | float | int | str = 0, result_format: Literal['timestamp', 'datetime', 'epoch'] | str = 'timestamp', exclude_millis: bool = False) datetime | float | str[source]
Returns current local or UTC time with an optional increment.
Arguments: -
time_zone:Get the current time on this time zone. Currently onlylocal(default) andUTCare supported. Has no effect if date is returned as an epoch time.increment:Optional time increment to add to the returned date inone of the supported time formats. Can be negative.
result_format:Format of the returned date (see date formats).exclude_millis:When set to any true value, rounds and dropsmilliseconds as explained in millisecond handling.
- robot.libraries.DateTime.subtract_date_from_date(date1: datetime | date | float | int | str, date2: datetime | date | float | int | str, result_format: Literal['number', 'verbose', 'compact', 'timer', 'timedelta'] = 'number', exclude_millis: bool = False, date1_format: str | None = None, date2_format: str | None = None) timedelta | float | str[source]
Subtracts date from another date and returns time between.
Arguments: -
date1:Date to subtract another date from in one of thesupported date formats.
date2:Date that is subtracted in one of the supporteddate formats.
result_format:Format of the returned time (see time formats).exclude_millis:When set to any true value, rounds and dropsmilliseconds as explained in millisecond handling.
date1_format:Possible custom timestamp format ofdate1.date2_format:Possible custom timestamp format ofdate2.
Examples:
- robot.libraries.DateTime.subtract_time_from_date(date: datetime | date | float | int | str, time: timedelta | float | int | str, result_format: Literal['timestamp', 'datetime', 'epoch'] | str = 'timestamp', exclude_millis: bool = False, date_format: str | None = None) datetime | float | str[source]
Subtracts time from date and returns the resulting date.
Arguments: -
date:Date to subtract time from in one of the supporteddate formats.
time:Time that is subtracted in one of the supportedtime formats.
result_format:Format of the returned date.exclude_millis:When set to any true value, rounds and dropsmilliseconds as explained in millisecond handling.
date_format:Possible custom timestamp format ofdate.
- robot.libraries.DateTime.subtract_time_from_time(time1: timedelta | float | int | str, time2: timedelta | float | int | str, result_format: Literal['number', 'verbose', 'compact', 'timer', 'timedelta'] = 'number', exclude_millis: bool = False) timedelta | float | str[source]
Subtracts time from another time and returns the resulting time.
Arguments: -
time1:Time to subtract another time from in one ofthe supported time formats.
time2:Time to subtract in one of the supported time formats.result_format:Format of the returned time.exclude_millis:When set to any true value, rounds and dropsmilliseconds as explained in millisecond handling.
robot.libraries.Dialogs module
A library providing dialogs for interacting with users.
Dialogs is Robot Framework’s standard library that provides means
for pausing the test or task execution and getting input from users.
Long lines in the provided messages are wrapped automatically. If you want
to wrap lines manually, you can add newlines using the \n character
sequence.
- robot.libraries.Dialogs.execute_manual_step(message: str, default_error: str = '')[source]
Pauses execution until user sets the keyword status.
User can press either
PASSorFAILbutton. In the latter case execution fails and an additional dialog is opened for defining the error message.messageis the instruction shown in the initial dialog anddefault_erroris the default value shown in the possible error message dialog.
- robot.libraries.Dialogs.get_selection_from_user(message: str, *values: str, default: str | int | None = None) str[source]
Pauses execution and asks user to select a value.
The selected value is returned. Pressing
Cancelfails the keyword.messageis the instruction shown in the dialog,valuesare the options given to the user anddefaultis the optional default value.The default value can either be one of the specified values or the index of the value starting from
1. For example,default=user1anddefault=1in the examples below have the exact same effect.defaultis new in Robot Framework 7.1.
- robot.libraries.Dialogs.get_selections_from_user(message: str, *values: str) list[str][source]
Pauses execution and asks user to select multiple values.
The selected values are returned as a list. Selecting no values is OK and in that case the returned list is empty. Pressing
Cancelfails the keyword.messageis the instruction shown in the dialog andvaluesare the options given to the user.
- robot.libraries.Dialogs.get_value_from_user(message: str, default_value: str = '', hidden: bool = False) str[source]
Pauses execution and asks user to input a value.
Value typed by the user, or the possible default value, is returned. Returning an empty value is fine, but pressing
Cancelfails the keyword.messageis the instruction shown in the dialog anddefault_valueis the possible default value shown in the input field.If
hiddenis given a true value, the value typed by the user is hidden.hiddenis considered true if it is a non-empty string not equal tofalse,noneorno, case-insensitively. If it is not a string, its truth value is got directly using same [http://docs.python.org/library/stdtypes.html#truth|rules as in Python].
robot.libraries.Easter module
robot.libraries.OperatingSystem module
- class robot.libraries.OperatingSystem.OperatingSystem[source]
Bases:
objectA library providing keywords for operating system related tasks.
OperatingSystemis Robot Framework’s standard library that enables various operating system related tasks to be performed in the system where Robot Framework is running. It can, among other things, execute commands (e.g. Run), create and remove files and directories (e.g. Create File, Remove Directory), check whether files or directories exists or contain something (e.g. File Should Exist, Directory Should Be Empty) and manipulate environment variables (e.g. Set Environment Variable).== Table of contents ==
%TOC%
= Path separators =
Because Robot Framework uses the backslash (
\) as an escape character in its data, using a literal backslash requires duplicating it like inc:\\path\\file.txt. That can be inconvenient especially with longer Windows paths, and thus all keywords expecting paths as arguments convert forward slashes to backslashes automatically on Windows. This also means that paths like${CURDIR}/path/file.txtare operating system independent.Notice that the automatic path separator conversion does not work if the path is only a part of an argument like with the Run keyword. In these cases the built-in variable
${/}that contains\or/, depending on the operating system, can be used instead.= Pattern matching =
Many keywords accept arguments as either _glob_ or _regular expression_ patterns.
== Glob patterns ==
Some keywords, for example List Directory, support so called [http://en.wikipedia.org/wiki/Glob_(programming)|glob patterns] where:
Unless otherwise noted, matching is case-insensitive on case-insensitive operating systems such as Windows.
== Regular expressions ==
Some keywords, for example Grep File, support [http://en.wikipedia.org/wiki/Regular_expression|regular expressions] that are more powerful but also more complicated that glob patterns. The regular expression support is implemented using Python’s [http://docs.python.org/library/re.html|re module] and its documentation should be consulted for more information about the syntax.
Because the backslash character (
\) is an escape character in Robot Framework data, possible backslash characters in regular expressions need to be escaped with another backslash like\\d\\w+. Strings that may contain special characters but should be handled as literal strings, can be escaped with the Regexp Escape keyword from the BuiltIn library.= Tilde expansion =
Paths beginning with
~or~usernameare expanded to the current or specified user’s home directory, respectively. The resulting path is operating system dependent, but typically e.g.~/robotis expanded toC:\Users\<user>\roboton Windows and/home/<user>/roboton Unixes.= pathlib.Path support =
Starting from Robot Framework 6.0, arguments representing paths can be given as [https://docs.python.org/3/library/pathlib.html|pathlib.Path] instances in addition to strings.
For backwards compatibility reasons, all keywords returning paths return them as strings.
= Example =
- ROBOT_LIBRARY_SCOPE = 'GLOBAL'
- ROBOT_LIBRARY_VERSION = '7.4.2'
- run(command: str) str[source]
_This keyword is considered deprecated. Use the [http://robotframework.org/robotframework/latest/libraries/Process.html| Process] library instead._
Runs the given command in the system and returns the output.
The execution status of the command _is not checked_ by this keyword, and it must be done separately based on the returned output. If the execution return code is needed, either Run And Return RC or Run And Return RC And Output can be used.
The standard error stream is automatically redirected to the standard output stream by adding
2>&1after the executed command. This automatic redirection is done only when the executed command does not contain additional output redirections. You can thus freely forward the standard error somewhere else, for example, likemy_command 2>stderr.txt.The returned output contains everything written into the standard output or error streams by the command (unless either of them is redirected explicitly). Many commands add an extra newline (
\n) after the output to make it easier to read in the console. To ease processing the returned output, this possible trailing newline is stripped by this keyword.
- run_and_return_rc(command: str) int[source]
_This keyword is considered deprecated. Use the [http://robotframework.org/robotframework/latest/libraries/Process.html| Process] library instead._
Runs the given command in the system and returns the return code (RC).
The return code is returned as a positive integer in range from 0 to 255 as returned by the executed command. On some operating systems (notable Windows) original return codes can be something else, but this keyword always maps them to the 0-255 range. Since the return code is an integer, it must be checked e.g. with the keyword Should Be Equal As Integers instead of Should Be Equal (both are built-in keywords).
See Run and Run And Return RC And Output if you need to get the output of the executed command.
- run_and_return_rc_and_output(command: str) tuple[int, str][source]
_This keyword is considered deprecated. Use the [http://robotframework.org/robotframework/latest/libraries/Process.html| Process] library instead._
Runs the given command in the system and returns the return code (RC) and output. The return code is returned similarly as with Run And Return RC and the output similarly as with Run.
- get_file(path: str, encoding: str = 'UTF-8', encoding_errors: str = 'strict') str[source]
Returns the contents of a specified file.
This keyword reads the specified file and returns the contents. Line breaks in content are converted to platform independent form. See also Get Binary File.
encodingdefines the encoding of the file. The default value isUTF-8, which means that UTF-8 and ASCII encoded files are read correctly. In addition to the encodings supported by the underlying Python implementation, the following special encoding values can be used:SYSTEM: Use the default system encoding.CONSOLE: Use the console encoding. Outside Windows this is same as the system encoding.
encoding_errorsargument controls what to do if decoding some bytes fails. All values accepted bydecodemethod in Python are valid, but in practice the following values are most useful:strict: Fail if characters cannot be decoded (default).ignore: Ignore characters that cannot be decoded.replace: Replace characters that cannot be decoded with a replacement character.
- get_binary_file(path: str) bytes[source]
Returns the contents of a specified file.
This keyword reads the specified file and returns the contents as is. See also Get File.
- grep_file(path: str, pattern: str, encoding: str = 'UTF-8', encoding_errors: str = 'strict', regexp: bool = False) str[source]
Returns the lines of the specified file that match the
pattern.This keyword reads a file from the file system using the defined
path,encodingandencoding_errorssimilarly as Get File. A difference is that only the lines that match the givenpatternare returned. Lines are returned as a single string concatenated back together with newlines and the number of matched lines is automatically logged. Possible trailing newline is never returned.A line matches if it contains the
patternanywhere in it i.e. it does not need to match the pattern fully. There are two supported pattern types:By default the pattern is considered a _glob_ pattern where, for example,
*and?can be used as wildcards.If the
regexpargument is given a true value, the pattern is considered to be a _regular expression_. These patterns are more powerful but also more complicated than glob patterns. They often use the backslash character and it needs to be escaped in Robot Framework date like \.
For more information about glob and regular expression syntax, see the Pattern matching section. With this keyword matching is always case-sensitive.
Special encoding values
SYSTEMandCONSOLEthat Get File supports are supported by this keyword only with Robot Framework 4.0 and newer.Support for regular expressions is new in Robot Framework 5.0.
- log_file(path: str, encoding: str = 'UTF-8', encoding_errors: str = 'strict') str[source]
Wrapper for Get File that also logs the returned file.
The file is logged with the INFO level. If you want something else, just use Get File and the built-in keyword Log with the desired level.
See Get File for more information about
encodingandencoding_errorsarguments.
- should_exist(path: str, msg: str | None = None)[source]
Fails unless the given path (file or directory) exists.
The path can be given as an exact path or as a glob pattern. See the Glob patterns section for details about the supported syntax.
The default error message can be overridden with the
msgargument.
- should_not_exist(path: str, msg: str | None = None)[source]
Fails if the given path (file or directory) exists.
The path can be given as an exact path or as a glob pattern. See the Glob patterns section for details about the supported syntax.
The default error message can be overridden with the
msgargument.
- file_should_exist(path: str, msg: str | None = None)[source]
Fails unless the given
pathpoints to an existing file.The path can be given as an exact path or as a glob pattern. See the Glob patterns section for details about the supported syntax.
The default error message can be overridden with the
msgargument.
- file_should_not_exist(path: str, msg: str | None = None)[source]
Fails if the given path points to an existing file.
The path can be given as an exact path or as a glob pattern. See the Glob patterns section for details about the supported syntax.
The default error message can be overridden with the
msgargument.
- directory_should_exist(path: str, msg: str | None = None)[source]
Fails unless the given path points to an existing directory.
The path can be given as an exact path or as a glob pattern. See the Glob patterns section for details about the supported syntax.
The default error message can be overridden with the
msgargument.
- directory_should_not_exist(path: str, msg: str | None = None)[source]
Fails if the given path points to an existing file.
The path can be given as an exact path or as a glob pattern. See the Glob patterns section for details about the supported syntax.
The default error message can be overridden with the
msgargument.
- wait_until_removed(path: str, timeout: timedelta | None = datetime.timedelta(seconds=60))[source]
Waits until the given file or directory is removed.
The path can be given as an exact path or as a glob pattern. See the Glob patterns section for details about the supported syntax. If the path is a pattern, the keyword waits until all matching items are removed.
Waits for 1 minute by default, but that can be changed by using the
timeoutargument. Using a negative value orNonedisables the timeout.Disabling timeout using
Noneis new in Robot Framework 7.4.
- wait_until_created(path: str, timeout: timedelta | None = datetime.timedelta(seconds=60))[source]
Waits until the given file or directory is created.
The path can be given as an exact path or as a glob pattern. See the Glob patterns section for details about the supported syntax. If the path is a pattern, the keyword returns when an item matching it is created.
Waits for 1 minute by default, but that can be changed by using the
timeoutargument. Using a negative value orNonedisables the timeout.Disabling timeout using
Noneis new in Robot Framework 7.4.
- directory_should_be_empty(path: str, msg: str | None = None)[source]
Fails unless the specified directory is empty.
The default error message can be overridden with the
msgargument.
- directory_should_not_be_empty(path: str, msg: str | None = None)[source]
Fails if the specified directory is empty.
The default error message can be overridden with the
msgargument.
- file_should_be_empty(path: str, msg: str | None = None)[source]
Fails unless the specified file is empty.
The default error message can be overridden with the
msgargument.
- file_should_not_be_empty(path: str, msg: str | None = None)[source]
Fails if the specified file is empty.
The default error message can be overridden with the
msgargument.
- create_file(path: str, content: str | Secret = '', encoding: str = 'UTF-8')[source]
Creates a file with the given content and encoding.
If the directory where the file is created does not exist, it is automatically created along with possible missing intermediate directories. Possible existing file is overwritten.
On Windows newline characters (
\n) in content are automatically converted to Windows native newline sequence (\r\n).See Get File for more information about possible
encodingvalues, including special valuesSYSTEMandCONSOLE.Use Append To File if you want to append to an existing file and Create Binary File if you need to write bytes without encoding. File Should Not Exist can be used to avoid overwriting existing files.
- create_binary_file(path: str, content: bytes)[source]
Creates a binary file with the given content.
If content is given as a Unicode string, it is first converted to bytes character by character. All characters with ordinal below 256 can be used and are converted to bytes with same values. Using characters with higher ordinal is an error.
Byte strings, and possible other types, are written to the file as is.
If the directory for the file does not exist, it is created, along with missing intermediate directories.
Use Create File if you want to create a text file using a certain encoding. File Should Not Exist can be used to avoid overwriting existing files.
- append_to_file(path: str, content: str | Secret = '', encoding: str = 'UTF-8')[source]
Appends the given content to the specified file.
If the file exists, the given text is written to its end. If the file does not exist, it is created.
Other than not overwriting possible existing files, this keyword works exactly like Create File. See its documentation for more details about the usage.
- remove_file(path: str)[source]
Removes a file with the given path.
Passes if the file does not exist, but fails if the path does not point to a regular file (e.g. it points to a directory).
The path can be given as an exact path or as a glob pattern. See the Glob patterns section for details about the supported syntax. If the path is a pattern, all files matching it are removed.
- empty_directory(path: str)[source]
Deletes all the content from the given directory.
Deletes both files and subdirectories, but the specified directory itself if not removed. Use Remove Directory if you want to remove the whole directory.
- create_directory(path: str)[source]
Creates the specified directory.
Possible intermediate directories are created as well. Passes if the directory already exists, but fails if the path exists and is not a directory.
- remove_directory(path: str, recursive: bool = False)[source]
Removes the directory pointed to by the given
path.If the second argument
recursiveis given a true value, the directory is removed recursively. Otherwise, removing fails if the directory is not empty.If the directory pointed to by the
pathdoes not exist, the keyword passes, but it fails, if thepathpoints to a file.
- copy_file(source: str, destination: str) str[source]
Copies the source file into the destination.
Source must be a path to an existing file or a glob pattern (see Glob patterns) that matches exactly one file. How the destination is interpreted is explained below.
1) If the destination is an existing file, the source file is copied over it.
2) If the destination is an existing directory, the source file is copied into it. A possible file with the same name as the source is overwritten.
3) If the destination does not exist, and it ends with a path separator (
/or\), it is considered a directory. That directory is created and a source file copied into it. Possible missing intermediate directories are also created.4) If the destination does not exist, and it does not end with a path separator, it is considered a file. If the path to the file does not exist, it is created.
The resulting destination path is returned.
See also Copy Files, Move File, and Move Files.
- move_file(source: str, destination: str) str[source]
Moves the source file into the destination.
Arguments have exactly same semantics as with Copy File keyword. Destination file path is returned.
If the source and destination are on the same filesystem, rename operation is used. Otherwise, file is copied to the destination filesystem and then removed from the original filesystem.
See also Move Files, Copy File, and Copy Files.
- copy_files(*sources_and_destination: str)[source]
Copies specified files to the target directory.
Source files can be given as exact paths and as glob patterns (see Glob patterns). At least one source must be given, but it is not an error if it is a pattern that does not match anything.
Last argument must be the destination directory. If the destination does not exist, it will be created.
See also Copy File, Move File, and Move Files.
- move_files(*sources_and_destination: str)[source]
Moves specified files to the target directory.
Arguments have exactly same semantics as with Copy Files keyword.
See also Move File, Copy File, and Copy Files.
- copy_directory(source, destination)[source]
Copies the source directory into the destination.
If the destination exists, the source is copied under it. Otherwise, the destination directory and the possible missing intermediate directories are created.
- move_directory(source: str, destination: str)[source]
Moves the source directory into a destination.
Uses Copy Directory keyword internally, and
sourceanddestinationarguments have exactly same semantics as with that keyword.
- get_environment_variable(name: str, default: str | None = None) str[source]
Returns the value of an environment variable with the given name.
If no environment variable is found, returns possible default value. If no default value is given, the keyword fails.
Returned variables are automatically decoded to Unicode using the system encoding.
Note that you can also access environment variables directly using the variable syntax
%{ENV_VAR_NAME}.
- set_environment_variable(name: str, value: str | Secret)[source]
Sets an environment variable to a specified value.
Values are converted to strings automatically. Set variables are automatically encoded using the system encoding.
- append_to_environment_variable(name: str, *values: str | Secret, separator: str = ':')[source]
Appends given
valuesto environment variablename.If the environment variable already exists, values are added after it, and otherwise a new environment variable is created.
Values are, by default, joined together using the operating system path separator (
;on Windows,:elsewhere). This can be changed by giving a separator after the values likeseparator=value.
- remove_environment_variable(*names: str)[source]
Deletes the specified environment variable.
Does nothing if the environment variable is not set.
It is possible to remove multiple variables by passing them to this keyword as separate arguments.
- environment_variable_should_be_set(name: str, msg: str | None = None)[source]
Fails if the specified environment variable is not set.
Environment variable is considered not to be set if it does not exist or if its value is an empty string.
The default error message can be overridden with the
msgargument.
- environment_variable_should_not_be_set(name: str, msg: str | None = None)[source]
Fails if the specified environment variable is set.
Environment variable is considered not to be set if it does not exist or if its value is an empty string.
The default error message can be overridden with the
msgargument.
- get_environment_variables() dict[str, str][source]
Returns currently available environment variables as a dictionary.
Both keys and values are decoded to Unicode using the system encoding. Altering the returned dictionary has no effect on the actual environment variables.
- log_environment_variables(level: Literal['TRACE', 'DEBUG', 'INFO', 'CONSOLE', 'HTML', 'WARN', 'ERROR'] = 'INFO') dict[str, str][source]
Logs all environment variables using the given log level.
Environment variables are also returned the same way as with Get Environment Variables keyword.
- join_path(base: str, *parts: str) str[source]
Joins the given path part(s) to the given base path.
The path separator (
/or\) is inserted when needed and the possible absolute paths handled as expected. The resulted path is also normalized.${path} = ‘my/path’
${p2} = ‘my/path’
${p3} = ‘my/path/my/file.txt’
${p4} = ‘/path’
${p5} = ‘/my/path2’
- join_paths(base: str, *paths: str) list[str][source]
Joins given paths with base and returns resulted paths.
See Join Path for more information.
@{p1} = [‘base/example’, ‘base/other’]
@{p2} = [‘/example’, ‘/my/base/other’]
@{p3} = [‘my/base/example/path’, ‘my/base/other’, ‘my/base/one/more’]
- normalize_path(path: str, case_normalize=False) str[source]
Normalizes the given path.
Collapses redundant separators and up-level references.
Converts
/to\on Windows.Replaces initial
~or~userby that user’s home directory.If
case_normalizeis given a true value on Windows, converts the path to all lowercase.Converts
pathlib.Pathinstances tostr.${path1} = ‘abc’
${path2} = ‘def’
${path3} = ‘abc/def/ghi’
${path4} = ‘/home/robot/stuff’
On Windows result would use
\instead of/and home directory would be different.
- split_path(path: str) tuple[str, str][source]
Splits the given path from the last path separator (
/or\).The given path is first normalized (e.g. a possible trailing path separator is removed, special directories
..and.removed). The parts that are split are returned as separate components.${path1} = ‘abc’ & ${dir} = ‘def’
${path2} = ‘abc/def’ & ${file} = ‘ghi.txt’
${path3} = ‘def’ & ${d2} = ‘ghi’
- split_extension(path: str) tuple[str, str][source]
Splits the extension from the given path.
The given path is first normalized (e.g. possible trailing path separators removed, special directories
..and.removed). The base path and extension are returned as separate components so that the dot used as an extension separator is removed. If the path contains no extension, an empty string is returned for it. Possible leading and trailing dots in the file name are never considered to be extension separators.${path} = ‘file’ & ${ext} = ‘extension’
${p2} = ‘path/file’ & ${e2} = ‘ext’
${p3} = ‘path/file’ & ${e3} = ‘’
${p4} = ‘p2/file’ & ${e4} = ‘ext’
${p5} = ‘path/.file’ & ${e5} = ‘ext’
${p6} = ‘path/.file’ & ${e6} = ‘’
- get_modified_time(path: str, format: str = 'timestamp') int | str | list[str][source]
Returns the last modification time of a file or directory.
How time is returned is determined based on the given
formatstring as follows. Note that all checks are case-insensitive. Returned time is also automatically logged.If
formatcontains the wordepoch, the time is returned in seconds after the UNIX epoch. The return value is always an integer.If
formatcontains any of the wordsyear,month,day,hour,minorsec, only the selected parts are returned. The order of the returned parts is always the one in the previous sentence and the order of the words informatis not significant. The parts are returned as zero-padded strings (e.g. May ->05).Otherwise, and by default, the time is returned as a timestamp string in the format
2006-02-24 15:08:31.
2006-03-29 15:06:21): - ${time} = ‘2006-03-29 15:06:21’ - ${secs} = 1143637581 - ${year} = ‘2006’ - ${y} = ‘2006’ & ${d} = ‘29’ - @{time} = [‘2006’, ‘03’, ‘29’, ‘15’, ‘06’, ‘21’]
- set_modified_time(path: str, mtime: int | str)[source]
Sets the file modification and access times.
Changes the modification and access times of the given file to the value determined by
mtime. The time can be given in different formats described below. Note that all checks involving strings are case-insensitive. Modified time can only be set to regular files.If
mtimeis a number, or a string that can be converted to a number, it is interpreted as seconds since the UNIX epoch (1970-01-01 00:00:00 UTC). This documentation was originally written about 1177654467 seconds after the epoch.If
mtimeis a timestamp, that time will be used. Valid timestamp formats areYYYY-MM-DD hh:mm:ssandYYYYMMDD hhmmss.If
mtimeis equal toNOW, the current local time is used.If
mtimeis equal toUTC, the current time in [http://en.wikipedia.org/wiki/Coordinated_Universal_Time|UTC] is used.If
mtimeis in the format likeNOW - 1 dayorUTC + 1 hour 30 min, the current local/UTC time plus/minus the time specified with the time string is used. The time string format is described in an appendix of Robot Framework User Guide.
- list_directory(path: str, pattern: str | None = None, absolute: bool = False) list[str][source]
Returns and logs items in a directory, optionally filtered with
pattern.File and directory names are returned in case-sensitive alphabetical order, e.g.
['A Name', 'Second', 'a lower case name', 'one more']. Implicit directories.and..are not returned. The returned items are automatically logged.File and directory names are returned relative to the given path (e.g.
'file.txt') by default. If you want them be returned in absolute format (e.g.'/home/robot/file.txt'), give theabsoluteargument a true value.If
patternis given, only items matching it are returned. The pattern is considered to be a _glob pattern_ and the full syntax is explained in the Glob patterns section. With this keyword matching is always case-sensitive.
- list_files_in_directory(path: str, pattern: str | None = None, absolute: bool = False) list[str][source]
Wrapper for List Directory that returns only files.
- list_directories_in_directory(path: str, pattern: str | None = None, absolute: bool = False) list[str][source]
Wrapper for List Directory that returns only directories.
- count_items_in_directory(path: str, pattern: str | None = None) int[source]
Returns and logs the number of all items in the given directory.
The argument
patternhas the same semantics as with List Directory keyword. The count is returned as an integer, so it must be checked e.g. with the built-in keyword Should Be Equal As Integers.
- count_files_in_directory(path: str, pattern: str | None = None) int[source]
Wrapper for Count Items In Directory returning only file count.
robot.libraries.Process module
- class robot.libraries.Process.ProcessResult(process, stdout, stderr, stdin=None, rc=None, output_encoding=None)[source]
Bases:
objectAn object containing process execution results in its attributes.
Notice that in
stdoutandstderrcontent possible trailing newline is removed and\r\nconverted to\nautomatically. If you need to see the original process output, redirect it to a file using process configuration and read it from there.- property stdout
- property stderr
- class robot.libraries.Process.ProcessConfiguration(cwd=None, shell=False, stdout=None, stderr=None, stdin=None, output_encoding='CONSOLE', alias=None, env=None, **env_extra)[source]
Bases:
object- property popen_config
- property result_config
- class robot.libraries.Process.Process[source]
Bases:
objectRobot Framework library for running processes.
The library has following main usages:
Running processes in system and waiting for their completion using the Run Process keyword.
Starting processes on background using the Start Process keyword.
Waiting started process to complete using Wait For Process or stopping them with Terminate Process or Terminate All Processes.
This library provides various benefits over using
Runand other similar keywords in the [http://robotframework.org/robotframework/latest/libraries/OperatingSystem.html| OperatingSystem] library:Better process configuration.
Convenient result object with all result information (rc, stdout, stderr).
Support for background processes, process termination, sending signals and so on.
This library utilizes Python’s [http://docs.python.org/library/subprocess.html|subprocess] module and its [http://docs.python.org/library/subprocess.html#popen-constructor|Popen] class.
== Table of contents ==
%TOC%
= Specifying command and arguments =
Both Run Process and Start Process accept the command to execute and all arguments passed to the command as separate arguments. This makes usage convenient and also allows these keywords to automatically escape possible spaces and other special characters in commands and arguments. Notice that if a command accepts options that themselves accept values, these options and their values must be given as separate arguments.
When running processes in shell, it is also possible to give the whole command to execute as a single string. The command can then contain multiple commands to be run together. When using this approach, the caller is responsible on escaping.
Possible non-string arguments are converted to strings automatically.
= Process configuration =
Run Process and Start Process keywords can be configured using optional configuration arguments. These arguments must be given after other arguments passed to these keywords and must use the
name=valuesyntax. Available configuration arguments are listed below and discussed further in the subsequent sections.Note that possible equal signs in other arguments passed to Run Process and Start Process must be escaped with a backslash like
name\=value. See Run Process for an example.== Running processes in shell ==
The
shellargument specifies whether to run the process in a shell or not. By default, shell is not used, which means that shell specific commands, likecopyanddiron Windows, are not available. You can, however, run shell scripts and batch files without using a shell.Giving the
shellargument any non-false value, such asshell=True, changes the program to be executed in a shell. It allows using the shell capabilities, but can also make the process invocation operating system dependent. Having a shell between the actually started process and this library can also interfere communication with the process such as stopping it and reading its outputs. Because of these problems, it is recommended to use the shell only when absolutely necessary.When using a shell it is possible to give the whole command to execute as a single string. See Specifying command and arguments section for examples and more details in general.
== Current working directory ==
By default, the child process will be executed in the same directory as the parent process, the process running Robot Framework, is executed. This can be changed by giving an alternative location using the
cwdargument. Forward slashes in the given path are automatically converted to backslashes on Windows.Standard output and error streams, when redirected to files, are also relative to the current working directory possibly set using the
cwdargument.== Environment variables ==
The child process will get a copy of the parent process’s environment variables by default. The
envargument can be used to give the child a custom environment as a Python dictionary. If there is a need to specify only certain environment variable, it is possible to use theenv:<name>=<value>format to set or override only that named variables. It is also possible to use these two approaches together.== Standard output and error streams ==
By default, processes are run so that their standard output and standard error streams are kept in the memory. This typically works fine, but there can be problems if the amount of output is large or unlimited. Prior to Robot Framework 7.3 the limit was smaller than nowadays and reaching it caused a deadlock.
To avoid the above-mentioned problems, it is possible to use
stdoutandstderrarguments to specify files on the file system where to redirect the output. This can also be useful if other processes or other keywords need to read or manipulate the output somehow.Given
stdoutandstderrpaths are relative to the current working directory. Forward slashes in the given paths are automatically converted to backslashes on Windows.Regardless are outputs redirected to files or not, they are accessible through the result object returned when the process ends. Commands are expected to write outputs using the console encoding, but output encoding can be configured using the
output_encodingargument if needed.As a special feature, it is possible to redirect the standard error to the standard output by using
stderr=STDOUT.If you are not interested in output at all, you can explicitly ignore it by using a special value
DEVNULLboth withstdoutandstderr. For example,stdout=DEVNULLis the same as redirecting output on console with> /dev/nullon UNIX-like operating systems or> NULon Windows. This way even a huge amount of output cannot cause problems, but naturally the output is not available after execution either.Note that the created output files are not automatically removed after execution. The user is responsible to remove them if needed.
== Standard input stream ==
The
stdinargument makes it possible to pass information to the standard input stream of the started process. How its value is interpreted is explained in the table below.Values
PIPEandNONEare case-insensitive and internally mapped tosubprocess.PIPEandNone, respectively, when calling [https://docs.python.org/3/library/subprocess.html#subprocess.Popen|subprocess.Popen].The support to configure
stdinis new in Robot Framework 4.1.2. Its default value used to bePIPEuntil Robot Framework 7.0.== Output encoding ==
Executed commands are, by default, expected to write outputs to the standard output and error streams using the encoding used by the system console. If the command uses some other encoding, that can be configured using the
output_encodingargument. This is especially useful on Windows where the console uses a different encoding than rest of the system, and many commands use the general system encoding instead of the console encoding.The value used with the
output_encodingargument must be a valid encoding and must match the encoding actually used by the command. As a convenience, it is possible to use stringsCONSOLEandSYSTEMto specify that the console or system encoding is used, respectively. If produced outputs use different encoding then configured, values got through the result object will be invalid.== Alias ==
A custom name given to the process that can be used when selecting the active process.
= Active process =
The library keeps record which of the started processes is currently active. By default, it is the latest process started with Start Process, but Switch Process can be used to activate a different process. Using Run Process does not affect the active process.
The keywords that operate on started processes will use the active process by default, but it is possible to explicitly select a different process using the
handleargument. The handle can be analiasexplicitly given to Start Process or the process object returned by it.= Result object =
Run Process, Wait For Process and Terminate Process keywords return a result object that contains information about the process execution as its attributes. The same result object, or some of its attributes, can also be get using Get Process Result keyword. Attributes available in the object are documented in the table below.
Notice that in
stdoutandstderrcontent possible trailing newline is removed and\r\nconverted to\nautomatically. If you need to see the original process output, redirect it to a file using process configuration and read it from there.= Example =
- ROBOT_LIBRARY_SCOPE = 'GLOBAL'
- ROBOT_LIBRARY_VERSION = '7.4.2'
- TERMINATE_TIMEOUT = 30
- KILL_TIMEOUT = 10
- run_process(command: str, *arguments: str | Secret, cwd: str | None = None, shell: bool = False, stdout: str | None = None, stderr: str | None = None, stdin: str | Secret | Path | int | IOBase | None = None, output_encoding: str = 'CONSOLE', alias: str | None = None, timeout: timedelta | None = None, on_timeout: Literal['continue', 'terminate', 'kill'] = 'terminate', env: dict[str, str | Secret] | None = None, **env_extra: str | Secret) ProcessResult[source]
Runs a process and waits for it to complete.
commandandargumentsspecify the command to execute and arguments passed to it. See Specifying command and arguments for more details.The started process can be configured using
cwd,shell,stdout,stderr,stdin,output_encoding,alias,envandenv_extraparameters that are documented in the Process configuration section.Configuration related to waiting for processes consists of
timeoutandon_timeoutparameters that have same semantics than with the Wait For Process keyword.Process outputs are, by default, written into in-memory buffers. This typically works fine, but there can be problems if the amount of output is large or unlimited. To avoid such problems, outputs can be redirected to files using the
stdoutandstderrconfiguration parameters. For more information see the Standard output and error streams section.Returns a result object containing information about the execution.
Note that possible equal signs in
commandandargumentsmust be escaped with a backslash (e.g.name\=value).This keyword does not change the active process.
- start_process(command: str, *arguments: str | Secret, cwd: str | None = None, shell: bool = False, stdout: str | None = None, stderr: str | None = None, stdin: str | Secret | Path | int | IOBase | None = None, output_encoding: str = 'CONSOLE', alias: str | None = None, env: dict[str, str | Secret] | None = None, **env_extra: str | Secret) Popen[source]
Starts a new process on background.
See Specifying command and arguments and Process configuration sections for more information about the arguments, and Run Process keyword for related examples. This includes information about redirecting process outputs to avoid process handing due to output buffers getting full.
Makes the started process new active process. Returns the created [https://docs.python.org/3/library/subprocess.html#popen-objects | subprocess.Popen] object which can be used later to activate this process.
Popenattributes likepidcan also be accessed directly.Processes are started so that they create a new process group. This allows terminating and sending signals to possible child processes.
Start process and wait for it to end later using an alias:
Use returned
Popenobject:Use started process in a pipeline with another process:
Returning a
subprocess.Popenobject is new in Robot Framework 5.0. Earlier versions returned a generic handle and getting the process object required using Get Process Object separately.
- is_process_running(handle: Popen | str | None = None) bool[source]
Checks is the process running or not.
If
handleis not given, uses the current active process.Returns
Trueif the process is still running andFalseotherwise.
- process_should_be_running(handle: Popen | str | None = None, error_message: str = 'Process is not running.')[source]
Verifies that the process is running.
If
handleis not given, uses the current active process.Fails if the process has stopped.
- process_should_be_stopped(handle: Popen | str | None = None, error_message: str = 'Process is running.')[source]
Verifies that the process is not running.
If
handleis not given, uses the current active process.Fails if the process is still running.
- wait_for_process(handle: Popen | str | None = None, timeout: timedelta | None = None, on_timeout: Literal['continue', 'terminate', 'kill'] = 'continue') ProcessResult | None[source]
Waits for the process to complete or to reach the given timeout.
The process to wait for must have been started earlier with Start Process. If
handleis not given, uses the current active process.timeoutdefines the maximum time to wait for the process. It can be given in [http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#time-format| various time formats] supported by Robot Framework, for example,42,42 s, or1 minute 30 seconds. The timeout is ignored if it isNone(default), zero or negative.on_timeoutdefines what to do if the timeout occurs. Possible values and corresponding actions are explained in the table below. Notice that reaching the timeout never fails the test.See Terminate Process keyword for more details how processes are terminated and killed.
If the process ends before the timeout, or it is terminated or killed, this keyword returns a result object containing information about the execution. If the process is left running, Python
Noneis returned instead.Note: If Robot Framework’s test or keyword timeout is exceeded while this keyword is waiting for the process to end, the process is killed to avoid leaving it running on the background. This is new in Robot Framework 7.3.
- terminate_process(handle: Popen | str | None = None, kill: bool = False) ProcessResult[source]
Stops the process gracefully or forcefully.
If
handleis not given, uses the current active process.By default, first tries to stop the process gracefully. If the process does not stop in 30 seconds, or the
killargument is given a true value, kills the process forcefully. Stops also all the child processes of the originally started process.Waits for the process to stop after terminating it. Returns a result object containing information about the execution similarly as Wait For Process.
On Unix-like machines graceful termination is done using
TERM (15)signal and forceful kill usingKILL (9). Use Send Signal To Process instead if you just want to send either of these signals without waiting for the process to stop.On Windows graceful termination is done using
CTRL_BREAK_EVENTevent and forceful kill using Win32 API functionTerminateProcess(). In this case forceful kill only stops the main process, not possible child processes.
- terminate_all_processes(kill: bool = False)[source]
Terminates all still running processes started by this library.
This keyword can be used in suite teardown or elsewhere to make sure that all processes are stopped,
Tries to terminate processes gracefully by default, but can be configured to forcefully kill them immediately. See Terminate Process that this keyword uses internally for more details.
- send_signal_to_process(signal: int | str, handle: Popen | str | None = None, group: bool = False)[source]
Sends the given
signalto the specified process.If
handleis not given, uses the current active process.Signal can be specified either as an integer as a signal name. In the latter case it is possible to give the name both with or without
SIGprefix, but names are case-sensitive. For example, all the examples below send signalINT (2):This keyword is only supported on Unix-like machines, not on Windows. What signals are supported depends on the system. For a list of existing signals on your system, see the Unix man pages related to signal handling (typically
man signalorman 7 signal).By default, sends the signal only to the parent process, not to possible child processes started by it. Notice that when running processes in shell, the shell is the parent process, and it depends on the system does the shell propagate the signal to the actual started process.
To send the signal to the whole process group, give the
groupargument a true value.
- get_process_id(handle: Popen | str | None = None) int[source]
Returns the process ID (pid) of the process as an integer.
If
handleis not given, uses the current active process.Starting from Robot Framework 5.0, it is also possible to directly access the
pidattribute of thesubprocess.Popenobject returned by Start Process like${process.pid}.
- get_process_object(handle: Popen | str | None = None) Popen[source]
Return the underlying
subprocess.Popenobject.If
handleis not given, uses the current active process.Starting from Robot Framework 5.0, Start Process returns the created
subprocess.Popenobject, not a generic handle, making this keyword mostly redundant.
- get_process_result(handle: Popen | str | None = None, rc: bool = False, stdout: bool = False, stderr: bool = False, stdout_path: bool = False, stderr_path: bool = False) ProcessResult | int | str | tuple[int | str, ...][source]
Returns the specified result object or some of its attributes.
The given
handlespecifies the process whose results should be returned. If nohandleis given, results of the current active process are returned. In either case, the process must have been finishes before this keyword can be used. In practice this means that processes started with Start Process must be finished either with Wait For Process or Terminate Process before using this keyword.If no other arguments than the optional
handleare given, a whole result object is returned. If one or more of the other arguments are given any true value, only the specified attributes of the result object are returned. These attributes are always returned in the same order as arguments are specified in the keyword signature.Although getting results of a previously executed process can be handy in general, the main use case for this keyword is returning results over the remote library interface. The remote interface does not support returning the whole result object, but individual attributes can be returned without problems.
- switch_process(handle: Popen | str | None)[source]
Makes the specified process the current active process.
The handle can be an identifier returned by Start Process or the
aliasgiven to it explicitly.
- ROBOT_AUTO_KEYWORDS = True
- ROBOT_LIBRARY_CONVERTERS = {<class 'robot.libraries.Process.ProcessResult'>: <function <lambda>>, <class 'subprocess.Popen'>: <function _popen_documentation>}
- split_command_line(command: str, escaping: bool = False) list[str][source]
Splits command line string into a list of arguments.
String is split from spaces, but argument surrounded in quotes may contain spaces in them.
If
escapingis given a true value, then backslash is treated as an escape character. It can escape unquoted spaces, quotes inside quotes, and so on, but it also requires doubling backslashes in Windows paths and elsewhere.
- join_command_line(*command: Sequence[str] | str) str[source]
Joins arguments into one command line string.
In resulting command line string arguments are delimited with a space, arguments containing spaces are surrounded with quotes, and possible quotes are escaped with a backslash.
Command to join can be given as individual arguments or as a list.
Giving command as individual arguments:
Giving command as a list:
robot.libraries.Remote module
- class robot.libraries.Remote.Remote(uri='http://127.0.0.1:8270', timeout=None)[source]
Bases:
objectConnects to a remote server at
uri.Optional
timeoutcan be used to specify a timeout to wait when initially connecting to the server and if a connection accidentally closes. Timeout can be given as seconds (e.g.60) or using Robot Framework time format (e.g.60s,2 minutes 10 seconds).The default timeout is typically several minutes, but it depends on the operating system and its configuration. Notice that setting a timeout that is shorter than keyword execution time will interrupt the keyword.
- ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
- class robot.libraries.Remote.ArgumentCoercer[source]
Bases:
object- binary = re.compile('[\x00-\x08\x0b\x0c\x0e-\x1f]')
- class robot.libraries.Remote.TimeoutHTTPSTransport(timeout=None)[source]
Bases:
TimeoutHTTPTransport
robot.libraries.Screenshot module
- class robot.libraries.Screenshot.Screenshot(screenshot_directory: Path | None = None, screenshot_module: str | None = None)[source]
Bases:
objectLibrary for taking screenshots on the machine where tests are executed.
Taking the actual screenshot requires a suitable tool or module that may need to be installed separately. Taking screenshots also requires tests to be run with a physical or virtual display.
== Table of contents ==
%TOC%
= Supported screenshot taking tools and modules =
How screenshots are taken depends on the operating system. On OSX screenshots are taken using the built-in
screencaptureutility. On other operating systems you need to have one of the following tools or Python modules installed. You can specify the tool/module to use when importing the library. If no tool or module is specified, the first one found will be used.wxPython :: http://wxpython.org :: Generic Python GUI toolkit.
PyGTK :: http://pygtk.org :: This module is available by default on most Linux distributions.
Pillow :: http://python-pillow.github.io :: Only works on Windows. Also the original PIL package is supported.
Scrot :: http://en.wikipedia.org/wiki/Scrot :: Not used on Windows. Install with
apt-get install scrotor similar.
= Where screenshots are saved =
By default screenshots are saved into the same directory where the Robot Framework log file is written. If no log is created, screenshots are saved into the directory where the XML output file is written.
It is possible to specify a custom location for screenshots using
screenshot_directoryargument when importing the library and using Set Screenshot Directory keyword during execution. It is also possible to save screenshots using an absolute path.= ScreenCapLibrary =
[https://github.com/mihaiparvu/ScreenCapLibrary|ScreenCapLibrary] is an external Robot Framework library that can be used as an alternative, which additionally provides support for multiple formats, adjusting the quality, using GIFs and video capturing.
Configure where screenshots are saved.
If
screenshot_directoryis not given, screenshots are saved into same directory as the log file. The directory can also be set using Set Screenshot Directory keyword.screenshot_modulespecifies the module or tool to use when using this library outside OSX. Possible values arewxPython,PyGTK,PILandscrot, case-insensitively. If no value is given, the first module/tool found is used in that order.- ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
- ROBOT_LIBRARY_VERSION = '7.4.2'
- set_screenshot_directory(path: Path) str[source]
Sets the directory where screenshots are saved.
It is possible to use
/as a path separator in all operating systems. Path to the old directory is returned.The directory can also be set in importing.
- take_screenshot(name: str = 'screenshot', width: str = '800px') str[source]
Takes a screenshot in JPEG format and embeds it into the log file.
Name of the file where the screenshot is stored is derived from the given
name. If thenameends with extension.jpgor.jpeg, the screenshot will be stored with that exact name. Otherwise a unique name is created by adding an underscore, a running index and an extension to thename.The name will be interpreted to be relative to the directory where the log file is written. It is also possible to use absolute paths. Using
/as a path separator works in all operating systems.widthspecifies the size of the screenshot in the log file.The path where the screenshot is saved is returned.
- take_screenshot_without_embedding(name: str = 'screenshot') str[source]
Takes a screenshot and links it from the log file.
This keyword is otherwise identical to Take Screenshot but the saved screenshot is not embedded into the log file. The screenshot is linked so it is nevertheless easily available.
robot.libraries.String module
- class robot.libraries.String.String[source]
Bases:
objectA library for string manipulation and verification.
Stringis Robot Framework’s standard library for manipulating strings (e.g. Replace String Using Regexp, Split To Lines) and verifying their contents (e.g. Should Be String).In addition to strings, most of the keywords work also with bytes. Bytes support was heavily enhanced in Robot Framework 7.4.
Following keywords from
BuiltInlibrary can also be used with strings and bytes:Get Length
Length Should Be
Should (Not) Be Empty
Should (Not) Be Equal (As Strings/Integers/Numbers)
Should (Not) Match (Regexp)
Should (Not) Contain
Should (Not) Start With
Should (Not) End With
Convert To String
Convert To Bytes
- ROBOT_LIBRARY_SCOPE = 'GLOBAL'
- ROBOT_LIBRARY_VERSION = '7.4.2'
- convert_to_lower_case(string: str | bytes) str | bytes[source]
Converts string to lower case.
Uses Python’s standard [https://docs.python.org/library/stdtypes.html#str.lower|lower()] method.
If this keyword is used with bytes, only ASCII characters are lower cased.
- convert_to_upper_case(string: str | bytes) str | bytes[source]
Converts string to upper case.
Uses Python’s standard [https://docs.python.org/library/stdtypes.html#str.upper|upper()] method.
If this keyword is used with bytes, only ASCII characters are upper cased.
- convert_to_title_case(string: str | bytes, exclude: str | bytes | list[str | bytes] | None = None) str | bytes[source]
Converts string to title case.
Uses the following algorithm:
Split the string to words from whitespace characters (spaces, newlines, etc.).
Exclude words that are not all lower case. This preserves, for example, “OK” and “iPhone”.
Exclude also words listed in the optional
excludeargument.Title case the first alphabetical character of each word that has not been excluded.
Join all words together so that original whitespace is preserved.
Explicitly excluded words can be given as a list or as a string with words separated by a comma and an optional space. Excluded words are actually considered to be regular expression patterns, so it is possible to use something like “example[.!?]?” to match the word “example” on it own and also if followed by “.”, “!” or “?”. See BuiltIn.Should Match Regexp for more information about Python regular expression syntax in general and how to use it in Robot Framework data in particular.
The reason this keyword does not use Python’s standard [https://docs.python.org/library/stdtypes.html#str.title|title()] method is that it can yield undesired results, for example, if strings contain upper case letters or special characters like apostrophes. It would, for example, convert “it’s an OK iPhone” to “It’S An Ok Iphone”.
If this keyword is used with bytes, only ASCII characters are title cased. Bytes support is new in Robot Framework 7.4.
- encode_string_to_bytes(string: str, encoding: str, errors: str = 'strict') bytes[source]
Encodes the given
stringto bytes using the givenencoding.errorsargument controls what to do if encoding some characters fails. All values accepted byencodemethod in Python are valid, but in practice the following values are most useful:strict: fail if characters cannot be encoded (default)ignore: ignore characters that cannot be encodedreplace: replace characters that cannot be encoded with a replacement character
Use Convert To Bytes in
BuiltInif you want to create bytes based on character or integer sequences. Use Decode Bytes To String if you need to convert bytes to strings and Convert To String inBuiltInif you need to convert arbitrary objects to strings.
- decode_bytes_to_string(bytes: bytes, encoding: str, errors: str = 'strict') str[source]
Decodes the given
bytesto a string using the givenencoding.errorsargument controls what to do if decoding some bytes fails. All values accepted bydecodemethod in Python are valid, but in practice the following values are most useful:strict: fail if characters cannot be decoded (default)ignore: ignore characters that cannot be decodedreplace: replace characters that cannot be decoded with a replacement character
Use Encode String To Bytes if you need to convert strings to bytes, and Convert To String in
BuiltInif you need to convert arbitrary objects to strings.
- format_string(template: str | bytes, /, *positional: object, **named: object) str | bytes[source]
Formats a
templateusing the givenpositionalandnamedarguments.The template can be either be a string or an absolute path to an existing file. In the latter case the file is read and its contents are used as the template. If the template file contains non-ASCII characters, it must be encoded using UTF-8.
The template is formatted using Python’s [https://docs.python.org/library/string.html#format-string-syntax|format string syntax]. Placeholders are marked using
{}with possible field name and format specification inside. Literal curly braces can be inserted by doubling them like {{ and }}.Prior to Robot Framework 7.1, possible equal signs in the template string needed to be escaped with a backslash like ``x={}`.
Support for bytes is new in Robot Framework 7.4.
- get_line_count(string: str | bytes) int[source]
Returns and logs the number of lines in the given string.
- split_to_lines(string: str | bytes, start: int | Literal[''] | None = 0, end: int | Literal[''] | None = None) list[str] | list[bytes][source]
Splits the given string to lines.
It is possible to get only a selection of lines from
starttoendso thatstartindex is inclusive andendis exclusive. Line numbering starts from 0, and it is possible to use negative indices to refer to lines from the end.Lines are returned without the newlines. The number of returned lines is automatically logged.
Use Get Line if you only need to get a single line.
- get_line(string: str | bytes, line_number: int) str | bytes[source]
Returns the specified line from the given
string.Line numbering starts from 0, and it is possible to use negative indices to refer to lines from the end. The line is returned without the newline character.
Use Split To Lines if all lines are needed.
- get_lines_containing_string(string: str | bytes, pattern: str | bytes, case_insensitive: bool | None = None, ignore_case: bool = False) str | bytes[source]
Returns lines of the given
stringthat contain thepattern.The
patternis always considered to be a normal string, not a glob or regexp pattern. A line matches if thepatternis found anywhere on it.The match is case-sensitive by default, but that can be changed by giving
ignore_casea true value. This option is new in Robot Framework 7.0, but with older versions it is possible to use the nowadays deprecatedcase_insensitiveargument.Lines are returned as a string with lines joined together with a newline. Possible trailing newline is never returned. The number of matching lines is automatically logged.
See Get Lines Matching Pattern and Get Lines Matching Regexp if you need more complex pattern matching.
If the first argument is bytes, the second argument is automatically converted to bytes as well.
Bytes support is new in Robot Framework 7.4.
- get_lines_matching_pattern(string: str | bytes, pattern: str | bytes, case_insensitive: bool | None = None, ignore_case: bool = False) str | bytes[source]
Returns lines of the given
stringthat match thepattern.The
patternis a _glob pattern_ where:A line matches only if it matches the
patternfully.The match is case-sensitive by default, but that can be changed by giving
ignore_casea true value. This option is new in Robot Framework 7.0, but with older versions it is possible to use the nowadays deprecatedcase_insensitiveargument.Lines are returned as a string with lines joined together with a newline. Possible trailing newline is never returned. The number of matching lines is automatically logged.
See Get Lines Matching Regexp if you need more complex patterns and Get Lines Containing String if searching literal strings is enough.
If the first argument is bytes, the second argument is automatically converted to bytes as well.
Bytes support is new in Robot Framework 7.4.
- get_lines_matching_regexp(string: str | bytes, pattern: str | bytes, partial_match: bool = False, flags: str | None = None) str | bytes[source]
Returns lines of the given
stringthat match the regexppattern.See BuiltIn.Should Match Regexp for more information about Python regular expression syntax in general and how to use it in Robot Framework data in particular.
Lines match only if they match the pattern fully by default, but partial matching can be enabled by giving the
partial_matchargument a true value.If the pattern is empty, it matches only empty lines by default. When partial matching is enabled, empty pattern matches all lines.
Possible flags altering how the expression is parsed (e.g.
re.IGNORECASE,re.VERBOSE) can be given using theflagsargument (e.g.flags=IGNORECASE | VERBOSE) or embedded to the pattern (e.g.(?ix)pattern).Lines are returned as one string concatenated back together with newlines. Possible trailing newline is never returned. The number of matching lines is automatically logged.
See Get Lines Matching Pattern and Get Lines Containing String if you do not need the full regular expression powers (and complexity).
The
flagsargument is new in Robot Framework 6.0.If the first argument is bytes, the second argument is automatically converted to bytes as well. This is new in Robot Framework 7.4.
- get_regexp_matches(string: str | bytes, pattern: str | bytes, *groups: int | str, flags: str | None = None) list[str] | list[tuple[str, ...]] | list[bytes] | list[tuple[bytes, ...]][source]
Returns a list of all non-overlapping matches in the given string.
stringis the string to find matches from andpatternis the regular expression. See BuiltIn.Should Match Regexp for more information about Python regular expression syntax in general and how to use it in Robot Framework data in particular.If no groups are used, the returned list contains full matches. If one group is used, the list contains only contents of that group. If multiple groups are used, the list contains tuples that contain individual group contents. All groups can be given as indexes (starting from 1) and named groups also as names.
Possible flags altering how the expression is parsed (e.g.
re.IGNORECASE,re.MULTILINE) can be given using theflagsargument (e.g.flags=IGNORECASE | MULTILINE) or embedded to the pattern (e.g.(?im)pattern).If the first argument is bytes, the second argument is automatically converted to bytes as well. This is new in Robot Framework 7.4.
The
flagsargument is new in Robot Framework 6.0.
- replace_string(string: str | bytes, search_for: str | bytes, replace_with: str | bytes, count: int = -1) str | bytes[source]
Replaces
search_forin the givenstringwithreplace_with.search_foris used as a literal string. See Replace String Using Regexp if more powerful pattern matching is needed. If you need to just remove a string see Remove String.If the optional argument
countis given, only that many occurrences from left are replaced. Negativecountmeans that all occurrences are replaced (default behaviour) and zero means that nothing is done.A modified version of the string is returned and the original string is not altered.
If the first argument is bytes, the following two arguments are automatically converted to bytes as well. This is new in Robot Framework 7.4.
- replace_string_using_regexp(string: str | bytes, pattern: str | bytes, replace_with: str | bytes, count: int = -1, flags: str | None = None) str | bytes[source]
Replaces
patternin the givenstringwithreplace_with.This keyword is otherwise identical to Replace String, but the
patternto search for is considered to be a regular expression. See BuiltIn.Should Match Regexp for more information about Python regular expression syntax in general and how to use it in Robot Framework data in particular.Possible flags altering how the expression is parsed (e.g.
re.IGNORECASE,re.MULTILINE) can be given using theflagsargument (e.g.flags=IGNORECASE | MULTILINE) or embedded to the pattern (e.g.(?im)pattern).If you need to just remove a string see Remove String Using Regexp.
If the first argument is bytes, the following two arguments are automatically converted to bytes as well. This is new in Robot Framework 7.4.
The
flagsargument is new in Robot Framework 6.0.
- remove_string(string: str | bytes, *removables: str | bytes) str | bytes[source]
Removes all
removablesfrom the givenstring.removablesare used as literal strings. Each removable will be matched to a temporary string from which preceding removables have been already removed. See second example below.Use Remove String Using Regexp if more powerful pattern matching is needed. If only a certain number of matches should be removed, Replace String or Replace String Using Regexp can be used.
A modified version of the string is returned and the original string is not altered.
If the first argument is bytes, the second argument is automatically converted to bytes as well.
Bytes support is new in Robot Framework 7.4.
- remove_string_using_regexp(string: str | bytes, *patterns: str | bytes, flags: str | None = None) str | bytes[source]
Removes
patternsfrom the givenstring.This keyword is otherwise identical to Remove String, but the
patternsto search for are considered to be a regular expression. See Replace String Using Regexp for more information about the regular expression syntax. That keyword can also be used if there is a need to remove only a certain number of occurrences.Possible flags altering how the expression is parsed (e.g.
re.IGNORECASE,re.MULTILINE) can be given using theflagsargument (e.g.flags=IGNORECASE | MULTILINE) or embedded to the pattern (e.g.(?im)pattern).If the first argument is bytes, the second argument is automatically converted to bytes as well.
The
flagsargument is new in Robot Framework 6.0. Bytes support is new in Robot Framework 7.4.
- split_string(string: str | bytes, separator: str | bytes | None = None, max_split: int = -1) list[str] | list[bytes][source]
Splits the
stringusingseparatoras a delimiter string.If a
separatoris not given, any whitespace string is a separator. In that case also possible consecutive whitespace as well as leading and trailing whitespace is ignored.Split words are returned as a list. If the optional
max_splitis given, at mostmax_splitsplits are done, and the returned list will have maximummax_split + 1elements.See Split String From Right if you want to start splitting from right, and Fetch From Left and Fetch From Right if you only want to get first/last part of the string.
If the first argument is bytes, the second argument is automatically converted to bytes as well. This is new in Robot Framework 7.4.
- split_string_from_right(string: str | bytes, separator: str | bytes | None = None, max_split: int = -1) list[str] | list[bytes][source]
Splits the
stringusingseparatorstarting from right.Same as Split String, but splitting is started from right. This has an effect only when
max_splitis given.If the first argument is bytes, the second argument is automatically converted to bytes as well. This is new in Robot Framework 7.4.
- split_string_to_characters(string: str | bytes) list[str] | list[bytes][source]
Splits the given
stringto characters.Bytes support is new in Robot Framework 7.4.
- fetch_from_left(string: str | bytes, marker: str | bytes) str | bytes[source]
Returns contents of the
stringbefore the first occurrence ofmarker.If the
markeris not found, whole string is returned.If the first argument is bytes, the second argument is automatically converted to bytes as well. This is new in Robot Framework 7.4.
See also Fetch From Right, Split String and Split String From Right.
- fetch_from_right(string: str | bytes, marker: str | bytes) str | bytes[source]
Returns contents of the
stringafter the last occurrence ofmarker.If the
markeris not found, whole string is returned.If the first argument is bytes, the second argument is automatically converted to bytes as well. This is new in Robot Framework 7.4.
See also Fetch From Left, Split String and Split String From Right.
- generate_random_string(length: int | str = 8, chars: str = '[LETTERS][NUMBERS]') str[source]
Generates a string with a desired
lengthfrom the givenchars.lengthcan be given as a number, a string representation of a number, or as a range of numbers, such as5-10. When a range of values is given the range will be selected by random within the range.The population sequence
charscontains the characters to use when generating the random string. It can contain any characters, and it is possible to use special markers explained in the table below:Giving
lengthas a range of values is new in Robot Framework 5.0. Support for markers[POLISH]and[ARABIC]is new in Robot Framework 7.4.
- get_substring(string: str | bytes, start: int | Literal[''] | None = 0, end: int | Literal[''] | None = None) str | bytes[source]
Returns a substring from
startindex toendindex.The
startindex is inclusive andendis exclusive. Indexing starts from 0, and it is possible to use negative indices to refer to characters from the end.Default value with
startis new in Robot Framework 7.4.
- strip_string(string: str | bytes, mode: Literal['left', 'right', 'both', 'none'] = 'both', characters: str | bytes | None = None) str | bytes[source]
Remove leading and/or trailing whitespaces from the given string.
modeis eitherleftto remove leading characters,rightto remove trailing characters,both(default) to remove the characters from both sides of the string ornoneto return the unmodified string.If the optional
charactersis given, it must be a string and the characters in the string will be stripped in the string. Please note, that this is not a substring to be removed but a list of characters, see the example below.If the first argument is bytes, the
charactersargument is automatically converted to bytes as well.Bytes support is new in Robot Framework 7.4.
- should_be_string(item: object, msg: str | None = None)[source]
Fails if the given
itemis not a string.The default error message can be overridden with the optional
msgargument.
- should_not_be_string(item: object, msg: str | None = None)[source]
Fails if the given
itemis a string.The default error message can be overridden with the optional
msgargument.
- should_be_unicode_string(item: object, msg: str | None = None)[source]
Fails if the given
itemis not a Unicode string.On Python 3 this keyword behaves exactly the same way Should Be String. That keyword should be used instead and this keyword will be deprecated.
- should_be_byte_string(item: object, msg: str | None = None)[source]
Fails if the given
itemis not a byte string.Use Should Be String if you want to verify the
itemis a string.The default error message can be overridden with the optional
msgargument.
- should_be_lower_case(string: str | bytes, msg: str | None = None)[source]
Fails if the given
stringis not in lower case.For example,
'string'and'with specials!'would pass, and'String',''and' 'would fail.The default error message can be overridden with the optional
msgargument.See also Should Be Upper Case and Should Be Title Case.
- should_be_upper_case(string: str | bytes, msg: str | None = None)[source]
Fails if the given
stringis not in upper case.For example,
'STRING'and'WITH SPECIALS!'would pass, and'String',''and' 'would fail.The default error message can be overridden with the optional
msgargument.See also Should Be Title Case and Should Be Lower Case.
- should_be_title_case(string: str | bytes, msg: str | None = None, exclude: str | bytes | list[str | bytes] | None = None)[source]
Fails if given
stringis not title.stringis a title cased string if there is at least one upper case letter in each word.For example,
'This Is Title'and'OK, Give Me My iPhone'would pass.'all words lower'and'Word In lower'would fail.This logic changed in Robot Framework 4.0 to be compatible with Convert to Title Case. See Convert to Title Case for title case algorithm and reasoning.
The default error message can be overridden with the optional
msgargument.Words can be explicitly excluded with the optional
excludeargument.Explicitly excluded words can be given as a list or as a string with words separated by a comma and an optional space. Excluded words are actually considered to be regular expression patterns, so it is possible to use something like “example[.!?]?” to match the word “example” on it own and also if followed by “.”, “!” or “?”. See BuiltIn.Should Match Regexp for more information about Python regular expression syntax in general and how to use it in Robot Framework data in particular.
See also Should Be Upper Case and Should Be Lower Case.
robot.libraries.Telnet module
robot.libraries.XML module
- class robot.libraries.XML.Source[source]
Bases:
objectXML source.
Can be given as a path to an XML file, as a string or bytes containing XML data, or as an already parsed XML element structure.
- class robot.libraries.XML.Element[source]
Bases:
objectA parsed XML element.
Represented as an ElementTree [https://docs.python.org/3/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element|Element] object. Can be used as a
sourceargument with keywords modifying or validating XML elements. In addition to that, attributes liketextcan be accessed using the extended variable syntax like${elem.text}directly.
- class robot.libraries.XML.XML(use_lxml: bool = False)[source]
Bases:
objectRobot Framework library for verifying and modifying XML documents.
As the name implies, _XML_ is a library for verifying contents of XML files. In practice, it is a pretty thin wrapper on top of Python’s [http://docs.python.org/library/xml.etree.elementtree.html|ElementTree XML API].
The library has the following main usages:
Parsing an XML file, or a string containing XML, into an XML element structure and finding certain elements from it for further analysis (e.g. Parse XML and Get Element keywords).
Getting text or attributes of elements (e.g. Get Element Text and Get Element Attribute).
Directly verifying text, attributes, or whole elements (e.g Element Text Should Be and Elements Should Be Equal).
Modifying XML and saving it (e.g. Set Element Text, Add Element and Save XML).
== Table of contents ==
%TOC%
= Parsing XML =
XML can be parsed into an element structure using Parse XML keyword. The XML to be parsed can be specified using a path to an XML file or as a string or bytes that contain XML directly. The keyword returns the root element of the structure, which then contains other elements as its children and their children. Possible comments and processing instructions in the source XML are removed.
XML is not validated during parsing even if it has a schema defined. How possible doctype elements are handled otherwise depends on the used XML module and on the platform. The standard ElementTree strips doctypes altogether, but when using lxml they are preserved when XML is saved.
The element structure returned by Parse XML, as well as elements returned by keywords such as Get Element, can be used as the
sourceargument with other keywords. In addition to an already parsed XML structure, other keywords also accept paths to XML files and strings containing XML similarly as Parse XML. Notice that keywords that modify XML do not write those changes back to disk even if the source would be given as a path to a file. Changes must always be saved explicitly using Save XML keyword.When the source is given as a path to a file, the forward slash character (
/) can be used as the path separator regardless the operating system. On Windows also the backslash works, but in the data it needs to be escaped by doubling it (\\). Using the built-in variable${/}naturally works too.= Using lxml =
By default, this library uses Python’s standard [http://docs.python.org/library/xml.etree.elementtree.html|ElementTree] module for parsing XML, but it can be configured to use [http://lxml.de|lxml] module instead when importing the library. The resulting element structure has same API regardless which module is used for parsing.
The main benefits of using lxml is that it supports richer xpath syntax than the standard ElementTree and enables using Evaluate Xpath keyword. It also preserves the doctype and possible namespace prefixes saving XML.
= Example =
The following simple example demonstrates parsing XML and verifying its contents both using keywords in this library and in _BuiltIn_ and _Collections_ libraries. How to use xpath expressions to find elements and what attributes the returned elements contain are discussed, with more examples, in Finding elements with xpath and Element attributes sections.
In this example, as well as in many other examples in this documentation,
${XML}refers to the following example XML document. In practice${XML}could either be a path to an XML file or it could contain the XML itself.Notice that in the example three last lines are equivalent. Which one to use in practice depends on which other elements you need to get or verify. If you only need to do one verification, using the last line alone would suffice. If more verifications are needed, parsing the XML with Parse XML only once would be more efficient.
= Finding elements with xpath =
ElementTree, and thus also this library, supports finding elements using xpath expressions. ElementTree does not, however, support the full xpath standard. The supported xpath syntax is explained below and [https://docs.python.org/library/xml.etree.elementtree.html#xpath-support| ElementTree documentation] provides more details. In the examples
${XML}refers to the same XML structure as in the earlier example.If lxml support is enabled when importing the library, the whole [http://www.w3.org/TR/xpath/|xpath 1.0 standard] is supported. That includes everything listed below but also a lot of other useful constructs.
== Tag names ==
When just a single tag name is used, xpath matches all direct child elements that have that tag name.
== Paths ==
Paths are created by combining tag names with a forward slash (
/). For example,parent/childmatches allchildelements underparentelement. Notice that if there are multipleparentelements that all havechildelements,parent/childxpath will match all thesechildelements.== Wildcards ==
An asterisk (
*) can be used in paths instead of a tag name to denote any element.== Current element ==
The current element is denoted with a dot (
.). Normally the current element is implicit and does not need to be included in the xpath.== Parent element ==
The parent element of another element is denoted with two dots (
..). Notice that it is not possible to refer to the parent of the current element.== Search all sub elements ==
Two forward slashes (
//) mean that all sub elements, not only the direct children, are searched. If the search is started from the current element, an explicit dot is required.== Predicates ==
Predicates allow selecting elements using also other criteria than tag names, for example, attributes or position. They are specified after the normal tag name or path using syntax
path[predicate]. The path can have wildcards and other special syntax explained earlier. What predicates the standard ElementTree supports is explained in the table below.Predicates can also be stacked like
path[predicate1][predicate2]. A limitation is that possible position predicate must always be first.= Element attributes =
All keywords returning elements, such as Parse XML, and Get Element, return ElementTree’s [http://docs.python.org/library/xml.etree.elementtree.html#element-objects|Element objects]. These elements can be used as inputs for other keywords, but they also contain several useful attributes that can be accessed directly using the extended variable syntax.
The attributes that are both useful and convenient to use in the data are explained below. Also other attributes, including methods, can be accessed, but that is typically better to do in custom libraries than directly in the data.
The examples use the same
${XML}structure as the earlier examples.== tag ==
The tag of the element.
== text ==
The text that the element contains or Python
Noneif the element has no text. Notice that the text _does not_ contain texts of possible child elements nor text after or between children. Notice also that in XML whitespace is significant, so the text contains also possible indentation and newlines. To get also text of the possible children, optionally whitespace normalized, use Get Element Text keyword.== tail ==
The text after the element before the next opening or closing tag. Python
Noneif the element has no tail. Similarly as withtext, alsotailcontains possible indentation and newlines.== attrib ==
A Python dictionary containing attributes of the element.
= Handling XML namespaces =
ElementTree and lxml handle possible namespaces in XML documents by adding the namespace URI to tag names in so-called Clark Notation. That is inconvenient especially with xpaths, and by default this library strips those namespaces away and moves them to
xmlnsattribute instead. That can be avoided by passingkeep_clark_notationargument to Parse XML keyword. Alternatively Parse XML supports stripping namespace information altogether by usingstrip_namespacesargument. The pros and cons of different approaches are discussed in more detail below.== How ElementTree handles namespaces ==
If an XML document has namespaces, ElementTree adds namespace information to tag names in [http://www.jclark.com/xml/xmlns.htm|Clark Notation] (e.g.
{http://ns.uri}tag) and removes originalxmlnsattributes. This is done both with default namespaces and with namespaces with a prefix. How it works in practice is illustrated by the following example, where${NS}variable contains this XML document:As you can see, including the namespace URI in tag names makes xpaths really long and complex.
If you save the XML, ElementTree moves namespace information back to
xmlnsattributes. Unfortunately it does not restore the original prefixes:The resulting output is semantically same as the original, but mangling prefixes like this may still not be desirable. Notice also that the actual output depends slightly on ElementTree version.
== Default namespace handling ==
Because the way ElementTree handles namespaces makes xpaths so complicated, this library, by default, strips namespaces from tag names and moves that information back to
xmlnsattributes. How this works in practice is shown by the example below, where${NS}variable contains the same XML document as in the previous example.Now that tags do not contain namespace information, xpaths are simple again.
A minor limitation of this approach is that namespace prefixes are lost. As a result the saved output is not exactly same as the original one in this case either:
Also this output is semantically same as the original. If the original XML had only default namespaces, the output would also look identical.
== Namespaces when using lxml ==
This library handles namespaces same way both when using lxml and when not using it. There are, however, differences how lxml internally handles namespaces compared to the standard ElementTree. The main difference is that lxml stores information about namespace prefixes and they are thus preserved if XML is saved. Another visible difference is that lxml includes namespace information in child elements got with Get Element if the parent element has namespaces.
== Stripping namespaces altogether ==
Because namespaces often add unnecessary complexity, Parse XML supports stripping them altogether by using
strip_namespaces=True. When this option is enabled, namespaces are not shown anywhere nor are they included if XML is saved.== Attribute namespaces ==
Attributes in XML documents are, by default, in the same namespaces as the element they belong to. It is possible to use different namespaces by using prefixes, but this is pretty rare.
If an attribute has a namespace prefix, ElementTree will replace it with Clark Notation the same way it handles elements. Because stripping namespaces from attributes could cause attribute conflicts, this library does not handle attribute namespaces at all. The following example thus works the same way regardless how namespaces are handled.
== Pattern matching ==
Some keywords, for example Elements Should Match, support so called [http://en.wikipedia.org/wiki/Glob_(programming)|glob patterns] where:
Unlike with glob patterns normally, path separator characters
/and\and the newline character\nare matches by the above wildcards.Import library with optionally lxml mode enabled.
This library uses Python’s standard [http://docs.python.org/library/xml.etree.elementtree.html|ElementTree] module for parsing XML by default. If
use_lxmlargument is given a true value, the [http://lxml.de|lxml] module is used instead. See the Using lxml section for benefits provided by lxml.Using lxml requires that the lxml module is installed on the system. If lxml mode is enabled but the module is not installed, this library emits a warning and reverts back to using the standard ElementTree.
- ROBOT_LIBRARY_SCOPE = 'GLOBAL'
- ROBOT_LIBRARY_VERSION = '7.4.2'
- parse_xml(source: Source, keep_clark_notation: bool = False, strip_namespaces: bool = False) Element[source]
Parses the given XML file or string into an element structure.
The
sourcecan either be a path to an XML file or a string containing XML. In both cases the XML is parsed into ElementTree [https://docs.python.org/3/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element|Element] structure. Possible comments and processing instructions in the source XML are removed.As discussed in Handling XML namespaces section, this keyword, by default, removes namespace information ElementTree has added to tag names and moves it into
xmlnsattributes. This typically eases handling XML documents with namespaces considerably. If you do not want that to happen, or want to avoid the small overhead of going through the element structure when your XML does not have namespaces, you can disable this feature by givingkeep_clark_notationargument a true value.If you want to strip namespace information altogether so that it is not included even if XML is saved, you can give a true value to
strip_namespacesargument.Use Get Element keyword if you want to get a certain element and not the whole structure. See Parsing XML section for more details and examples.
NOTE: This keyword does not accept an already parsed XML element as an argument. Use Get Element instead.
- get_element(source: Source, xpath: str = '.') Element[source]
Returns an element in the
sourcematching thexpath.The
sourcecan be a path to an XML file, a string containing XML, or an already parsed XML element. Thexpathspecifies which element to find. See the introduction for more details about both the possible sources and the supported xpath syntax.The keyword fails if more, or less, than one element matches the
xpath. Use Get Elements if you want all matching elements to be returned.Parse XML is recommended for parsing XML when the whole structure is needed. It must be used if there is a need to configure how XML namespaces are handled.
Many other keywords use this keyword internally, and keywords modifying XML are typically documented to both to modify the given source and to return it. Modifying the source does not apply if the source is given as a string. The XML structure parsed based on the string and then modified is nevertheless returned.
- get_elements(source: Source, xpath: str) list[Element][source]
Returns a list of elements in the
sourcematching thexpath.The
sourcecan be a path to an XML file, a string containing XML, or an already parsed XML element. Thexpathspecifies which element to find. See the introduction for more details.Elements matching the
xpathare returned as a list. If no elements match, an empty list is returned. Use Get Element if you want to get exactly one match.
- get_child_elements(source: Source, xpath: str = '.') list[Element][source]
Returns the child elements of the specified element as a list.
The element whose children to return is specified using
sourceandxpath. They have exactly the same semantics as with Get Element keyword.All the direct child elements of the specified element are returned. If the element has no children, an empty list is returned.
- get_element_count(source: Source, xpath: str = '.') int[source]
Returns and logs how many elements the given
xpathmatches.Arguments
sourceandxpathhave exactly the same semantics as with Get Elements keyword that this keyword uses internally.See also Element Should Exist and Element Should Not Exist.
- element_should_exist(source: Source, xpath: str = '.', message: str | None = None)[source]
Verifies that one or more element match the given
xpath.Arguments
sourceandxpathhave exactly the same semantics as with Get Elements keyword. Keyword passes if thexpathmatches one or more elements in thesource. The default error message can be overridden with themessageargument.See also Element Should Not Exist as well as Get Element Count that this keyword uses internally.
- element_should_not_exist(source: Source, xpath: str = '.', message: str | None = None)[source]
Verifies that no element match the given
xpath.Arguments
sourceandxpathhave exactly the same semantics as with Get Elements keyword. Keyword fails if thexpathmatches any element in thesource. The default error message can be overridden with themessageargument.See also Element Should Exist as well as Get Element Count that this keyword uses internally.
- get_element_text(source: Source, xpath: str = '.', normalize_whitespace: bool = False) str[source]
Returns all text of the element, possibly whitespace normalized.
The element whose text to return is specified using
sourceandxpath. They have exactly the same semantics as with Get Element keyword.This keyword returns all the text of the specified element, including all the text its children and grandchildren contain. If the element has no text, an empty string is returned. The returned text is thus not always the same as the text attribute of the element.
All whitespace, including newlines and indentation, inside the element is returned as-is. If
normalize_whitespaceis given a true value, then leading and trailing whitespace is stripped, newlines and tabs converted to spaces, and multiple spaces collapsed into one. This is especially useful when dealing with HTML data.See also Get Elements Texts, Element Text Should Be and Element Text Should Match.
- get_elements_texts(source: Source, xpath: str, normalize_whitespace: bool = False) list[str][source]
Returns text of all elements matching
xpathas a list.The elements whose text to return is specified using
sourceandxpath. They have exactly the same semantics as with Get Elements keyword.The text of the matched elements is returned using the same logic as with Get Element Text. This includes optional whitespace normalization using the
normalize_whitespaceoption.
- element_text_should_be(source: Source, expected: str, xpath: str = '.', normalize_whitespace: bool = False, message: str | None = None)[source]
Verifies that the text of the specified element is
expected.The element whose text is verified is specified using
sourceandxpath. They have exactly the same semantics as with Get Element keyword.The text to verify is got from the specified element using the same logic as with Get Element Text. This includes optional whitespace normalization using the
normalize_whitespaceoption.The keyword passes if the text of the element is equal to the
expectedvalue, and otherwise it fails. The default error message can be overridden with themessageargument. Use Element Text Should Match to verify the text against a pattern instead of an exact value.
- element_text_should_match(source: Source, pattern: str, xpath: str = '.', normalize_whitespace: bool = False, message: str | None = None)[source]
Verifies that the text of the specified element matches
expected.This keyword works exactly like Element Text Should Be except that the expected value can be given as a pattern that the text of the element must match.
Pattern matching is similar as matching files in a shell with
*,?and[chars]acting as wildcards. See the Pattern matching section for more information.
- get_element_attribute(source: Source, name: str, xpath: str = '.', default: object = None) str | object[source]
Returns the named attribute of the specified element.
The element whose attribute to return is specified using
sourceandxpath. They have exactly the same semantics as with Get Element keyword.The value of the attribute
nameof the specified element is returned. If the element does not have such element, thedefaultvalue is returned instead.See also Get Element Attributes, Element Attribute Should Be, Element Attribute Should Match and Element Should Not Have Attribute.
- get_element_attributes(source: Source, xpath: str = '.') dict[str, str][source]
Returns all attributes of the specified element.
The element whose attributes to return is specified using
sourceandxpath. They have exactly the same semantics as with Get Element keyword.Attributes are returned as a Python dictionary. It is a copy of the original attributes so modifying it has no effect on the XML structure.
Use Get Element Attribute to get the value of a single attribute.
- element_attribute_should_be(source: Source, name: str, expected: str | None, xpath: str = '.', message: str | None = None)[source]
Verifies that the specified attribute is
expected.The element whose attribute is verified is specified using
sourceandxpath. They have exactly the same semantics as with Get Element keyword.The keyword passes if the attribute
nameof the element is equal to theexpectedvalue, and otherwise it fails. The default error message can be overridden with themessageargument.To test that the element does not have a certain attribute, Python
None(i.e. variable${NONE}) can be used as the expected value. A cleaner alternative is using Element Should Not Have Attribute.See also Element Attribute Should Match and Get Element Attribute.
- element_attribute_should_match(source: Source, name: str, pattern: str, xpath: str = '.', message: str | None = None)[source]
Verifies that the specified attribute matches
expected.This keyword works exactly like Element Attribute Should Be except that the expected value can be given as a pattern that the attribute of the element must match.
Pattern matching is similar as matching files in a shell with
*,?and[chars]acting as wildcards. See the Pattern matching section for more information.
- element_should_not_have_attribute(source: Source, name: str, xpath: str = '.', message: str | None = None)[source]
Verifies that the specified element does not have attribute
name.The element whose attribute is verified is specified using
sourceandxpath. They have exactly the same semantics as with Get Element keyword.The keyword fails if the specified element has attribute
name. The default error message can be overridden with themessageargument.See also Get Element Attribute, Get Element Attributes, Element Text Should Be and Element Text Should Match.
- elements_should_be_equal(source: Source, expected: Source, exclude_children: bool = False, normalize_whitespace: bool = False, sort_children: bool = False)[source]
Verifies that the given
sourceelement is equal toexpected.Both
sourceandexpectedcan be given as a path to an XML file, as a string containing XML, or as an already parsed XML element structure. See introduction for more information about parsing XML in general.The keyword passes if the
sourceelement andexpectedelement are equal. This includes testing the tag names, texts, and attributes of the elements. By default, also child elements are verified the same way, but this can be disabled by settingexclude_childrento a true value. Child elements are expected to be in the same order, but that can be changed by givingsort_childrena true value. Notice that elements are sorted solely based on tag names.All texts inside the given elements are verified, but possible text outside them is not. By default, texts must match exactly, but setting
normalize_whitespaceto a true value makes text verification independent on newlines, tabs, and the amount of spaces. For more details about handling text see Get Element Text keyword and discussion about elements’ text and tail attributes in the introduction.The last example may look a bit strange because the
<p>element only has textText with. The reason is that rest of the text inside<p>actually belongs to the child elements. This includes the.at the end that is the tail text of the<i>element.See also Elements Should Match.
sort_childrenis new in Robot Framework 7.0.
- elements_should_match(source: Source, expected: Source, exclude_children: bool = False, normalize_whitespace: bool = False, sort_children: bool = False)[source]
Verifies that the given
sourceelement matchesexpected.This keyword works exactly like Elements Should Be Equal except that texts and attribute values in the expected value can be given as patterns.
Pattern matching is similar as matching files in a shell with
*,?and[chars]acting as wildcards. See the Pattern matching section for more information.See Elements Should Be Equal for more examples.
- set_element_tag(source: Source, tag: str, xpath: str = '.') Element[source]
Sets the tag of the specified element.
The element whose tag to set is specified using
sourceandxpath. They have exactly the same semantics as with Get Element keyword. The resulting XML structure is returned, and if thesourceis an already parsed XML structure, it is also modified in place.Can only set the tag of a single element. Use Set Elements Tag to set the tag of multiple elements in one call.
- set_elements_tag(source: Source, tag: str, xpath: str = '.') Element[source]
Sets the tag of the specified elements.
Like Set Element Tag but sets the tag of all elements matching the given
xpath.
- set_element_text(source: Source, text: str | None = None, tail: str | None = None, xpath: str = '.') Element[source]
Sets text and/or tail text of the specified element.
The element whose text to set is specified using
sourceandxpath. They have exactly the same semantics as with Get Element keyword. The resulting XML structure is returned, and if thesourceis an already parsed XML structure, it is also modified in place.Element’s text and tail text are changed only if new
textand/ortailvalues are given. See Element attributes section for more information about text and tail in general.Can only set the text/tail of a single element. Use Set Elements Text to set the text/tail of multiple elements in one call.
- set_elements_text(source: Source, text: str | None = None, tail: str | None = None, xpath: str = '.') Element[source]
Sets text and/or tail text of the specified elements.
Like Set Element Text but sets the text or tail of all elements matching the given
xpath.
- set_element_attribute(source: Source, name: str, value: str, xpath: str = '.') Element[source]
Sets attribute
nameof the specified element tovalue.The element whose attribute to set is specified using
sourceandxpath. They have exactly the same semantics as with Get Element keyword. The resulting XML structure is returned, and if thesourceis an already parsed XML structure, it is also modified in place.It is possible to both set new attributes and to overwrite existing. Use Remove Element Attribute or Remove Element Attributes for removing them.
Can only set an attribute of a single element. Use Set Elements Attribute to set an attribute of multiple elements in one call.
- set_elements_attribute(source: Source, name: str, value: str, xpath: str = '.') Element[source]
Sets attribute
nameof the specified elements tovalue.Like Set Element Attribute but sets the attribute of all elements matching the given
xpath.
- remove_element_attribute(source: Source, name: str, xpath: str = '.') Element[source]
Removes attribute
namefrom the specified element.The element whose attribute to remove is specified using
sourceandxpath. They have exactly the same semantics as with Get Element keyword. The resulting XML structure is returned, and if thesourceis an already parsed XML structure, it is also modified in place.It is not a failure to remove a non-existing attribute. Use Remove Element Attributes to remove all attributes and Set Element Attribute to set them.
Can only remove an attribute from a single element. Use Remove Elements Attribute to remove an attribute of multiple elements in one call.
- remove_elements_attribute(source: Source, name: str, xpath: str = '.') Element[source]
Removes attribute
namefrom the specified elements.Like Remove Element Attribute but removes the attribute of all elements matching the given
xpath.
- remove_element_attributes(source: Source, xpath: str = '.') Element[source]
Removes all attributes from the specified element.
The element whose attributes to remove is specified using
sourceandxpath. They have exactly the same semantics as with Get Element keyword. The resulting XML structure is returned, and if thesourceis an already parsed XML structure, it is also modified in place.Use Remove Element Attribute to remove a single attribute and Set Element Attribute to set them.
Can only remove attributes from a single element. Use Remove Elements Attributes to remove all attributes of multiple elements in one call.
- remove_elements_attributes(source: Source, xpath: str = '.') Element[source]
Removes all attributes from the specified elements.
Like Remove Element Attributes but removes all attributes of all elements matching the given
xpath.
- add_element(source: Source, element: Source, index: int | None = None, xpath: str = '.') Element[source]
Adds a child element to the specified element.
The element to whom to add the new element is specified using
sourceandxpath. They have exactly the same semantics as with Get Element keyword. The resulting XML structure is returned, and if thesourceis an already parsed XML structure, it is also modified in place.The
elementto add can be specified as a path to an XML file or as a string containing XML, or it can be an already parsed XML element. The element is copied before adding so modifying either the original or the added element has no effect on the other . The element is added as the last child by default, but a custom index can be used to alter the position. Indices start from zero (0 = first position, 1 = second position, etc.), and negative numbers refer to positions at the end (-1 = second last position, -2 = third last, etc.).Use Remove Element or Remove Elements to remove elements.
- remove_element(source: Source, xpath: str = '', remove_tail: bool = False) Element[source]
Removes the element matching
xpathfrom thesourcestructure.The element to remove from the
sourceis specified withxpathusing the same semantics as with Get Element keyword. The resulting XML structure is returned, and if thesourceis an already parsed XML structure, it is also modified in place.The keyword fails if
xpathdoes not match exactly one element. Use Remove Elements to remove all matched elements.Element’s tail text is not removed by default, but that can be changed by giving
remove_taila true value. See the Element attributes section for more information abouttailin general.
- remove_elements(source: Source, xpath: str = '', remove_tail: bool = False) Element[source]
Removes all elements matching
xpathfrom thesourcestructure.The elements to remove from the
sourceare specified withxpathusing the same semantics as with Get Elements keyword. The resulting XML structure is returned, and if thesourceis an already parsed XML structure, it is also modified in place.It is not a failure if
xpathmatches no elements. Use Remove Element to remove exactly one element.Element’s tail text is not removed by default, but that can be changed by using
remove_tailargument similarly as with Remove Element.
- clear_element(source: Source, xpath: str = '.', clear_tail: bool = False) Element[source]
Clears the contents of the specified element.
The element to clear is specified using
sourceandxpath. They have exactly the same semantics as with Get Element keyword. The resulting XML structure is returned, and if thesourceis an already parsed XML structure, it is also modified in place.Clearing the element means removing its text, attributes, and children. Element’s tail text is not removed by default, but that can be changed by giving
clear_taila true value. See the Element attributes section for more information abouttailin general.Use Remove Element to remove the whole element.
- copy_element(source: Source, xpath: str = '.') Element[source]
Returns a copy of the specified element.
The element to copy is specified using
sourceandxpath. They have exactly the same semantics as with Get Element keyword.If the copy or the original element is modified afterward, the changes have no effect on the other.
- element_to_string(source: Source, xpath: str = '.', encoding: str | None = None) bytes | str[source]
Returns the string representation of the specified element.
The element to convert to a string is specified using
sourceandxpath. They have exactly the same semantics as with Get Element keyword.The string is returned as Unicode by default. If
encodingargument is given any value, the string is returned as bytes in the specified encoding. The resulting string never contains the XML declaration.See also Log Element and Save XML.
- log_element(source: Source, level: Literal['TRACE', 'DEBUG', 'INFO', 'CONSOLE', 'HTML', 'WARN', 'ERROR'] = 'INFO', xpath: str = '.') str[source]
Logs the string representation of the specified element.
The element specified with
sourceandxpathis first converted into a string using Element To String keyword internally. The resulting string is then logged using the givenlevel.The logged string is also returned.
- save_xml(source: Source, path: Path, encoding: str = 'UTF-8')[source]
Saves the given element to the specified file.
The element to save is specified with
sourceusing the same semantics as with Get Element keyword.The file where the element is saved is denoted with
pathand the encoding to use withencoding. The resulting file always contains the XML declaration.The resulting XML file may not be exactly the same as the original: - Comments and processing instructions are always stripped. - Possible doctype and namespace prefixes are only preserved when
using lxml.
Other small differences are possible depending on the ElementTree or lxml version.
Use Element To String if you just need a string representation of the element.
- evaluate_xpath(source: Source, expression: str, context: str = '.') object[source]
Evaluates the given xpath expression and returns results.
The element in which context the expression is executed is specified using
sourceandcontextarguments. They have exactly the same semantics assourceandxpatharguments have with Get Element keyword.The xpath expression to evaluate is given as
expressionargument. The result of the evaluation is returned as-is.This keyword works only if lxml mode is taken into use when importing the library.
- ROBOT_AUTO_KEYWORDS = True
- ROBOT_LIBRARY_CONVERTERS = {<class 'robot.libraries.XML.Element'>: <function <lambda>>, <class 'robot.libraries.XML.Source'>: <function <lambda>>}
- class robot.libraries.XML.NameSpaceStripper(etree, lxml_etree: bool = False)[source]
Bases:
object
- class robot.libraries.XML.ElementFinder(etree, modern: bool = True, lxml: bool = False)[source]
Bases:
object
- class robot.libraries.XML.Location(path: str, is_root: bool = True)[source]
Bases:
object- children: dict[str, int]
robot.libraries.dialogs_py module
- class robot.libraries.dialogs_py.TkDialog(message: str, value: str | Sequence[str] | None = None, **config)[source]
Bases:
ToplevelConstruct a toplevel widget with the parent MASTER.
Valid resource names: background, bd, bg, borderwidth, class, colormap, container, cursor, height, highlightbackground, highlightcolor, highlightthickness, menu, relief, screen, takefocus, use, visual, width.
- left_button = 'OK'
- right_button = 'Cancel'
- font = (None, 12)
- padding = 16
- background = None
- class robot.libraries.dialogs_py.MessageDialog(message: str, value: str | Sequence[str] | None = None, **config)[source]
Bases:
TkDialogConstruct a toplevel widget with the parent MASTER.
Valid resource names: background, bd, bg, borderwidth, class, colormap, container, cursor, height, highlightbackground, highlightcolor, highlightthickness, menu, relief, screen, takefocus, use, visual, width.
- right_button = None
- class robot.libraries.dialogs_py.InputDialog(message: str, default: str = '', hidden: bool = False)[source]
Bases:
TkDialogConstruct a toplevel widget with the parent MASTER.
Valid resource names: background, bd, bg, borderwidth, class, colormap, container, cursor, height, highlightbackground, highlightcolor, highlightthickness, menu, relief, screen, takefocus, use, visual, width.
- class robot.libraries.dialogs_py.SelectionDialog(message: str, values: Sequence[str], default: str | int | None = None)[source]
Bases:
TkDialogConstruct a toplevel widget with the parent MASTER.
Valid resource names: background, bd, bg, borderwidth, class, colormap, container, cursor, height, highlightbackground, highlightcolor, highlightthickness, menu, relief, screen, takefocus, use, visual, width.
- class robot.libraries.dialogs_py.MultipleSelectionDialog(message: str, value: str | Sequence[str] | None = None, **config)[source]
Bases:
TkDialogConstruct a toplevel widget with the parent MASTER.
Valid resource names: background, bd, bg, borderwidth, class, colormap, container, cursor, height, highlightbackground, highlightcolor, highlightthickness, menu, relief, screen, takefocus, use, visual, width.
- class robot.libraries.dialogs_py.PassFailDialog(message: str, value: str | Sequence[str] | None = None, **config)[source]
Bases:
TkDialogConstruct a toplevel widget with the parent MASTER.
Valid resource names: background, bd, bg, borderwidth, class, colormap, container, cursor, height, highlightbackground, highlightcolor, highlightthickness, menu, relief, screen, takefocus, use, visual, width.
- left_button = 'PASS'
- right_button = 'FAIL'