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 [eval](https://docs.python.org/library/functions.html#eval) function so that all Python built-ins like len() and int() 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.
```robotframework * Test Cases * Evaluating expressions
Should Be True len(“${result}”) > 3 Run Keyword If os.sep == “/” Non-Windows Keyword ${version} = Evaluate robot.__version__
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.
```robotframework * Test Cases * Using normal variables
Should Be True ${rc} < 10 Run Keyword If ‘${status}’ == ‘PASS’ Log Passed Run Keyword If ‘FAIL’ in ‘’’${output}’’’ Log Output contains FAIL
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.
```robotframework * Test Cases * Special variable syntax
Should Be True $rc < 10 Run Keyword If $status == ‘PASS’ Log Passed Run Keyword If ‘FAIL’ in $output Log Output contains FAIL Should Be True len($result) > 1 and $result[1] == ‘OK’ Should Be True $result is not None
- class robot.libraries.BuiltIn.BuiltIn[source]
Bases:
_Verify,_Converter,_Variables,_RunKeyword,_Control,_MiscAn always available standard library with often needed keywords.
BuiltIn is Robot Framework’s standard library that provides a set of often needed generic keywords. 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 msg and values arguments that can be used to override keyword specific default failure messages.
If msg is given and values gets a true value (default), the failure message is <msg>: <default-message>.
If msg is given and values gets a false value, the message is simply <msg>.
```robotframework * Test Cases * Default error message
[Documentation] Fails with “x != y”. Should Be Equal x y
- Custom error message
[Documentation] Fails with “Message: x != y”. Should Be Equal x y Message
- Custom error message without values
[Documentation] Fails with “Message”. Should Be Equal x y Message values=False
## 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.
```robotframework * Test Cases * HTML message
Fail HTML <b>Message</b>
# String and bytes normalization
Various validation keywords accept ignore_case, strip_spaces and collapse_spaces arguments that make it possible to normalize strings and bytes before comparison. They are all False by default, which means that no normalization is done, but they can be individually enabled:
If ignore_case is given a true value, comparison is case-insensitive.
If strip_spaces is given a value LEADING or TRAILING (case-insensitive), leading or trailing spaces, respectively, are removed before comparison. This includes all white space characters such as newlines and tabs.
If strip_spaces is given any other true value, both leading and trailing spaces are removed.
If collapse_spaces is 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 for bytes normalization and recursive normalization with collections are new in Robot Framework 7.4.
# String representations
Several keywords log values and report errors explicitly or implicitly. By default, these messages use human-readable string representation, which means that strings like Hello and numbers like 42 are shown 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 42 and integer 42. [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 (rn on Windows, n elsewhere) 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 like a != а are not very helpful.
Some Unicode characters can be represented using [different forms][NFC]. For example, ä can be represented either as a single code point u00e4 or using two combined code points u0061 and 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 formatter argument that can be used to configure the string representation. The supported values are str (default), repr, and ascii that work similarly as [Python built-in functions](https://docs.python.org/library/functions.html) with same names. More detailed semantics are explained below.
## str
Use the human-readable string representation. Equivalent to using [str()](https://docs.python.org/3/library/functions.html#func-str) in Python. This is the default.
## repr
Use the machine-readable string representation. Similar to using [repr()](https://docs.python.org/3/library/functions.html#repr) in Python, which means that strings like Hello are logged like ‘Hello’, newlines and non-printable characters are escaped like n and 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()](https://docs.python.org/3/library/functions.html#ascii) in Python. Similar to using repr explained above, but with the following differences:
Non-ASCII characters are escaped like xe4 instead 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 [eval](https://docs.python.org/library/functions.html#eval) function so that all Python built-ins like len() and int() 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.
```robotframework * Test Cases * Evaluating expressions
Should Be True len(‘${result}’) > 3 Run Keyword If os.sep == ‘/’ Non-Windows Keyword ${version} = Evaluate robot.__version__
[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.submod or 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.
```robotframework * Test Cases * Normal variables
Should Be True ${rc} < 10 Run Keyword If ‘${status}’ == ‘PASS’ Log Passed Run Keyword If ‘FAIL’ in ‘’’${output}’’’ Log Output contains FAIL
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.
```robotframework * Test Cases * Special variable syntax
Should Be True $rc < 10 Run Keyword If $status == ‘PASS’ Log Passed Run Keyword If ‘FAIL’ in $output Log Output contains FAIL Should Be True len($result) > 1 and $result[1] == ‘OK’ Should Be True $result is not None
Using the $variable syntax 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 $variable or ${variable}. For example, these are typically equivalent and create new suite level variable ${name} with value value:
```robotframework * Test Cases * Normal variable syntax
Set Suite Variable ${name} value
- Escaped by removing curly braces
Set Suite Variable $name value
- Escaped with backslash
Set Suite Variable ${name} value
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, the earlier examples would have created 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].
Notice that the [VAR syntax] introduced in Robot Framework 7.0 can be used to create local variables as well as variables in different scopes. It thus unifies creating variables, and it also avoids all the problems discussed above. It is recommended to use that syntax instead of the Set Global/Suite/Test/Local Variable keywords whenever possible.
# Pattern matching
Many keywords accept arguments as either glob or regular expression patterns.
## Glob patterns
Some keywords, for example [Should Match], support so called [glob patterns](https://en.wikipedia.org/wiki/Glob_(programming) “Wikipedia”) that support the following wildcard characters and character sequences.
Unlike with glob patterns normally, path separator characters / and ` and the newline character `n are matched by the above wildcards.
## Regular expressions
Some keywords, for example [Should Match Regexp], support [regular expressions](https://en.wikipedia.org/wiki/Regular_expression “Wikipedia”) that are more powerful but also more complicated that glob patterns. The regular expression support is implemented using Python’s [re](https://docs.python.org/library/re.html) 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 [unified diff format](https://en.wikipedia.org/wiki/Diff_utility#Unified_format “Wikipedia”) if both strings have more than two lines.
```robotframework * Test Cases * Multiline diff
VAR ${first} … Not in second … Same … Differs … Same … separator=n VAR ${second} … Same … Differs2 … Same … separator=n Should Be Equal ${first} ${second}
Results in the following error message:
` Multiline strings are different: --- first +++ second @@ -1,4 +1,3 @@ -Not in second Same -Differs +Differs2 Same `[DateTime]: https://robotframework.org/robotframework/latest/libraries/DateTime.html [search path]: https://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#module-search-path [VAR syntax]: https://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#var-syntax [IF/ELSE syntax]: https://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#if-else-syntax [TRY/EXCEPT syntax]: https://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#try-except-syntax [BREAK statement]: https://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#loop-control-using-break-and-continue [CONTINUE statement]: https://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#loop-control-using-break-and-continue [RETURN statement]: https://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#using-return-statement [NFC]: https://en.wikipedia.org/wiki/Unicode_equivalence
- 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>>}
- ROBOT_LIBRARY_DOC_FORMAT = 'MARKDOWN'
- ROBOT_LIBRARY_SCOPE = 'GLOBAL'
- ROBOT_LIBRARY_VERSION = '(.*)'
- 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.
Args:
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_process to 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.
Examples:
```python from robot.libraries.BuiltIn import BuiltIn, register_run_keyword
register_run_keyword(__name__, ‘My Run Keyword’)
robot.libraries.Collections module
- class robot.libraries.Collections.Collections[source]
Bases:
_List,_DictionaryA library providing keywords for handling lists and dictionaries.
Collections is 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 list objects. 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 dict objects. 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_case argument. Case-insensitivity can be enabled by using ignore_case=True and it works recursively.
With dictionaries, it is also possible to use special values KEYS and VALUES to normalize only keys or values, respectively. These options themselves are case-insensitive and also singular forms KEY and VALUE are supported.
If a dictionary contains keys that normalize to the same value, e.g. {‘a’: 1, ‘A’: 2}, normalizing keys causes an error.
```robotframework * Test Cases * Ignore case
VAR @{list1} abc DEF VAR @{list2} ABC def Lists Should Be Equal ${list1} ${list2} ignore_case=True
- Ignore key/value case
VAR &{dict1} a=x b=y c=z VAR &{dict2} A=x B=y C=z VAR &{dict3} a=X b=Y c=Z Dictionaries Should Be Equal ${dict1} ${dict2} ignore_case=KEYS Dictionaries Should Be Equal ${dict1} ${dict3} ignore_case=VALUES Dictionaries Should Be Equal ${dict1} ${dict3} ignore_case=True
Notice that some keywords accept also an older case_insensitive argument in addition to ignore_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.
- <!— Markdown comment to hide library import that eases testing examples.
Can be removed if a separate example with the import is added.
`robotframework *** Settings *** Library Collections `—>[BuiltIn]: https://robotframework.org/robotframework/latest/libraries/BuiltIn.html [String]: https://robotframework.org/robotframework/latest/libraries/String.html [#5762]: https://github.com/robotframework/robotframework/issues/5762
- ROBOT_LIBRARY_SCOPE = 'GLOBAL'
- ROBOT_LIBRARY_VERSION = '(.*)'
- ROBOT_LIBRARY_DOC_FORMAT = 'Markdown'
- 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 pattern is not found in list.
- Args:
list: The list to search. pattern: The pattern to match. msg: Optional custom error message. case_insensitive: Deprecated. Use ignore_case instead. whitespace_insensitive: Deprecated. Use ignore_whitespace instead. ignore_case: Whether to ignore case when matching. ignore_whitespace: Whether to ignore whitespace when matching.
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 prepend glob= to your pattern to explicitly use this pattern matching behavior.
If you prepend regexp= to your pattern, the pattern is considered to be a regular expression that uses Python’s [regular expression syntax](http://docs.python.org/library/re.html). 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 like regexp=\d{6}. See Should Match Regexp from the [BuiltIn] library for more details.
Matching is case-sensitive by default, but that can be changed by giving the ignore_case argument a true value. This argument is new in Robot Framework 7.0, but with earlier versions it is possible to use case_insensitive for the same purpose.
It is possible to ignore all whitespace by giving the ignore_whitespace argument a true value. This argument is new in Robot Framework 7.0 as well, and with earlier versions it is possible to use whitespace_insensitive.
Notice that both case_insensitive and whitespace_insensitive are considered deprecated. They will eventually be removed.
Non-string values in lists are ignored when matching patterns.
```robotframework * Variables * @{MATCHED} foo bar abc 123
* Test Cases * Match using glob pattern
Should Contain Match ${MATCHED} f* Should Contain Match ${MATCHED} b?r Should Contain Match ${MATCHED} abc [1-9][1-9][1-9]
- Match using regexp
Should Contain Match ${MATCHED} regexp=f.* Should Contain Match ${MATCHED} regexp=b.r Should Contain Match ${MATCHED} regexp=abc \d\d\d
- Normalization
Should Contain Match ${MATCHED} ABC * ignore_case=True Should Contain Match ${MATCHED} abc??? ignore_whitespace=True
> [!IMPORTANT] > When using glob patterns, the pattern must match items fully, but > when using regular expressions, it is enough if the pattern matches > the beginning. This will be changed in the future, though, and a > full match will be required regardless the pattern type. > > Starting from Robot Framework 7.5, there is a warning if the > forthcoming change affects the results of this keyword. To avoid > the warning, add .* at the end of the pattern to preserve the > current behavior, or add $ to require a full match already now.
- 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 pattern is found in list.
- Args:
list: The list to search. pattern: The pattern that should not match. msg: Optional custom error message. case_insensitive: Deprecated. Use ignore_case instead. whitespace_insensitive: Deprecated. Use ignore_whitespace instead. ignore_case: Whether to ignore case when matching. ignore_whitespace: Whether to ignore whitespace when matching.
Exact opposite of [Should Contain Match] keyword. See that keyword for information about arguments and usage in general.
> [!IMPORTANT] > When using glob patterns, the pattern must match items fully, but > when using regular expressions, it is enough if the pattern matches > the beginning. This will be changed in the future, though, and a > full match will be required regardless the pattern type. > > Starting from Robot Framework 7.5, there is a warning if the > forthcoming change affects the results of this keyword. To avoid > the warning, add .* at the end of the pattern to preserve the > current behavior, or add $ to require a full match already now.
- 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 pattern in list.
- Args:
list: The list to search. pattern: The pattern to match. case_insensitive: Deprecated. Use ignore_case instead. whitespace_insensitive: Deprecated. Use ignore_whitespace instead. ignore_case: Whether to ignore case when matching. ignore_whitespace: Whether to ignore whitespace when matching.
- Returns:
A list containing matching items.
For more information on pattern, case_insensitive/ignore_case, and whitespace_insensitive/ignore_whitespace, see [Should Contain Match].
```robotframework * Variables * @{MATCHED} foo bar abc 123
* Test Cases * Get matches
${matches} = Get Matches ${MATCHED} A ignore_case=True Lists Should Be Equal ${matches} [“bar”, “abc 123”]
- Get no matches
${matches} = Get Matches ${MATCHED} no match Should Be Empty ${matches}
> [!IMPORTANT] > When using glob patterns, the pattern must match items fully, but > when using regular expressions, it is enough if the pattern matches > the beginning. This will be changed in the future, though, and a > full match will be required regardless the pattern type. > > Starting from Robot Framework 7.5, there is a warning if the > forthcoming change affects the results of this keyword. To avoid > the warning, add .* at the end of the pattern to preserve the > current behavior, or add $ to require a full match already now.
- 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 pattern in list.
- Args:
list: The list to search matches from. pattern: The pattern to match. case_insensitive: Deprecated. Use ignore_case instead. whitespace_insensitive: Deprecated. Use ignore_whitespace instead. ignore_case: Whether to ignore case when matching. ignore_whitespace: Whether to ignore whitespace when matching.
- Returns:
The number of matches.
For more information on pattern, case_insensitive/ignore_case, and whitespace_insensitive/ignore_whitespace, see [Should Contain Match].
```robotframework * Variables * @{MATCHED} foo bar abc 123
* Test Cases * Get match count
${matches} = Get Match Count ${MATCHED} A ignore_case=True Should Be Equal ${matches} 2 type=int
- Get zero match count
${matches} = Get Match Count ${MATCHED} no match Should Be Equal ${matches} 0 type=int
> [!IMPORTANT] > When using glob patterns, the pattern must match items fully, but > when using regular expressions, it is enough if the pattern matches > the beginning. This will be changed in the future, though, and a > full match will be required regardless the pattern type. > > Starting from Robot Framework 7.5, there is a warning if the > forthcoming change affects the results of this keyword. To avoid > the warning, add .* at the end of the pattern to preserve the > current behavior, or add $ to require a full match already now.
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 any time zone information. For example, 2014-06-11 10:07:42.
time: A time interval. For example, 1 hour 20 minutes or 01:20:00.
This terminology differs from what Python’s standard [datetime module] uses. Basically its [datetime] and [timedelta] objects match date and time as defined by this library.
# Date formats
Dates can be given to and received from keywords in different formats:
[Timestamp]
[Custom timestamp]
[TODAY and NOW]
[datetime object]
[date object]
[Epoch time]
Input format is in most cases determined automatically. An exception is that when using a [custom timestamp], the format must be specified using the date_format argument. The default result format is [timestamp], but it can be overridden using the result_format argument like result_format=datetime.
## Timestamp
If a date is given as a string, it is always considered to be a timestamp. If a custom format is not given using the date_format argument, the timestamp is expected to be in [ISO 8601] like format YYYY-MM-DD hh:mm:ss.mmmmmm, 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 missing time components are considered to be zeros.
Dates can also be returned in the YYYY-MM-DD hh:mm:ss.mmm format by using the timestamp value with the result_format argument. This is also the default format that keywords returning dates use. Milliseconds can be excluded using exclude_millis as explained in the [Millisecond handling] section.
```robotframework * Test Cases * Timestamps
${date1} = Convert Date 2014-06-11 10:07:42.000 ${date2} = Convert Date 20140611 100742 result_format=timestamp Should Be Equal ${date1} ${date2} ${date} = Convert Date 20140612 12:57 exclude_millis=True Should Be Equal ${date} 2014-06-12 12:57:00
## Custom timestamp
It is possible to use custom timestamps in both input and output. This format uses the same [format codes] as the [datetime module]. 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 the 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.
```robotframework * Test Cases * Custom timestamps
${date} = Convert Date 28.05.2014 12:05 date_format=%d.%m.%Y %H:%M Should Be Equal ${date} 2014-05-28 12:05:00.000 ${date} = Convert Date ${date} result_format=%d.%m.%Y Should Be Equal ${date} 28.05.2014
## TODAY and NOW
Strings TODAY and NOW (case-insensitive) can be used to get the current date automatically without using the [Get Current Date] keyword.
```robotframework * Variables * ${ROBOCON 2027} 2027-03-08
* Test Cases * Days to RoboCon 2027
${delta} = Subtract Date From Date ${ROBOCON 2027} TODAY result_format=timedelta Log It is ${delta.days} days to RoboCon 2027!
Support for TODAY and NOW is new in Robot Framework 7.5.
## datetime object
Python’s standard [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.
```robotframework * Test Cases * Datetine
${datetime} = Convert Date 2014-06-11 10:07:42.123 datetime Should Be Equal ${datetime.year} 2014 type=int Should Be Equal ${datetime.month} 6 type=int Should Be Equal ${datetime.day} 11 type=int Should Be Equal ${datetime.hour} 10 type=int Should Be Equal ${datetime.minute} 7 type=int Should Be Equal ${datetime.second} 42 type=int Should Be Equal ${datetime.microsecond} 123000 type=int
## date object
Python’s standard [date] objects are automatically recognized in input the same way as [datetime] objects are. In output, it is possible to get [date] objects by using result_format=date. Possible non-zero time components are simply discarded.
Support for [date] objects in input and output is new Robot Framework 7.0 and Robot Framework 7.5, respectively.
## Epoch time
Epoch time is the time in seconds since the [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 the epoch value with the 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.
```robotframework * Test Cases * Epoch
${date} = Convert Date ${1000000000} Should Be Equal ${date} 2001-09-09 04:46:40.000 ${date} = Convert Date 2014-06-12 13:27:59.279 epoch Should Be Equal ${date} ${1402568879.279}
## 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 customized using the 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.
```robotframework * Test Cases * Number
${time} = Convert Time 3.14 Should Be Equal ${time} 3.14 type=float ${time} = Convert Time ${time} result_format=number Should Be Equal ${time} 3.14 type=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, d
hours, hour, h
minutes, minute, mins, min, m
seconds, second, secs, sec, s
milliseconds, millisecond, millis, ms
microseconds, 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 like week and day, and adds s at the end when needed. The compact format uses shorter specifiers like w and d, and even drops the space between the number and the specifier.
```robotframework * Test Cases * Time string
${time} = Convert Time 1 minute 42 seconds Should Be Equal ${time} ${102} ${time} = Convert Time 4200 verbose Should Be Equal ${time} 1 hour 10 minutes ${time} = Convert Time - 1.5 hours compact Should Be Equal ${time} - 1h 30min
## 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, the result_format argument must be given the 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 the [Millisecond handling] section.
```robotframework * Test Cases * Timer string
${time} = Convert Time 01:42 Should Be Equal ${time} 102 type=float ${time} = Convert Time 01:10:00.123 Should Be Equal ${time} 4200.123 type=float ${time} = Convert Time 102 timer Should Be Equal ${time} 00:01:42.000 ${time} = Convert Time -101.567 timer exclude_millis=True Should Be Equal ${time} -00:01:42
## Python timedelta
Python’s standard [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 the timedelta value to the result_format argument.
```robotframework * Test Cases * Timedelta
${timedelta} = Convert Time 01:10:02.123 timedelta Should Be Equal ${timedelta.total_seconds()} ${4202.123}
# 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. 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.
```robotframework * Test Cases * Milliseconds
${date} = Convert Date 2014-06-11 10:07:42 Should Be Equal ${date} 2014-06-11 10:07:42.000 ${date} = Convert Date 2014-06-11 10:07:42.500 exclude_millis=True Should Be Equal ${date} 2014-06-11 10:07:43 ${dt} = Convert Date 2014-06-11 10:07:42.500 datetime exclude_millis=True Should Be Equal ${dt.second} ${43} Should Be Equal ${dt.microsecond} ${0} ${time} = Convert Time 102 timer exclude_millis=False Should Be Equal ${time} 00:01:42.000 ${time} = Convert Time 102.567 timer exclude_millis=True Should Be Equal ${time} 00:01:43
# 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:
```python from robot.libraries.DateTime import convert_time
- def example_keyword(timeout):
seconds = convert_time(timeout) …
Additionally, helper classes Date and Time can be used directly:
```python from robot.libraries.DateTime import Date, Time
- def example_keyword(day, interval):
date = Date(day).convert(‘datetime’) interval = Time(interval).convert(‘number’) …
In common cases it is more convenient to just use [datetime], [date] and [timedelta] as type hints and let Robot Framework handle argument conversion automatically:
```python from datetime import datetime, timedelta
- def example_keyword(day: datetime, interval: timedelta):
…
[ISO 8601]: http://en.wikipedia.org/wiki/ISO_8601 [UNIX epoch]: http://en.wikipedia.org/wiki/Unix_time [datetime module]: http://docs.python.org/library/datetime.html [datetime]: http://docs.python.org/library/datetime.html#datetime-objects [date]: https://docs.python.org/3/library/datetime.html#date-objects [timedelta]: http://docs.python.org/library/datetime.html#timedelta-objects [format codes]: https://docs.python.org/3/library/datetime.html#format-codes
- 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 | date | float | str[source]
Adds time to date and returns the resulting date.
- Args:
date: Date to add time to in one of the supported [date formats]. time: Time that is added in one of the supported [time formats]. result_format: Format of the returned date. exclude_millis: When set to a true value, rounds and drops
milliseconds as explained in the [Millisecond handling] section.
date_format: Possible [custom timestamp] format of date.
- Returns:
The resulting date in the requested format.
```robotframework * Test Cases * Add time to date
${date} = Add Time To Date 2014-05-28 12:05:03.111 7 days Should Be Equal ${date} 2014-06-04 12:05:03.111 ${date} = Add Time To Date 2014-05-28 12:05:03.111 01:02:03:004 Should Be Equal ${date} 2014-05-28 13:07:06.115
- 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.
- Args:
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 drops
milliseconds as explained in the [Millisecond handling] section.
- Returns:
The sum of the given times in the requested format.
```robotframework * Test Cases * Add time to time
${time} = Add Time To Time 1 minute 42 Should Be Equal ${time} ${102} ${time} = Add Time To Time 3h 5min 01:02:03 timer exclude_millis=True Should Be Equal ${time} 04:07:03
- 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 | date | float | str[source]
Converts between supported [date formats].
- Args:
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 drops
milliseconds as explained in the [Millisecond handling] section.
date_format: Specifies possible [custom timestamp] format.
- Returns:
The converted date in the requested format.
```robotframework * Test Cases * Convert date
${date} = Convert Date 20140528 12:05:03.111 Should Be Equal ${date} 2014-05-28 12:05:03.111 ${date} = Convert Date ${date} epoch Should Be Equal ${date} ${1401267903.111} ${date} = Convert Date 5.28.2014 12:05 exclude_millis=yes date_format=%m.%d.%Y %H:%M Should Be Equal ${date} 2014-05-28 12:05:00
- 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].
- Args:
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 drops
milliseconds as explained in the [Millisecond handling] section.
- Returns:
The converted time in the requested format.
```robotframework * Test Cases * Convert time
${time} = Convert Time 10 seconds Should Be Equal ${time} ${10} ${time} = Convert Time 1:00:01 verbose Should Be Equal ${time} 1 hour 1 second ${time} = Convert Time ${3661.5} timer exclude_milles=yes Should Be Equal ${time} 01:01:02
- 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 | date | float | str[source]
Returns current local or UTC time with an optional increment.
- Args:
- time_zone: Get the current time on this time zone. Currently only
local (default) and UTC are supported. This argument has no effect if date is returned as an [Epoch time].
- increment: Optional time increment to add to the returned date in
one 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 drops
milliseconds as explained in the [Millisecond handling] section.
- Returns:
The current date in the requested format.
```robotframework * Test Cases * Get current date
${date} = Get Current Date Should Be Equal ${date} 2014-06-12 20:00:58.946 ${date} = Get Current Date UTC Should Be Equal ${date} 2014-06-12 17:00:58.946 ${date} = Get Current Date increment=02:30:00 Should Be Equal ${date} 2014-06-12 22:30:58.946 ${date} = Get Current Date UTC - 5 hours Should Be Equal ${date} 2014-06-12 12:00:58.946 ${date} = Get Current Date result_format=datetime Should Be Equal ${date.year} ${2014} Should Be Equal ${date.month} ${6}
- 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.
- Args:
- date1: Date to subtract another date from in one of the
supported [date formats].
- date2: Date that is subtracted in one of the supported
[date formats].
result_format: Format of the returned time (see [Time formats]). exclude_millis: When set to a true value, rounds and drops
milliseconds as explained in the [Millisecond handling] section.
date1_format: Possible [custom timestamp] format of date1. date2_format: Possible [custom timestamp] format of date2.
- Returns:
The time between the given dates in the requested format.
```robotframework * Test Cases * Subtract date from date
${time} = Subtract Date From Date 2014-05-28 12:05:52 2014-05-28 12:05:10 Should Be Equal ${time} ${42} ${time} = Subtract Date From Date 2014-05-28 12:05:52 2014-05-27 12:05:10 verbose Should Be Equal ${time} 1 day 42 seconds
- 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 | date | float | str[source]
Subtracts time from date and returns the resulting date.
- Args:
date: Date to subtract time from in one of the supported [date formats]. time: Time that is subtracted in one of the supported [time formats]. result_format: Format of the returned date. exclude_millis: When set to any true value, rounds and drops
milliseconds as explained in the [Millisecond handling] section.
date_format: Possible [custom timestamp] format of date.
- Returns:
The resulting date in the requested format.
```robotframework * Test Cases * Subtract time from date
${date} = Subtract Time From Date 2014-06-04 12:05:03.111 7 days Should Be Equal ${date} 2014-05-28 12:05:03.111 ${date} = Subtract Time From Date 2014-05-28 13:07:06.115 01:02:03:004 Should Be Equal ${date} 2014-05-28 12:05:03.111
- 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.
- Args:
- time1: Time to subtract another time from in one of
the 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 drops
milliseconds as explained in the [Millisecond handling] section.
- Returns:
The difference between the given times in the requested format.
```robotframework * Test Cases * Subtract time from time
${time} = Subtract Time From Time 00:02:30 100 Should Be Equal ${time} ${50} ${time} = Subtract Time From Time ${time} 1 minute compact Should Be Equal ${time} - 10s
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 PASS or FAIL button. In the latter case execution fails and an additional dialog is opened for defining the error message.
- Args:
message: The instruction shown in the initial dialog. default_error: 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 Cancel fails the keyword.
- Args:
message: The instruction shown in the dialog. *values: The options given to the user. default: Optional default value. Can either be one of the specified
values or the index of the value starting from 1. For example, default=user1 and default=1 in the examples below have the exact same effect.
- Returns:
The value selected by the user.
- Raises:
RuntimeError: If the user presses Cancel.
```robotframework * Test Cases * Select User
${user} = Get Selection From User Select user user1 user2 admin ${user} = Get Selection From User Select user user1 user2 admin default=user1 ${user} = Get Selection From User Select user user1 user2 admin default=1
default is 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 Cancel fails the keyword.
- Args:
message: The instruction shown in the dialog. *values: The options given to the user.
- Returns:
The values selected by the user as a list. Empty if nothing was selected.
- Raises:
RuntimeError: If the user presses Cancel.
```robotframework * Test Cases * Select Users
${users} = Get Selections From User Select users user1 user2 admin
- 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 Cancel fails the keyword.
- Args:
message: The instruction shown in the dialog. default_value: The possible default value shown in the input field. hidden: If given a true value, the value typed by the user is hidden.
- Returns:
Value typed by the user, or the default value.
- Raises:
RuntimeError: If the user presses Cancel.
```robotframework * Test Cases * Get Credentials
${username} = Get Value From User Input username default ${password} = Get Value From User Input password hidden=yes
robot.libraries.Easter module
robot.libraries.OperatingSystem module
- class robot.libraries.OperatingSystem.OperatingSystem[source]
Bases:
objectA library providing keywords for operating system related tasks.
OperatingSystem is 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, for example, 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]), manipulate environment variables (e.g. [Set Environment Variable]) and execute commands (e.g. [Run]).
%TOC%
# Path separators
Because Robot Framework uses the backslash (`) as an escape character in its data, using a literal backslash requires duplicating it like in `c:\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.txt are 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 patterns or regular expressions.
## Glob patterns
Some keywords, for example [List Directory], support [glob patterns](https://en.wikipedia.org/wiki/Glob_(programming) “Wikipedia”) that support the following wildcard characters and character sequences.
Unless otherwise noted, matching is case-insensitive on case-insensitive operating systems such as Windows.
## Regular expressions
Some keywords, for example [Grep File], support [regular expressions](https//en.wikipedia.org/wiki/Regular_expression “Wikipedia”) that are more powerful but also more complicated than glob patterns. The regular expression support is implemented using Python’s [re](https://docs.python.org/library/re.html) 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 ~username are expanded to the current or specified user’s home directory, respectively. The resulting path is operating system dependent, but typically e.g. ~/file.txt is expanded to C:Users<user>file.txt on Windows and /home/<user>/file.txt on Unixes.
# pathlib.Path support
Starting from Robot Framework 6.0, arguments representing paths can be given as [pathlib.Path](https://docs.python.org/3/library/pathlib.html) instances in addition to strings.
For backwards compatibility reasons, all keywords returning paths return them as strings.
# Example
```robotframework * Settings * Library OperatingSystem
* Variables * ${PATH} ${CURDIR}/example.txt
- * Test Cases *
Create File ${PATH} Some text File Should Exist ${PATH} Copy File ${PATH} ~/file.txt
[Process]: https://robotframework.org/robotframework/latest/libraries/Process.html “Process library” [BuiltIn]: https://robotframework.org/robotframework/latest/libraries/BuiltIn.html “BuiltIn library”
- ROBOT_LIBRARY_DOC_FORMAT = 'Markdown'
- ROBOT_LIBRARY_SCOPE = 'GLOBAL'
- ROBOT_LIBRARY_VERSION = '(.*)'
- run(command: str) str[source]
This keyword is considered deprecated. Use the [Process] library instead.
Runs the given command in the system and returns the output.
- Args:
command: Command to execute.
- Returns:
The command output with a possible trailing newline removed.
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 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.
```robotframework * Test Cases * Run
${output} = Run ls -lhF /tmp Log ${output} ${result} = Run ${CURDIR}${/}script.py arg1 arg2 Should Not Contain ${result} FAIL ${stdout} = Run /opt/script.sh 2>/tmp/stderr.txt Should Be Equal ${stdout} TEST PASSED File Should Be Empty /tmp/stderr.txt
- run_and_return_rc(command: str) int[source]
This keyword is considered deprecated. Use the [Process] library instead.
Runs the given command in the system and returns the return code (RC).
- Args:
command: Command to execute.
- Returns:
The command return code as an integer in range 0-255.
The return code is returned as an integer in range from 0 to 255 as returned by the executed command. On some operating systems (notable Windows) the original return code can be something else, but this keyword always maps them to the 0-255 range.
```robotframework * Test Cases * Run And Return RC
${rc} = Run and Return RC ${CURDIR}${/}script.py arg Should Be Equal ${rc} 0 type=int ${rc} = Run and Return RC /path/to/example.rb arg1 arg2 Should Be True 0 < ${rc} < 42
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 [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].
- Args:
command: Command to execute.
- Returns:
A tuple containing the command return code and output.
```robotframework * Test Cases * Run And Return RC And Output
${rc} ${output} = Run and Return RC and Output ${CURDIR}${/}mytool Should Be Equal ${rc} 0 type=int Should Not Contain ${output} FAIL ${rc} ${stdout} = Run and Return RC and Output /opt/script.sh 2>/tmp/stderr.txt Should Be True ${rc} > 42 Should Be Equal ${stdout} TEST PASSED File Should Be Empty /tmp/stderr.txt
- get_file(path: str, encoding: str = 'UTF-8', encoding_errors: str = 'strict') str[source]
Returns the contents of a specified file.
- Args:
path: Path to the file to read. encoding: File encoding to use. encoding_errors: Error handler to use if decoding fails.
- Returns:
The file contents as text with platform-independent line breaks.
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].
encoding defines the encoding of the file. The default value is UTF-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.
The encoding_errors argument supports all Python’s standard [error handlers](https://docs.python.org/3/library/codecs.html#error-handlers), 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.
- Args:
path: Path to the file to read.
- Returns:
The file contents as bytes.
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.
- Args:
path: Path to the file to read. pattern: Glob or regular expression pattern to match. encoding: File encoding to use. encoding_errors: Error handler to use if decoding fails. regexp: When true, the pattern is considered to be a regular
expression instead of a glob pattern.
- Returns:
Matching lines joined with newlines, without a trailing newline.
This keyword reads a file from the file system using the defined path, encoding and encoding_errors similarly as [Get File]. A difference is that only the lines that match the given pattern are 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 pattern anywhere 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 regexp argument 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 data like \.
For more information about glob and regular expression syntax, see the [Pattern matching] section. With this keyword matching is always case-sensitive.
```robotframework * Test Cases * Grep File
${errors} = Grep File /var/log/myapp.log ERROR ${ret} = Grep File ${CURDIR}/file.txt [Ww]ildc??d ex*ple ${ret} = Grep File ${CURDIR}/file.txt [Ww]ildc\w+d ex.*ple regexp=True
Special encoding values SYSTEM and CONSOLE that [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.
- Args:
path: Path to the file to read and log. encoding: File encoding to use. encoding_errors: Error handler to use if decoding fails.
- Returns:
The logged file contents.
The file is logged with the INFO level. If you want something else, just use [Get File] and the [BuiltIn] keyword Log with the desired level.
See [Get File] for more information about encoding and encoding_errors arguments.
- should_exist(path: str, msg: str | None = None)[source]
Fails unless the given path (file or directory) exists.
- Args:
path: Exact path or glob pattern to check. msg: Optional custom error message.
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.
- should_not_exist(path: str, msg: str | None = None)[source]
Fails if the given path (file or directory) exists.
- Args:
path: Exact path or glob pattern to check. msg: Optional custom error message.
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.
- file_should_exist(path: str, msg: str | None = None)[source]
Fails unless the given path points to an existing file.
- Args:
path: Exact file path or glob pattern to check. msg: Optional custom error message.
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.
- file_should_not_exist(path: str, msg: str | None = None)[source]
Fails if the given path points to an existing file.
- Args:
path: Exact file path or glob pattern to check. msg: Optional custom error message.
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.
- directory_should_exist(path: str, msg: str | None = None)[source]
Fails unless the given path points to an existing directory.
- Args:
path: Exact directory path or glob pattern to check. msg: Optional custom error message.
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.
- directory_should_not_exist(path: str, msg: str | None = None)[source]
Fails if the given path points to an existing file.
- Args:
path: Exact directory path or glob pattern to check. msg: Optional custom error message.
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.
- wait_until_removed(path: str, timeout: timedelta | None = datetime.timedelta(seconds=60))[source]
Waits until the given file or directory is removed.
- Args:
path: Exact path or glob pattern to wait for. timeout: Maximum time to wait, or a negative value or None for no limit.
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 timeout argument. Using a negative value or None disables the timeout.
```robotframework * Test Cases * Wait Until Removed
Wait Until Removed ${path} Wait Until Removed ${path} 10 seconds Wait Until Removed ${path} timeout=None
Disabling timeout using None is 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.
- Args:
path: Exact path or glob pattern to wait for. timeout: Maximum time to wait, or a negative value or None for no limit.
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 timeout argument. Using a negative value or None disables the timeout.
```robotframework * Test Cases * Wait Until Created
Wait Until Created ${path} Wait Until Created ${path} 10 seconds Wait Until Created ${path} timeout=None
Disabling timeout using None is new in Robot Framework 7.4.
- directory_should_be_empty(path: str, msg: str | None = None)[source]
Fails unless the specified directory is empty.
- Args:
path: Path to the directory to check. msg: Optional custom error message.
- directory_should_not_be_empty(path: str, msg: str | None = None)[source]
Fails if the specified directory is empty.
- Args:
path: Path to the directory to check. msg: Optional custom error message.
- file_should_be_empty(path: str, msg: str | None = None)[source]
Fails unless the specified file is empty.
- Args:
path: Path to the file to check. msg: Optional custom error message.
- file_should_not_be_empty(path: str, msg: str | None = None)[source]
Fails if the specified file is empty.
- Args:
path: Path to the file to check. msg: Optional custom error message.
- create_file(path: str, content: str | Secret = '', encoding: str = 'UTF-8')[source]
Creates a file with the given content and encoding.
- Args:
path: Path to the file to create. content: Content to write. [Secret] values are not logged. encoding: Encoding to use when writing the file.
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 (rn).
See [Get File] for more information about possible encoding values, including special values SYSTEM and CONSOLE.
```robotframework * Test Cases * Create File
Create File ${dir}/example.txt Hello, world! Create File ${path} Hyvä esimerkki encoding=Latin-1 Create File /tmp/foo.txt 3nlinesnheren SYSTEM
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.
- Args:
path: Path to the file to create. content: Binary content to write.
If content is given as a Unicode string, it is first converted to bytes character by character. Bytes that cannot be represented as visible characters can be created using escape sequences like x00. 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.
If the directory for the file does not exist, it is created, along with missing intermediate directories.
```robotframework * Test Cases * Create Binary File
Create Binary File ${dir}/example.png ${image} Create Binary File ${path} x00RFx01
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.
- Args:
path: Path to the file to append to. content: Content to append. [Secret] values are not logged. encoding: Encoding to use when writing the 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.
- Args:
path: Exact file path or glob pattern identifying files to remove.
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.
- remove_files(*paths: str)[source]
Uses [Remove File] to remove multiple files one-by-one.
- Args:
*paths: Exact file paths or glob patterns identifying files to remove.
```robotframework * Test Cases * Remove Files
Remove Files ${TEMPDIR}/foo.txt ${TEMPDIR}/*.log
- empty_directory(path: str)[source]
Deletes all the content from the given directory.
- Args:
path: Path to the directory to empty.
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.
- Args:
path: Path to the directory to create.
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.
- Args:
path: Path to the directory to remove. recursive: When true, remove the directory recursively.
If recursive is 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 path does not exist, the keyword passes, but it fails, if the path points to a file.
- copy_file(source: str, destination: str) str[source]
Copies the source file into the destination.
- Args:
source: Existing file path or a glob pattern matching one file. destination: Destination file or directory path.
- Returns:
The resulting destination file path.
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:
If the destination is an existing file, the source file is copied over it.
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.
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.
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.
See also [Copy Files], [Move File], and [Move Files].
- move_file(source: str, destination: str) str[source]
Moves the source file into the destination.
- Args:
source: Existing file path or a glob pattern matching one file. destination: Destination file or directory path.
- Returns:
The resulting destination file path.
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.
- Args:
- *sources_and_destination: Source paths or glob patterns followed by
the destination directory as the final argument.
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.
```robotframework * Test Cases * Copy Files
Copy Files ${dir}/file-1.txt ${dir}/file-2.txt ${dir2} Copy Files ${dir}/file-*.txt ${dir2}
See also [Copy File], [Move File], and [Move Files].
- move_files(*sources_and_destination: str)[source]
Moves specified files to the target directory.
- Args:
- *sources_and_destination: Source paths or glob patterns followed by
the destination directory as the final argument.
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.
- Args:
source: Path to the existing source directory. destination: Destination directory path.
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.
- Args:
source: Path to the existing source directory. destination: Destination directory path.
Uses [Copy Directory] keyword internally, and source and destination arguments 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.
- Args:
name: Name of the environment variable. default: Value to return if the variable does not exist.
- Returns:
The environment variable value or the given default value.
If no environment variable is found, returns possible default value. If no default value is given, the keyword fails.
Note that you can also access environment variables using the variable syntax %{ENV_VAR_NAME}.
- set_environment_variable(name: str, value: str | Secret)[source]
Sets an environment variable to a specified value.
- Args:
name: Name of the environment variable. value: Value to set. [Secret] values are not logged.
- append_to_environment_variable(name: str, *values: str | Secret, separator: str = ':')[source]
Appends given values to environment variable name.
- Args:
name: Name of the environment variable. *values: Values to append. [Secret] values are not logged. separator: Separator to use between values.
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 like separator=value.
```robotframework * Test Cases * Append To Environment Variable
Append To Environment Variable NAME first Should Be Equal %{NAME} first Append To Environment Variable NAME second third Should Be Equal %{NAME} first${:}second${:}third Append To Environment Variable NAME2 first separator=- Should Be Equal %{NAME2} first Append To Environment Variable NAME2 second separator=- Should Be Equal %{NAME2} first-second
- remove_environment_variable(*names: str)[source]
Deletes the specified environment variable.
- Args:
*names: Names of the environment variables to remove.
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.
- Args:
name: Name of the environment variable to check. msg: Optional custom error message.
Environment variable is considered not to be set if it does not exist or if its value is an empty string.
- environment_variable_should_not_be_set(name: str, msg: str | None = None)[source]
Fails if the specified environment variable is set.
- Args:
name: Name of the environment variable to check. msg: Optional custom error message.
Environment variable is considered not to be set if it does not exist or if its value is an empty string.
- get_environment_variables() dict[str, str][source]
Returns currently available environment variables as a dictionary.
- Returns:
A dictionary containing the available environment variables.
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.
- Args:
level: Log level to use.
- Returns:
A dictionary containing the available environment variables.
Environment variables are returned the same way as with the [Get Environment Variables] keyword.
- join_path(base: str, *parts: str) str[source]
Joins the given path part(s) to the given base path.
- Args:
base: Base path. *parts: Path parts to join to the base path.
- Returns:
The constructed and normalized path.
The path separator (/ or ``) is inserted when needed and the possible absolute paths handled as expected. The resulted path is also normalized.
```robotframework * Test Cases * Join Path
${path1} = Join Path my path ${path2} = Join Path my/ path/ ${path3} = Join Path my path my file.txt ${path4} = Join Path my /path ${path5} = Join Path /my/path/ .. path2 Should Be Equal ${path1} my/path Should Be Equal ${path2} my/path Should Be Equal ${path3} my/path/my/file.txt Should Be Equal ${path4} /path Should Be Equal ${path5} /my/path2
On Windows results would use ` instead of `/.
- join_paths(base: str, *paths: str) list[str][source]
Joins given paths with base and returns resulted paths.
- Args:
base: Base path. *paths: Paths to join to the base path.
- Returns:
A list of constructed and normalized paths.
See [Join Path] for more information.
```robotframework * Test Cases * Join Paths
@{paths1} = Join Paths base example other @{paths2} = Join Paths /my/base /root one/more Should Be Equal ${paths1} [‘base/example’, ‘base/other’] type=list Should Be Equal ${paths2} [‘/root’, ‘/my/base/one/more’] type=list
On Windows results would use ` instead of `/.
- normalize_path(path: str, case_normalize=False) str[source]
Normalizes the given path.
- Args:
path: Path to normalize. case_normalize: When true, normalize character case on Windows.
- Returns:
The normalized path.
In practice this keyword does the following:
Collapses redundant separators and up-level references.
Converts / to `` on Windows.
Replaces initial ~ or ~user by that user’s home directory.
If case_normalize is given a true value on Windows, converts the path to all lowercase.
Converts pathlib.Path instances to str.
```robotframework * Test Cases * Normalize Path
${path1} = Normalize Path abc/ ${path2} = Normalize Path abc/../def ${path3} = Normalize Path abc/./def//ghi ${path4} = Normalize Path ~robot/stuff Should Be Equal ${path1} abc Should Be Equal ${path2} def Should Be Equal ${path3} abc/def/ghi Should Be Equal ${path4} /home/robot/stuff
On Windows result would use ` instead of `/ and the home directory would be different.
- split_path(path: str) tuple[str, str][source]
Splits the given path from the last path separator (/ or ``).
- Args:
path: Path to split.
- Returns:
A tuple containing the directory and final path component.
The given path is first normalized (e.g. a possible trailing path separator and special directories .. and . removed). The parts that are split are returned as separate components.
```robotframework * Test Cases * Split Path
${path1} ${dir} = Split Path abc/def ${path2} ${file} = Split Path abc/def/ghi.txt Should Be Equal ${path1} abc Should Be Equal ${dir} def Should Be Equal ${path2} abc/def Should Be Equal ${file} ghi.txt
- split_extension(path: str) tuple[str, str][source]
Splits the extension from the given path.
- Args:
path: Path whose extension to split.
- Returns:
A tuple containing the path without the extension and the extension without its leading dot.
The given path is first normalized (e.g. possible trailing path separator and special directories .. and . removed). The base path and the 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.
```robotframework * Test Cases * Split Extension
${path1} ${ext1} = Split Extension file.extension ${path2} ${ext2} = Split Extension path/file.ext ${path3} ${ext3} = Split Extension path/file ${path4} ${ext4} = Split Extension p1/../p2/file.ext ${path5} ${ext5} = Split Extension path/.file.ext ${path6} ${ext6} = Split Extension path/.file Should Be Equal ${path1} file Should Be Equal ${ext1} extension Should Be Equal ${path2} path/file Should Be Equal ${ext2} ext Should Be Equal ${path3} path/file Should Be Empty ${ext3} Should Be Equal ${path4} p2/file Should Be Equal ${ext4} ext Should Be Equal ${path5} path/.file Should Be Equal ${ext5} ext Should Be Equal ${path6} path/.file Should Be Empty ${ext6}
- get_modified_time(path: str, format: str = 'timestamp') int | str | list[str][source]
Returns the last modification time of a file or directory.
- Args:
path: Path to the file or directory to inspect. format: Format controlling which representation or time parts to return.
- Returns:
The modification time as an integer, timestamp string, or list of selected time parts depending on format.
How time is returned is determined based on the given format string as follows. Note that all checks are case-insensitive. Returned time is also automatically logged.
If format contains the word epoch, the time is returned in seconds after the UNIX epoch. The return value is always an integer.
If format contains any of the words year, month, day, hour, min or sec, 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 in format is 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.
```robotframework * Test Cases * Get Modified Time
${time} = Get Modified Time ${CURDIR} ${secs} = Get Modified Time ${CURDIR} epoch ${year} ${month} = Get Modified Time ${CURDIR} year, month Should Be Equal ${time} 2006-03-29 15:06:21 Should Be Equal ${secs} 1143637581 type=int Should Be Equal ${year} 2006 Should Be Equal ${month} 03
- set_modified_time(path: str, mtime: int | str)[source]
Sets the file modification and access times.
- Args:
path: Path to the regular file to modify. mtime: New modification time in one of the supported formats.
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 mtime is 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 mtime is a timestamp, that time will be used. Valid timestamps formats are YYYY-MM-DD hh:mm:ss and YYYYMMDD hhmmss.
If mtime is equal to NOW, the current local time is used.
If mtime is equal to UTC, the current time in [UTC](https//en.wikipedia.org/wiki/Coordinated_Universal_Time) is used.
If mtime is in the format like NOW - 1 day or UTC + 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.
```robotframework * Test Cases * Set Modified Time
Set Modified Time /path/file 1177654467 Set Modified Time /path/file 2007-04-27 9:14:27 Set Modified Time /path/file NOW Set Modified Time /path/file NOW - 1 day Set Modified Time /path/file UTC + 1h 2min 3s
- get_file_size(path: str) int[source]
Returns and logs file size as an integer in bytes.
- Args:
path: Path to the file to inspect.
- Returns:
The file size in bytes.
- 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.
- Args:
path: Path to the directory to list. pattern: Optional glob pattern for filtering items. absolute: When true, return absolute file paths instead of file names.
- Returns:
A case-sensitively sorted list of matching items.
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 the absolute argument a true value.
If pattern is given, only items matching it are returned. The pattern is considered to be a glob pattern (see [Glob patterns]). With this keyword matching is always case-sensitive.
```robotframework * Test Cases * List Directory
@{items} = List Directory ${TEMPDIR} @{files} = List Files In Directory /tmp *.txt absolute ${count} = Count Files In Directory ${CURDIR} ???
- list_files_in_directory(path: str, pattern: str | None = None, absolute: bool = False) list[str][source]
Wrapper for [List Directory] that returns only files.
- Args:
path: Path to the directory to list. pattern: Optional glob pattern for filtering files. absolute: Return absolute paths instead of names if true.
- Returns:
A case-sensitively sorted list of matching 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.
- Args:
path: Path to the directory to list. pattern: Optional glob pattern for filtering directories. absolute: Return absolute paths instead of names if true.
- Returns:
A case-sensitively sorted list of matching 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.
- Args:
path: Path to the directory whose items to count. pattern: Optional glob pattern for filtering items.
- Returns:
The number of matching items.
The argument pattern has the same semantics as with [List Directory] keyword.
- count_files_in_directory(path: str, pattern: str | None = None) int[source]
Wrapper for [Count Items In Directory] returning only file count.
- Args:
path: Path to the directory whose files to count. pattern: Optional glob pattern for filtering files.
- Returns:
The number of matching files.
- count_directories_in_directory(path: str, pattern: str | None = None) int[source]
Wrapper for [Count Items In Directory] returning only directory count.
- Args:
path: Path to the directory whose subdirectories to count. pattern: Optional glob pattern for filtering directories.
- Returns:
The number of matching directories.
- touch(path: str)[source]
Emulates the UNIX touch command.
- Args:
path: Path to the file to create or update.
Creates a file, if it does not exist. Otherwise, changes its access and modification times to the current time.
Fails if used with the directories or the parent directory of the given file does not exist.
robot.libraries.Process module
- class robot.libraries.Process.ProcessResult(process, stdout, stderr, stdin=None, rc=None, output_encoding=None, streams_to_close=())[source]
Bases:
objectAn object containing process execution results in its attributes.
|-------------|—————————————————————|
```robotframework * Test Cases * Run process
${result} = Run Process python -c print(“Hello!”) Should Be Equal ${result.rc} 0 type=int Should Be Equal ${result.stdout} Hello! Should Be Empty ${result.stderr}
Notice that in stdout and stderr content possible trailing newline is removed and rn converted to n automatically. 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 the 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 Run and other similar keywords in the [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 uses Python’s standard [subprocess] module internally.
### 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.
```robotframework * Test Cases * Command and arguments separately
Run Process python -c print(“Hello!”) Run Process ${tools}/prog.py argument second arg with spaces
- Command and arguments as single string
Run Process prog.py “one arg” && tool.sh shell=True cwd=${tools}
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=value syntax. Available configuration arguments are listed below and discussed further in the subsequent sections.
|-----------------|———————————————————-|
Note that possible equal signs in other arguments passed to the [Run Process] and [Start Process] keywords must be escaped with a backslash like name=value. See the [Run Process] keyword for an example.
## Running processes in shell
The shell argument specifies whether to run the process in a shell or not. By default, shell is not used, which means that shell specific commands, like copy and dir on Windows, are not available. You can, however, run shell scripts and batch files without using a shell.
Using shell=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 the [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 cwd argument. Forward slashes in the given path are automatically converted to backslashes on Windows.
When [standard output and error streams] are redirected to files, file paths are relative to the current working directory as well.
```robotframework * Test Cases * Current working directory
Run Process prog.exe cwd=${ROOT}/directory stdout=stdout.txt
## Environment variables
The child process will get a copy of the parent process’s environment variables by default. The env argument 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 the env:<name>=<value> format to set or override only that named variables. It is also possible to use these two approaches together.
```robotframework * Test Cases * Environment variables
Run Process program env=${environ} Run Process program env:http_proxy=10.144.1.10:8080 env:PATH=%{PATH}${:}${PROGDIR} Run Process program env=${environ} env:EXTRA=value
## 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 stdout and stderr arguments 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 stdout and stderr paths 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_encoding argument 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 outputs at all, you can explicitly ignore it by using a special value DEVNULL both with stdout and stderr. For example, stdout=DEVNULL is the same as redirecting output on console with > /dev/null on UNIX-like operating systems or > NUL on Windows. This way even a huge amount of output cannot cause problems, but naturally the output is not available after execution either.
```robotframework * Test Cases * Redirect stdout and stderr
${result} = Run Process program stdout=${TMP}/stdout.txt stderr=${TMP}/stderr.txt
- Merge stderr to stdout
${result} = Run Process program stderr=STDOUT
- Discard output
${result} = Run Process program stdout=DEVNULL stderr=DEVNULL
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 stdin argument 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 PIPE and NONE are case-insensitive and internally mapped to subprocess.PIPE and None, respectively.
```robotframework * Test Cases * Stdin as file
Run Process command stdin=${CURDIR}/stdin.txt
- Stdin as text
Run Process command stdin=Stdin as text.
- Stdin from other process
${process} = Start Process command1 Run Process command2 stdin=${process.stdout}
The [Examples] section has an executable example where output of a process is passed to another using stdin.
The support to configure stdin is new in Robot Framework 4.1.2. Its default value used to be PIPE until 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_encoding argument. This is especially useful on Windows where the console can use 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_encoding argument must be a valid encoding and must match the encoding actually used by the command. As a convenience, it is possible to use strings CONSOLE and SYSTEM to 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.
```robotframework * Test Cases * Output encoding
Start Process program output_encoding=UTF-8 Run Process program stdout=${path} output_encoding=SYSTEM
## Alias
A custom name given to the process that can be used when selecting the [active process].
```robotframework * Test Cases * Alias
Start Process program alias=MyProgram # Later Wait For Process MyProgram
# 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 handle argument. The handle can be an [alias] explicitly 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.
|-------------|—————————————————————|
```robotframework * Test Cases * Result object
${result} = Run Process python -c print(“Hello!”) Should Be Equal ${result.rc} 0 type=int Should Be Equal ${result.stdout} Hello! Should Be Empty ${result.stderr}
Notice that in stdout and stderr content possible trailing newline is removed and rn converted to n automatically. If you need to see the original process output, redirect it to a file using [process configuration] and read it from there.
# Examples
These examples can be executed locally.
```robotframework * Settings * Library Process Suite Teardown Terminate All Processes kill=True
* Test Cases * Simple execution
${result} = Run Process python -c print(“Hello, world!”) Should Be Equal ${result.stdout} Hello, world!
- Background processes and process configuration
${process} = Start Process python -c print(“Hello!”) Start Process … python -c “import time; time.sleep(3)” && python -c “print(‘Hi!’)” … stdout=${CURDIR}/stdout.txt … stderr=STDOUT … shell=True … alias=Slow ${result1} = Run Process python -c print(“Moi!”) Should Be Equal ${result1.stdout} Moi! ${result2} = Wait For Process ${process} Should Be Equal ${result2.stdout} Hello! ${result3} = Wait For Process Slow Should Be Equal ${result3.stdout} Hi!
- Pipeline
${process} = Start Process python -c print(“Hello, world!”) ${result} = Run Process … python -c import sys; print(sys.stdin.read().upper().strip()) … stdin=${process.stdout} Wait For Process ${process} Should Be Equal ${result.stdout} HELLO, WORLD!
[OperatingSystem]: https://robotframework.org/robotframework/latest/libraries/OperatingSystem.html [subprocess]: https://docs.python.org/library/subprocess.html [subprocess.Popen]: https://docs.python.org/3/library/subprocess.html#popen-objects
- 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.
- Args:
command: Command to execute. *arguments: Arguments passed to the command. cwd: Working directory of the process. shell: Whether to run the command in a shell. stdout: Path to file for standard output. stderr: Path to file for standard error. stdin: Process standard input configuration. output_encoding: Encoding for reading command outputs. alias: Custom name for the process. timeout: Maximum time to wait for the process. on_timeout: Action when timeout occurs. env: Environment variables as a Python dictionary. **env_extra: Override named environment variables using
env:<name>=<value> syntax.
- Returns:
Result object containing execution results.
command and arguments specify the command to execute and arguments passed to it. See the [Specifying command and arguments] section for more details.
The started process can be configured using the cwd, shell, stdout, stderr, stdin, output_encoding, env, env_extra and alias parameters that are documented in the [Process configuration] section.
Configuration related to waiting for processes consists of timeout and on_timeout parameters 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 stdout and stderr configuration parameters. See the [Standard output and error streams] section for more information.
Note that possible equal signs in command and arguments must be escaped with a backslash (e.g. name=value).
This keyword does not change the [active process].
```robotframework * Test Cases * Run process
${result} = Run Process python -c print(“Hello, world!”) Should Be Equal ${result.stdout} Hello, world! ${result} = Run Process ${command} stdout=${CURDIR}/stdout.txt stderr=STDOUT ${result} = Run Process ${command} timeout=1 minute on_timeout=continue ${result} = Run Process java -Dname=value Example shell=True cwd=${EXAMPLE}
- 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.
- Args:
command: Command to execute. *arguments: Arguments passed to the command. cwd: Working directory for the process. shell: Whether to run the command in a shell. stdout: Path to file for standard output. stderr: Path to file for standard error. stdin: Process standard input configuration. output_encoding: Encoding for reading command outputs. alias: Custom name for the process. env: Environment variables as a Python dictionary. **env_extra: Override named environment variables using
env:<name>=<value> syntax.
- Returns:
Created [subprocess.Popen] object which can be used later to activate this process. Popen attributes like pid can also be accessed directly.
See the [Specifying command and arguments] and [Process configuration] sections for more information about the arguments, and the [Run Process] keyword for related examples. This includes information about redirecting process outputs to avoid process handing due to output buffers getting full.
Processes are started so that they create a new process group. This allows terminating and sending signals to possible child processes.
Makes the started process new [active process].
```robotframework * Test Cases * Start process and wait using alias
Start Process ${command} alias=example # Later ${result} = Wait For Process example
- Start process and terminate using process object
${process} = Start Process ${command} Log PID: ${process.pid} # Later Terminate Process ${process}
See the [Examples] section for examples starting multiple processes and creating process pipelines.
Returning a [subprocess.Popen] object is new in Robot Framework 5.0. Earlier versions returned a generic handle and getting the process object required using the [Get Process Object] keyword separately.
- is_process_running(handle: Popen | str | None = None) bool[source]
Checks is the process running or not.
- Args:
- handle: Process handle or alias. Uses the current [active process]
by default.
- Returns:
True if the process is still running and False otherwise.
- process_should_be_running(handle: Popen | str | None = None, error_message: str = 'Process is not running.')[source]
Verifies that the process is running.
- Args:
- handle: Process handle or alias. Uses the current [active process]
by default.
error_message: Message used if verification fails.
- Raises:
AssertionError: 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.
- Args:
- handle: Process handle or alias. Uses the current [active process]
by default.
error_message: Message used if verification fails.
- Raises:
AssertionError: 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.
- Args:
- handle: Process handle or alias. Uses the current [active process]
by default.
timeout: Maximum time to wait for the process. on_timeout: What to do if the process does not end within the timeout.
- Returns:
Result object if the process ends, None if it is left running.
The process to wait for must have been started earlier using the [Start Process] keyword.
timeout defines the maximum time to wait for the process. It can be given in formats like 42, 42 s, or 1 minute 30 seconds. The timeout is ignored if it is None (default), zero or negative.
on_timeout defines 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 the [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 None is 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.
```robotframework * Test Cases * Process ends cleanly
${result} = Wait For Process example Process Should Be Stopped example Should Be Equal ${result.rc} 0 type=int
- Process does not end
${result} = Wait For Process timeout=42 secods Process Should Be Running Should Be Equal ${result} None type=None
- Kill non-ending process
${result} = Wait For Process timeout=1min 30s on_timeout=kill Should Be Equal ${result.rc} -9 type=int
- terminate_process(handle: Popen | str | None = None, kill: bool = False) ProcessResult[source]
Stops the process gracefully or forcefully.
- Args:
handle: Process handle or alias. Uses the current [active process] by default. kill: Whether to forcefully kill the process.
- Returns:
Result object containing information about the execution.
- Raises:
- RuntimeError: If terminating processes is not supported by the
used Python version, or if forceful kill fails.
By default, first tries to stop the process gracefully. If the process does not stop in 30 seconds, or the kill argument 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 the TERM (15) signal and forceful kill using KILL (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 the CTRL_BREAK_EVENT event and forceful kill using Win32 API function TerminateProcess(). 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.
- Args:
kill: Whether to forcefully kill processes.
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 the [Terminate Process] keyword 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 signal to the specified process.
- Args:
signal: The signal to send, either as an integer or signal name. handle: Process handle or alias. Uses the current [active process]
by default.
group: Whether to send the signal to the whole process group.
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 SIG prefix, but names are case-sensitive. For example, all the examples below send signal INT (2).
```robotframework * Test Cases * Send signal
Send Signal To Process 2 Send Signal To Process INT Send Signal To Process SIGINT myproc
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 signal or man 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.
- get_process_id(handle: Popen | str | None = None) int[source]
Returns the process ID (pid) of the process as an integer.
- Args:
- handle: Process handle or alias. Uses the current [active process]
by default.
- Returns:
Process ID as an integer.
Starting from Robot Framework 5.0, it is also possible to directly access the pid attribute of the [subprocess.Popen] object returned by the [Start Process] keyword like ${process.pid}.
- get_process_object(handle: Popen | str | None = None) Popen[source]
Return the underlying subprocess.Popen object.
- Args:
- handle: Process handle or alias. Uses the current [active process]
by default.
- Returns:
The underlying [subprocess.Popen] object.
Starting from Robot Framework 5.0, the [Start Process] keyword returns the created [subprocess.Popen] object directly. That makes 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.
- Args:
- handle: Process handle or alias. Uses the current [active process]
by default.
rc: If true, return the return code. stdout: If true, return the standard output. stderr: If true, return the standard error. stdout_path: If true, return the stdout path. stderr_path: If true, return the stderr path.
- Returns:
A result object, a single attribute, or a tuple of attributes depending on which arguments are given.
The given handle specifies the process whose results should be returned. If no handle is 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 handle are 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.
```robotframework * Test Cases * Get process result
Run Process python -c print(‘Hello, world!’) alias=myproc # Get result object ${result} = Get Process Result myproc Should Be Equal ${result.rc} 0 type=int Should Be Equal ${result.stdout} Hello, world! # Get one attribute ${stdout} = Get Process Result myproc stdout=Trye Should Be Equal ${stdout} Hello, world! # Get multiple attributes ${stdout} ${stderr} = Get Process Result myproc rc=True stderr=True Should Be Equal ${rc} 0 type=int Should Be Equal ${stdout} Hello, world!
- switch_process(handle: Popen | str | None)[source]
Makes the specified process the current [active process].
- Args:
handle: Process handle or alias to activate.
The handle can be the process object returned by the [Start Process] keyword or the alias given to it explicitly.
```robotframework * Test Cases * Switch Active Process
Start Process prog1 alias=process1 Start Process prog2 alias=process2 # The active process is ‘process2’ at this point. Switch Process process1 # Now active process is ‘process1’.
- ROBOT_AUTO_KEYWORDS = True
- ROBOT_LIBRARY_CONVERTERS = {<class 'robot.libraries.Process.ProcessResult'>: <function <lambda>>, <class 'subprocess.Popen'>: <function _popen_documentation>}
- ROBOT_LIBRARY_DOC_FORMAT = 'MARKDOWN'
- ROBOT_LIBRARY_SCOPE = 'GLOBAL'
- ROBOT_LIBRARY_VERSION = '(.*)'
- split_command_line(command: str, escaping: bool = False) list[str][source]
Splits command line string into a list of arguments.
- Args:
command: Command line string to split. escaping: Whether to treat backslash as an escape character.
- Returns:
List of command line arguments.
String is split from spaces, but argument surrounded in quotes may contain spaces in them.
If escaping is 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.
```robotframework * Test Cases * Parse Command Line
@{cmd} = Split Command Line –option “value with spaces” Should Be Equal ${cmd} [’–option’, ‘value with spaces’] type=list
- join_command_line(*command: Sequence[str] | str) str[source]
Joins arguments into one command line string.
- Args:
*command: Arguments to join, either as individual strings or as a list.
- Returns:
Joined 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.
```robotframework * Test Cases * Command as individual arguments
${cmd} = Join Command Line –option value with spaces Should Be Equal ${cmd} –option “value with spaces”
- Command as list
VAR @{arguments} –option value with spaces ${cmd} = Join Command Line ${arguments} Should Be Equal ${cmd} –option “value with spaces”
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 screencapture utility. 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 many Linux distributions.
[Pillow](http://python-pillow.github.io) - Only used 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 scrot or similar.
# Where screenshots are saved
Screenshots are saved into the same directory where the Robot Framework log file is written by default. If no log is created, screenshots are saved into the directory where the output file is written.
It is possible to specify a custom location for screenshots using screenshot_directory argument when [importing] the library and using [Set Screenshot Directory] keyword during execution. It is also possible to save screenshots using an absolute path.
# ScreenCapLibrary
[ScreenCapLibrary](https://github.com/mihaiparvu/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.
- Args:
- screenshot_directory: If not given, screenshots are saved into
same directory as the log file. The directory can also be set using [Set Screenshot Directory] keyword.
- screenshot_module: Specifies the module or tool to use when using
this library outside OSX. Possible values are wxPython, PyGTK, PIL and scrot, case-insensitively. If no value is given, the first module/tool found is used in that order.
`robotframework *** Settings *** Library Screenshot Library Screenshot ${TEMPDIR} Library Screenshot screenshot_module=PyGTK `- ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
- ROBOT_LIBRARY_VERSION = '(.*)'
- ROBOT_LIBRARY_DOC_FORMAT = 'Markdown'
- 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].
- Args:
path: Directory where to save screenshots. Must already exist.
- Returns:
Path to the previous screenshot directory.
- Raises:
RuntimeError: If path does not exist or is not a directory.
- 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 the name ends with extension .jpg or .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 the name.
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.
width specifies the size of the screenshot in the log file.
- Args:
name: Base name or path for the screenshot file. width: Width of the embedded image in the log file.
- Returns:
Path where the screenshot was saved.
```robotframework * Test Cases * Take Screenshots
Take Screenshot # LOGDIR/screenshot_1.jpg Take Screenshot # LOGDIR/screenshot_2.jpg Take Screenshot mypic # LOGDIR/mypic_1.jpg Take Screenshot mypic # LOGDIR/mypic_2.jpg Take Screenshot pic.jpg # LOGDIR/pic.jpg Take Screenshot pic.jpg # LOGDIR/pic.jpg Take Screenshot ${TEMPDIR}/mypic # /tmp/mypic_1.jpg Take Screenshot images/login.jpg 80% Take Screenshot width=550px
- 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.
- Args:
name: Base name or path for the screenshot file.
- Returns:
Path where the screenshot was saved.
robot.libraries.String module
- class robot.libraries.String.String[source]
Bases:
objectA library for string manipulation and verification.
String is 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 the [BuiltIn] library 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
[BuiltIn]: https://robotframework.org/robotframework/latest/libraries/BuiltIn.html
- convert_to_lower_case(string: str | bytes) str | bytes[source]
Converts string to lower case.
- Args:
string: The string or bytes to convert.
- Returns:
The input converted to lower case.
Uses Python’s standard [str.lower()](https://docs.python.org/library/stdtypes.html#str.lower) or [bytes.lower()](https://docs.python.org/library/stdtypes.html#bytes.lower) method, depending on the input value type.
```robotframework * Test Cases * Convert to lower case
${str1} = Convert To Lower Case ABC ${str2} = Convert To Lower Case 1A2c3D Should Be Equal ${str1} abc Should Be Equal ${str2} 1a2c3d
If this keyword is used with bytes, only ASCII characters are lowercased.
- convert_to_upper_case(string: str | bytes) str | bytes[source]
Converts string to upper case.
- Args:
string: The string or bytes to convert.
- Returns:
The input converted to upper case.
Uses Python’s standard [str.upper()](https://docs.python.org/library/stdtypes.html#str.upper) or [bytes.upper()](https://docs.python.org/library/stdtypes.html#bytes.upper) method, depending on the input value type.
```robotframework * Test Cases * Convert to upper case
${str1} = Convert To Upper Case abc ${str2} = Convert To Upper Case 1a2C3d Should Be Equal ${str1} ABC Should Be Equal ${str2} 1A2C3D
If this keyword is used with bytes, only ASCII characters are uppercased.
- convert_to_title_case(string: str | bytes, exclude: str | bytes | list[str | bytes] | None = None) str | bytes[source]
Converts string to title case.
- Args:
string: The string or bytes to convert. exclude: Optional words to exclude from title casing. Can be a list
or a comma-separated string. Each word is treated as a regular expression pattern.
- Returns:
The input converted to title case.
Titlecasing is done using 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 exclude argument.
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 its own and also if followed by ., ! or ?. See the [BuiltIn] library keyword Should Match Regexp for more information about Python regular expression syntax in general and how to use it in Robot Framework data in particular.
```robotframework * Test Cases * Convert to title case
${str1} = Convert To Title Case hello, world! ${str2} = Convert To Title Case it’s an OK iPhone exclude=a, an, the ${str3} = Convert To Title Case distance is 1 km. exclude=is, km.? Should Be Equal ${str1} Hello, World! Should Be Equal ${str2} It’s an OK iPhone Should Be Equal ${str3} Distance is 1 km.
The reason this keyword does not use Python’s standard [str.title()](https://docs.python.org/library/stdtypes.html#str.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 titlecased. 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 string to bytes using the given encoding.
- Args:
string: The string to encode. encoding: The encoding to use. errors: How to handle encoding errors.
- Returns:
The input string encoded to bytes.
The errors argument supports all Python’s standard [error handlers](https://docs.python.org/3/library/codecs.html#error-handlers), but in practice the following values are most useful:
strict: fail if characters cannot be encoded (default)
ignore: ignore characters that cannot be encoded
replace: replace characters that cannot be encoded with a replacement character
```robotframework * Test Cases * Encode string to bytes
${bytes} = Encode String To Bytes ${string} UTF-8 ${bytes} = Encode String To Bytes ${string} ASCII errors=ignore
Use the [Decode Bytes To String] keyword if you need to convert bytes to strings. Use the [BuiltIn] library keyword Convert To Bytes if you want to create bytes based on character or integer sequences.
- decode_bytes_to_string(bytes: bytes, encoding: str, errors: str = 'strict') str[source]
Decodes the given bytes to a string using the given encoding.
- Args:
bytes: The bytes to decode. encoding: The encoding to use. errors: How to handle encoding errors.
- Returns:
The input bytes decoded to string,
The errors argument supports all Python’s standard [error handlers](https://docs.python.org/3/library/codecs.html#error-handlers), but in practice the following values are most useful:
strict: fail if characters cannot be encoded (default)
ignore: ignore characters that cannot be encoded
replace: replace characters that cannot be encoded with a replacement character
```robotframework * Test Cases * Decide bytes ti strinog
${string} = Decode Bytes To String ${bytes} UTF-8 ${string} = Decode Bytes To String ${bytes} ASCII errors=ignore
Use the [Encode String To Bytes] keyword if you need to convert strings to bytes. Use the [BuiltIn] library keyword Convert To String if you want to convert arbitrary objects to strings.
- format_string(template: str | bytes, /, *positional: object, **named: object) str | bytes[source]
Formats a template using the given positional and named arguments.
- Args:
template: A template string or an absolute path to a template file. *positional: Positional arguments used to format the template. **named: Named arguments used to format the template.
- Returns:
The formatted string or bytes.
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 [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 }}.
```robotframework * Test Cases * Format string
${to} = Format String To: {} <{}> ${user} ${email} ${to} = Format String To: {name} <{email}> name=${name} email=${email} ${to} = Format String To: {u.name} <{u.email}> u=${user_object} ${xx} = Format String {:*^30} centered ${yy} = Format String {0:{width}{base}} ${42} base=X width=10 ${zz} = Format String ${CURDIR}/template.txt positional named=value
Prior to Robot Framework 7.1, possible equal signs in the template string needed to be escaped with a backslash like x={}. Bytes support is new in Robot Framework 7.4.
[format string syntax]: https://docs.python.org/library/string.html#format-string-syntax
- get_line_count(string: str | bytes) int[source]
Returns and logs the number of lines in the given string.
- Args:
string: The string or bytes to count lines from.
- Returns:
The number of lines.
- 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.
- Args:
string: The string or bytes to split. start: Start index for line selection. Defaults to 0. end: End index for line selection. Defaults to None (end of string).
- Returns:
A list of lines.
It is possible to get only a selection of lines from start to end so that start index is inclusive and end is 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.
```robotframework * Test Cases * Split to lines
@{lines} = Split To Lines ${string} @{ignore first} = Split To Lines ${string} 1 @{ignore last} = Split To Lines ${string} end=-1 @{5th to 10th} = Split To Lines ${string} 4 10 @{first two} = Split To Lines ${string} end=1 @{last two} = Split To Lines ${string} start=-2
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.
- Args:
string: The string or bytes to get the line from. line_number: Index of the line to return.
- Returns:
The specified line without the newline character.
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.
```robotframework * Test Cases * Get line
${first} = Get Line ${string} 0 ${2nd last} = Get Line ${string} -2
Use [Split To Lines] if all lines, or a subset of 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 string that contain the pattern.
- Args:
string: The string or bytes to search lines from. pattern: The string pattern to search for. case_insensitive: Deprecated alias for ignore_case. ignore_case: If given a true value, matching is case-insensitive.
- Returns:
Matching lines joined with newlines.
The pattern is always considered to be a normal string, not a glob or regexp pattern. A line matches if the pattern is found anywhere on it.
The match is case-sensitive by default, but that can be changed by giving ignore_case a true value. This option is new in Robot Framework 7.0, but with older versions it is possible to use the nowadays deprecated case_insensitive argument.
Lines are returned as a single string with lines joined together with a newline. Possible trailing newline is never returned. The number of matching lines is automatically logged.
```robotframework * Test Cases * Get lines containing string
${lines} = Get Lines Containing String ${string} An example ${lines} = Get Lines Containing String ${string} FAIL ignore_case=True
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 string that match the pattern.
- Args:
string: The string or bytes to search lines from. pattern: The glob pattern to match. case_insensitive: Deprecated alias for ignore_case. ignore_case: If given a true value, matching is case-insensitive.
- Returns:
Matching lines joined with newlines.
The pattern is a _glob pattern_ where:
A line matches only if it matches the pattern fully.
The match is case-sensitive by default, but that can be changed by giving ignore_case a true value. This option is new in Robot Framework 7.0, but with older versions it is possible to use the nowadays deprecated case_insensitive argument.
Lines are returned as a single string with lines joined together with a newline. Possible trailing newline is never returned. The number of matching lines is automatically logged.
```robotframework * Test Cases * Get lines matching regexp
${lines} = Get Lines Matching Pattern ${string} Wild???? example ${lines} = Get Lines Matching Pattern ${string} FAIL: * ignore_case=True
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 string that match the regexp pattern.
- Args:
string: The string or bytes to search lines from. pattern: The regular expression pattern to match. partial_match: If given a true value, lines match if the pattern
is found anywhere on the line.
flags: Optional regular expression flags.
- Returns:
Matching lines joined with newlines.
Lines match only if they match the pattern fully by default, but partial matching can be enabled by giving the partial_match argument 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 the flags argument (e.g. flags=IGNORECASE | VERBOSE) or embedded to the pattern (e.g. (?ix)pattern).
Lines are returned as a single string concatenated back together with newlines. Possible trailing newline is never returned. The number of matching lines is automatically logged.
```robotframework * Test Cases * Get lines matching regexp
${lines} = Get Lines Matching Regexp ${string} Reg\w{3} example ${lines} = Get Lines Matching Regexp ${string} Reg\w{3} example partial_match=True ${lines} = Get Lines Matching Regexp ${string} (?i)FAIL: .* ${lines} = Get Lines Matching Regexp ${string} FAIL: .* flags=IGNORECASE
Notice that the backslash character that is often used with regular expressions is an escape character in Robot Framework data. If a literal backslash is needed, it needs to be doubled as the above example illustrates. For more information about the supported regular expression syntax and using regular expressions with Robot Framework in general, see the documentation of the [BuiltIn] library keyword Should Match Regexp keyword.
Use [Get Lines Matching Pattern] and [Get Lines Containing String] if you do not need the full regular expression powers (and complexity).
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 flags argument is new in Robot Framework 6.0.
- 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.
- Args:
string: The string or bytes to find matches from. pattern: The regular expression pattern to match. *groups: Optional group indexes or names to return. flags: Optional regular expression flags.
- Returns:
A list of matches, group contents, or tuples of group contents.
string is the string to find matches from and pattern is the regular expression. See the [BuiltIn] library keyword 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 can also be given as names.
Possible flags altering how the expression is parsed (e.g. re.IGNORECASE, re.MULTILINE) can be given using the flags argument (e.g. flags=IGNORECASE | MULTILINE) or embedded to the pattern (e.g. (?im)pattern).
```robotframework * Variables * ${string} the string
* Test Cases * No match
${result} = Get Regexp Matches ${string} xxx Should Be Equal ${result} [] type=list
- Match
${result} = Get Regexp Matches ${string} t.. Should Be Equal ${result} [“the”, “tri”] type=list
- Flags
${result} = Get Regexp Matches ${string} T.. flags=IGNORECASE Should Be Equal ${result} [“the”, “tri”] type=list
- One group by index
${result} = Get Regexp Matches ${string} t(..) 1 Should Be Equal ${result} [“he”, “ri”] type=list
- One group by name
${result} = Get Regexp Matches ${string} t(?P<name>..) name Should Be Equal ${result} [“he”, “ri”] type=list
- Multiple groups
${result} = Get Regexp Matches ${string} t(.)(.) 1 2 Should Be Equal ${result} [(“h”, “e”), (“r”, “i”)] type=list
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 flags argument 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_for in the given string with replace_with.
- Args:
string: The string or bytes to modify. search_for: The string to search for. replace_with: The replacement string. count: Maximum number of replacements. -1 means all (default).
- Returns:
The modified string or bytes.
If the optional argument count is given, only that many occurrences from left are replaced. Negative count means that all occurrences are replaced (default behavior) and zero means that nothing is done.
search_for is 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].
A modified version of the string is returned and the original string is not altered.
```robotframework * Test Cases * Replace string
${str} = Replace String Hello, world! world tellus Should Be Equal ${str} Hello, tellus! ${str} = Replace String Hello, world! l e count=1 Should Be Equal ${str} Heelo, world!
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 pattern in the given string with replace_with.
- Args:
string: The string or bytes to modify. pattern: The regular expression pattern to search for. replace_with: The replacement string. count: Maximum number of replacements. -1 means all (default). flags: Optional regular expression flags.
- Returns:
The modified string or bytes.
This keyword is otherwise identical to [Replace String], but the pattern to search for is considered to be a regular expression. See the [BuiltIn] library keyword 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 the flags argument (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].
```robotframework * Test Cases * Replace string using regexp
${str} = Replace String Using Regexp ${str} 2026-\d\d-\d\d <DATE> ${str} = Replace String Using Regexp ${str} (Hello|Hi) Moi count=1
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 flags argument is new in Robot Framework 6.0.
- remove_string(string: str | bytes, *removables: str | bytes) str | bytes[source]
Removes all removables from the given string.
- Args:
string: The string or bytes to modify. *removables: Strings to remove.
- Returns:
The modified string or bytes.
removables are used as literal strings. Each removable will be matched to a temporary string from which preceding removables have been already removed. See the 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.
```robotframework * Test Cases * Remove string
${str} = Remove String Robot Framework work Should Be Equal ${str} Robot Frame ${str} = Remove String Robot Framework o bt Should Be Equal ${str} R Framewrk
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 patterns from the given string.
- Args:
string: The string or bytes to modify. *patterns: Regular expression patterns to remove. flags: Optional regular expression flags.
- Returns:
The modified string or bytes.
This keyword is otherwise identical to [Remove String], but the patterns to 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 the flags argument (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. Bytes support is new in Robot Framework 7.4.
The flags argument is new in Robot Framework 6.0.
- split_string(string: str | bytes, separator: str | bytes | None = None, max_split: int = -1) list[str] | list[bytes][source]
Splits the string using separator as a delimiter string.
- Args:
string: The string or bytes to split. separator: The delimiter string. Defaults to splitting on whitespace. max_split: Maximum number of splits. -1 means no limit (default).
- Returns:
A list of split parts.
If a separator is 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 parts are returned as a list. If the optional max_split is given, at most max_split splits are done, and the returned list will have maximum max_split + 1 elements.
```robotframework * Test Cases * Split string
@{words} = Split String ${string} @{words} = Split String ${string} ,${SPACE} ${pre} ${post} = Split String ${string} :: 1
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 string using separator starting from right.
- Args:
string: The string or bytes to split. separator: The delimiter string. Defaults to splitting on whitespace. max_split: Maximum number of splits. -1 means no limit (default).
- Returns:
A list of split parts.
Same as [Split String], but splitting is started from right. This has an effect only when max_split is given.
```robotframework * Test Cases * Split string from right
${first} ${rest} = Split String ${string} - 1 ${rest} ${last} = Split String From Right ${string} - 1
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 string to characters.
- Args:
string: The string or bytes to split.
- Returns:
A list of single-character strings or bytes.
```robotframework * Test Cases * Split string to characters
@{characters} = Split String To Characters ${string}
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 string before the first occurrence of marker.
- Args:
string: The string or bytes to search from. marker: The marker string to search for.
- Returns:
The part of the string before the first marker.
If the marker is 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 string after the last occurrence of marker.
- Args:
string: The string or bytes to search from. marker: The marker string to search for.
- Returns:
The part of the string after the last marker.
If the marker is 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 length from the given chars.
- Args:
- length: Desired length of the generated string. Can be an integer,
a string representation of an integer, or a range like 5-10.
chars: Characters to use when generating the string.
- Returns:
The generated random string.
length can be given as a number, a string representation of a number, or as a range of numbers, such as 5-10. When a range of values is given the range will be selected by random within the range.
The population sequence chars contains 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:
```robotframework * Test Cases * Generate random string
${ret} = Generate Random String ${low} = Generate Random String 12 [LOWER] ${bin} = Generate Random String 8 01 ${hex} = Generate Random String 4 [NUMBERS]abcdef ${rnd} = Generate Random String 5-10
Giving length as a range of values is new in Robot Framework 5.0. Support for [POLISH] and [ARABIC] markers 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 start index to end index.
- Args:
string: The string or bytes to get the substring from. start: Start index. Defaults to 0. end: End index. Defaults to None (end of string).
- Returns:
The requested substring.
The start index is inclusive and end is exclusive. Indexing starts from 0, and it is possible to use negative indices to refer to characters from the end.
```robotframework * Test Cases * Get substring
${ignore first} = Get Substring ${string} 1 ${ignore last} = Get Substring ${string} 0 -1 ${5th to 10th} = Get Substring ${string} 4 10 ${first two} = Get Substring ${string} end=1 ${last two} = Get Substring ${string} -2
Default value with start is 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.
- Args:
string: The string or bytes to strip. mode: Which end(s) of the string to strip from. characters: Optional characters to remove instead of whitespace.
- Returns:
The stripped string or bytes.
mode is either left to remove leading characters, right to remove trailing characters, both (default) to remove the characters from both sides of the string or none to return the unmodified string.
This keyword strips whitespace by default, but arbitrary characters can be stripped by using the optional characters argument. As the example below illustrates, each character is separately stripped instead of considering characters a substring to be stripped.
```robotframework * Test Cases * Strip string
${stripped} = Strip String ${SPACE}Hello${SPACE} Should Be Equal ${stripped} Hello ${stripped} = Strip String ${SPACE}Hello${SPACE} mode=left Should Be Equal ${stripped} Hello${SPACE} ${stripped} = Strip String aabaHelloeee characters=abe Should Be Equal ${stripped} Hello
If the first argument is bytes, the characters argument 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 item is not a string.
- Args:
item: The object to verify. msg: Optional custom error message.
- should_not_be_string(item: object, msg: str | None = None)[source]
Fails if the given item is a string.
- Args:
item: The object to verify. msg: Optional custom error message.
- should_be_unicode_string(item: object, msg: str | None = None)[source]
Fails if the given item is 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.
- Args:
item: The object to verify. msg: Optional custom error message.
- should_be_byte_string(item: object, msg: str | None = None)[source]
Fails if the given item is not a byte string.
Use [Should Be String] if you want to verify the item is a string.
- Args:
item: The object to verify. msg: Optional custom error message.
- should_be_lower_case(string: str | bytes, msg: str | None = None)[source]
Fails if the given string is not in lower case.
- Args:
string: The string or bytes to verify. msg: Optional custom error message.
For example, ‘string’ and ‘with specials!’ would pass, and ‘String’, ‘’ and ‘ ‘ would fail.
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 string is not in upper case.
- Args:
string: The string or bytes to verify. msg: Optional custom error message.
For example, ‘STRING’ and ‘WITH SPECIALS!’ would pass, and ‘String’, ‘’ and ‘ ‘ would fail.
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 string is not title.
- Args:
string: The string or bytes to verify. msg: Optional custom error message. exclude: Optional words to exclude from title case verification.
Can be a list or a comma-separated string. Each word is treated as a regular expression pattern.
string is 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.
See also [Should Be Upper Case] and [Should Be Lower Case].
- ROBOT_AUTO_KEYWORDS = True
- ROBOT_LIBRARY_DOC_FORMAT = 'MARKDOWN'
- ROBOT_LIBRARY_SCOPE = 'GLOBAL'
- ROBOT_LIBRARY_VERSION = '(.*)'
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.
```robotframework * Test Cases *
# Give source as a path: ${xml} = Parse XML ${CURDIR}/example.xml # Give source as an already parsed element: ${elem} = Get Element ${xml} xpath=child # Give source as a string: Elements Should Be Equal ${elem} <child>text</child>
- class robot.libraries.XML.Element[source]
Bases:
objectA parsed XML element.
Represented as an ElementTree [Element] object. Can be used as a source argument with keywords modifying or validating XML elements. or validating XML elements. In addition to that, attributes like text can be accessed using the extended variable syntax like ${elem.text} directly.
```robotframework * Test Cases *
# Get element as a return value: ${elem} = Parse XML ${CURDIR}/example.xml # Use element as an argument with other keywords: ${child} = Get Element ${elem} expath=child # Access element attributes: Log ${elem.text}
[Element]: https://docs.python.org/3/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element “API docs”
- 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 [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 source argument 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 [ElementTree] module for parsing XML, but it can be configured to use [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. 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.
<first id=”1”>text</first> <second id=”2”>
<child />
</second> <third>
<child>more text</child> <second id=”child” /> <child>
<grandchild />
</child>
</third> <html>
- <p>
Text with <b>bold</b> and <i>italics</i>.
</p>
</html>
```robotframework * Settings * Library XML use_xml=True
- * Test Cases *
${root} = Parse XML ${XML} Should Be Equal ${root.tag} example ${first} = Get Element ${root} first Should Be Equal ${first.text} text Element Text Should Be ${first} text Element Attribute Should Be ${first} id 1 Element Attribute Should Be ${root} id 1 xpath=first Element Attribute Should Be ${XML} id 1 xpath=first
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 [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 [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.
```robotframework * Test Cases * Tag names
${elem} = Get Element ${XML} third Should Be Equal ${elem.tag} third @{children} = Get Elements ${elem} child Length Should Be ${children} 2
## Paths
Paths are created by combining tag names with a forward slash (/). For example, parent/child matches all child elements under parent element. Notice that if there are multiple parent elements that all have child elements, parent/child xpath will match all these child elements.
```robotframework * Test Cases * Paths
${elem} = Get Element ${XML} second/child Should Be Equal ${elem.tag} child ${elem} = Get Element ${XML} third/child/grandchild Should Be Equal ${elem.tag} grandchild
## Wildcards
An asterisk (*) can be used in paths instead of a tag name to denote any element.
```robotframework * Test Cases * Wildcards
@{children} = Get Elements ${XML} */child Length Should Be ${children} 3
## 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.
```robotframework * Test Cases * Parent element
${elem} = Get Element ${XML} */second/.. Should Be Equal ${elem.tag} third
## 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.
```robotframework * Test Cases * Search all sub elements
@{elements} = Get Elements ${XML} .//second Length Should Be ${elements} 2 ${b} = Get Element ${XML} html//b Should Be Equal ${b.text} bold
## 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.
position can be an integer starting from 1, expression last(), or a relative expression like last() - 1.
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 [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. Other attributes, including methods, can also 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.
```robotframework * Test Cases * Tag
${root} = Parse XML ${XML} Should Be Equal ${root.tag} example
## text
The text that the element contains or Python None if 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.
```robotframework * Test Cases * Text
${1st} = Get Element ${XML} first Should Be Equal ${1st.text} text ${2nd} = Get Element ${XML} second/child Should Be Equal ${2nd.text} ${NONE} ${p} = Get Element ${XML} html/p Should Be Equal ${p.text} n${SPACE*12}Text with${SPACE}
## tail
The text after the element before the next opening or closing tag. Python None if the element has no tail. Similarly as with text, also tail contains possible indentation and newlines.
```robotframework * Test Cases * Tail
${b} = Get Element ${XML} html/p/b Should Be Equal ${b.tail} ${SPACE}and${SPACE}
## attrib
A Python dictionary containing attributes of the element.
```robotframework * Test Cases * Attrib
${2nd} = Get Element ${XML} second Should Be Equal ${2nd.attrib[‘id’]} 2 ${3rd} = Get Element ${XML} third Should Be Empty ${3rd.attrib}
# 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 xmlns attribute instead. That can be avoided by passing keep_clark_notation argument to [Parse XML] keyword. Alternatively [Parse XML] supports stripping namespace information altogether by using strip_namespaces argument. 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 [Clark Notation] (e.g. {http://ns.uri}tag) and removes original xmlns attributes. 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 the ${NS} variable contains this XML document:
```xml <xsl:stylesheet xmlns:xsl=”http://www.w3.org/1999/XSL/Transform”
```robotframework * Test Cases * Using Clark notation
${root} = Parse XML ${NS} keep_clark_notation=True Should Be Equal ${root.tag} {http://www.w3.org/1999/XSL/Transform}stylesheet Element Should Exist ${root} {http://www.w3.org/1999/XSL/Transform}template/{http://www.w3.org/1999/xhtml}html Should Be Empty ${root.attrib}
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 xmlns attributes. Unfortunately it does not restore the original prefixes and you get something like this:
```xml <ns0:stylesheet xmlns:ns0=”http://www.w3.org/1999/XSL/Transform”>
- <ns0:template match=”/”>
<ns1:html xmlns:ns1=”http://www.w3.org/1999/xhtml”></ns1:html>
</ns0:template>
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 also on the 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 xmlns attributes. How this works in practice is shown by the example below, where ${NS} variable contains the same XML document as in the previous example.
```robotframework * Test Cases * Default namespace handling
${root} = Parse XML ${NS} Should Be Equal ${root.tag} stylesheet Element Should Exist ${root} template/html Element Attribute Should Be ${root} xmlns http://www.w3.org/1999/XSL/Transform Element Attribute Should Be ${root} xmlns http://www.w3.org/1999/xhtml xpath=template/html
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:
```xml <stylesheet xmlns=”http://www.w3.org/1999/XSL/Transform”>
- <template match=”/”>
<html xmlns=”http://www.w3.org/1999/xhtml”/>
</template>
This output is semantically same as the original as well. 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.
```robotframework * Test Cases * Attribute namespaces
${root} = Parse XML <root id=”1” ns:id=”2” xmlns:ns=”http://my.ns”/> Element Attribute Should Be ${root} id 1 Element Attribute Should Be ${root} {http://my.ns}id 2
## Pattern matching
Some keywords, for example [Elements Should Match], support so called [glob patterns] where:
Unlike with glob patterns normally, path separator characters / and ` and the newline character `n are matches by the above wildcards.
[ElementTree XML API]: http://docs.python.org/library/xml.etree.elementtree.html “ElementTree XML API” [ElementTree]: http://docs.python.org/library/xml.etree.elementtree.html “ElementTree” [lxml]: http://lxml.de “lxml” [ElementTree documentation]: https://docs.python.org/library/xml.etree.elementtree.html#xpath-support “ElementTree documentation” [xpath 1.0 standard]: http://www.w3.org/TR/xpath/ “xpath 1.0 standard” [Element objects]: http://docs.python.org/library/xml.etree.elementtree.html#element-objects “Element objects” [Clark Notation]: http://www.jclark.com/xml/xmlns.htm “Clark Notation” [glob patterns]: http://en.wikipedia.org/wiki/Glob_(programming) “glob patterns”
Import library with optionally lxml mode enabled.
- Args:
- use_lxml: Enable the lxml module for parsing XML instead of the
standard ElementTree.
This library uses Python’s standard [ElementTree] module for parsing XML by default. If use_lxml argument is given a true value, the [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.
- 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.
- Args:
- source: Path to an XML file or a string or bytes containing XML.
Does not accept an already parsed element.
- keep_clark_notation: When true, namespace information is not
removed from tag names.
strip_namespaces: When true, namespace information is removed altogether.
- Returns:
The root element of the parsed structure.
The source can either be a path to an XML file or a string containing XML. In both cases the XML is parsed into ElementTree [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 xmlns attributes. 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, you can disable this feature by using the keep_clark_notation argument.
If you want to strip namespace information altogether so that it is not included even if XML is saved, you can use the strip_namespaces argument.
```robotframework * Test Cases * Parse XML
${root} = Parse XML <root><child/></root> ${xml} = Parse XML ${CURDIR}/test.xml keep_clark_notation=True ${xml} = Parse XML ${CURDIR}/test.xml strip_namespaces=True
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 a source. > Use [Get Element] instead.
- get_element(source: Source, xpath: str = '.') Element[source]
Returns an element in the source matching the xpath.
- Args:
source: Path to an XML file, XML string or bytes, or a parsed element. xpath: XPath expression selecting the element to return.
- Returns:
The matching element.
- Raises:
AssertionError: If zero or more than one element matches.
The source can be a path to an XML file, a string containing XML, or an already parsed XML element. The xpath specifies 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.
```robotframework * Test Cases * Get element
${element} = Get Element ${XML} second ${child} = Get Element ${element} child
[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 source matching the xpath.
- Args:
source: Path to an XML file, XML string or bytes, or a parsed element. xpath: XPath expression selecting elements to return.
- Returns:
A list of matching elements. An empty list if none match.
The source can be a path to an XML file, a string containing XML, or an already parsed XML element. The xpath specifies which element to find. See the [introduction] for more details.
Elements matching the xpath are returned as a list. If no elements match, an empty list is returned. Use [Get Element] if you want to get exactly one match.
```robotframework * Test Cases * Get elements
${children} = Get Elements ${XML} third/child Length Should Be ${children} 2 ${children} = Get Elements ${XML} first/child Should Be Empty ${children}
- get_child_elements(source: Source, xpath: str = '.') list[Element][source]
Returns the child elements of the specified element as a list.
- Args:
source: Path to an XML file, XML string or bytes, or a parsed element. xpath: XPath expression selecting the parent element.
- Returns:
A list of direct child elements.
The element whose children to return is specified using source and xpath. They have exactly the same semantics as with the [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.
```robotframework * Test Cases * Get child elements
${children} = Get Child Elements ${XML} Length Should Be ${children} 4 ${children} = Get Child Elements ${XML} xpath=first Should Be Empty ${children}
- get_element_count(source: Source, xpath: str = '.') int[source]
Returns and logs how many elements the given xpath matches.
- Args:
source: Path to an XML file, XML string or bytes, or a parsed element. xpath: XPath expression selecting elements to count.
- Returns:
The number of matching elements.
Arguments source and xpath have 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.
- Args:
source: Path to an XML file, XML string or bytes, or a parsed element. xpath: XPath expression to match. message: Optional custom error message.
Arguments source and xpath have exactly the same semantics as with [Get Elements] keyword. Keyword passes if the xpath matches one or more elements in the source. The default error message can be overridden with the message argument.
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.
- Args:
source: Path to an XML file, XML string or bytes, or a parsed element. xpath: XPath expression to match. message: Optional custom error message.
Arguments source and xpath have exactly the same semantics as with [Get Elements] keyword. Keyword fails if the xpath matches any element in the source. The default error message can be overridden with the message argument.
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.
- Args:
source: Path to an XML file, XML string or bytes, or a parsed element. xpath: XPath expression selecting the element. normalize_whitespace: Normalize whitespace in the returned text.
- Returns:
All text of the element, including text of child elements.
The element whose text to return is specified using source and xpath. They have exactly the same semantics as with the [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_whitespace is 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.
```robotframework * Test Cases * Get element text
${text} = Get Element Text ${XML} first Should Be Equal ${text} text ${text} = Get Element Text ${XML} second/child Should Be Empty ${text} ${paragraph} = Get Element ${XML} html/p ${text} = Get Element Text ${paragraph} normalize_whitespace=True Should Be Equal ${text} Text with bold and italics.
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 xpath as a list.
- Args:
source: Path to an XML file, XML string or bytes, or a parsed element. xpath: XPath expression selecting elements. normalize_whitespace: Normalize whitespace in returned texts.
- Returns:
A list of texts of the matched elements.
The elements whose text to return is specified using source and xpath. They have exactly the same semantics as with the [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_whitespace option.
```robotframework * Test Cases * Get elements texts
@{texts} = Get Elements Texts ${XML} third/child normalize_whitespace=True Length Should Be ${texts} 2 Should Be Equal ${texts}[0] more text Should Be Equal ${texts}[1] ${EMPTY}
- 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.
- Args:
source: Path to an XML file, XML string or bytes, or a parsed element. expected: Expected text of the element. xpath: XPath expression selecting the element. normalize_whitespace: Normalize whitespace before comparison. message: Optional custom error message.
The element whose text is verified is specified using source and xpath. They have exactly the same semantics as with the [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_whitespace option.
The keyword passes if the text of the element is equal to the expected value, and otherwise it fails. The default error message can be overridden with the message argument. Use Element Text Should Match to verify the text against a pattern instead of an exact value.
```robotframework * Test Cases * Element text should be
Element Text Should Be ${XML} text xpath=first Element Text Should Be ${XML} ${EMPTY} xpath=second/child ${paragraph} = Get Element ${XML} xpath=html/p Element Text Should Be ${paragraph} Text with bold and italics. normalize_whitespace=True
- 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 pattern.
- Args:
source: Path to an XML file, XML string or bytes, or a parsed element. pattern: Pattern the element text must match. xpath: XPath expression selecting the element. normalize_whitespace: Normalize whitespace before matching. message: Optional custom error message.
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.
```robotframework * Test Cases * Element text should match
Element Text Should Match ${XML} t??? xpath=first ${paragraph} = Get Element ${XML} xpath=html/p Element Text Should Match ${paragraph} Text with * and *. normalize_whitespace=True
- get_element_attribute(source: Source, name: str, xpath: str = '.', default: object = None) str | object[source]
Returns the named attribute of the specified element.
- Args:
source: Path to an XML file, XML string or bytes, or a parsed element. name: Name of the attribute to return. xpath: XPath expression selecting the element. default: Value returned if the attribute does not exist.
- Returns:
The attribute value, or
defaultif the attribute is missing.
The element whose attribute to return is specified using source and xpath. They have exactly the same semantics as with the [Get Element] keyword.
The value of the attribute name of the specified element is returned. If the element does not have such element, the default value is returned instead.
```robotframework * Test Cases * Get element attribute
${attribute} = Get Element Attribute ${XML} id xpath=first Should Be Equal ${attribute} 1 ${attribute} = Get Element Attribute ${XML} xx xpath=first default=value Should Be Equal ${attribute} value
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.
- Args:
source: Path to an XML file, XML string or bytes, or a parsed element. xpath: XPath expression selecting the element.
- Returns:
A dictionary of all attributes of the element.
The element whose attributes to return is specified using source and xpath. They have exactly the same semantics as with the [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.
```robotframework * Test Cases * Get element attributes
${attributes} = Get Element Attributes ${XML} first Should Be Equal ${attributes}[id] 1 ${attributes} = Get Element Attributes ${XML} third Should Be Empty ${attributes}
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.
- Args:
source: Path to an XML file, XML string or bytes, or a parsed element. name: Name of the attribute to verify. expected: Expected attribute value. xpath: XPath expression selecting the element. message: Optional custom error message.
The element whose attribute is verified is specified using source and xpath. They have exactly the same semantics as with [Get Element] keyword.
The keyword passes if the attribute name of the element is equal to the expected value, and otherwise it fails. The default error message can be overridden with the message argument.
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].
```robotframework * Test Cases * Element attribute should be
Element Attribute Should Be ${XML} id 1 xpath=first Element Attribute Should Be ${XML} id ${NONE}
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 pattern.
- Args:
source: Path to an XML file, XML string or bytes, or a parsed element. name: Name of the attribute to verify. pattern: Pattern the attribute value must match. xpath: XPath expression selecting the element. message: Optional custom error message.
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.
```robotframework * Test Cases * Element attribute should match
Element Attribute Should Match ${XML} id ? xpath=first Element Attribute Should Match ${XML} id c*d xpath=third/second
- 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.
- Args:
source: Path to an XML file, XML string or bytes, or a parsed element. name: Name of the attribute that must not exist. xpath: XPath expression selecting the element. message: Optional custom error message.
The element whose attribute is verified is specified using source and xpath. 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 the message argument.
```robotframework * Test Cases * Element should not have attribute
Element Should Not Have Attribute ${XML} id Element Should Not Have Attribute ${XML} xxx xpath=first
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 source element is equal to expected.
- Args:
source: Element to compare. expected: Expected element as a path, string, or parsed element. exclude_children: Exclude child elements from comparison. normalize_whitespace: Normalize whitespace in text comparison. sort_children: Sort child elements by tag name before comparison.
Both source and expected can 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 source element and expected element 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 setting exclude_children to a true value. Child elements are expected to be in the same order, but that can be changed by giving sort_children a 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_whitespace to 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].
```robotframework * Test Cases * Elements should be equal
${first} = Get Element ${XML} first Elements Should Be Equal ${first} <first id=”1”>text</first> ${p} = Get Element ${XML} html/p Elements Should Be Equal ${p} <p>Text with <b>bold</b> and <i>italics</i>.</p> normalize_whitespace=True Elements Should Be Equal ${p} <p>Text with</p> exclude normalize
The last example may look a bit strange because the <p> element only has text Text 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_children is 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 source element matches expected.
- Args:
source: Element to compare. expected: Expected element as a path, string, or parsed element. exclude_children: Exclude child elements from comparison. normalize_whitespace: Normalize whitespace in text comparison. sort_children: Sort child elements by tag name before comparison.
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.
```robotframework * Test Cases * Elements should match
${first} = Get Element ${XML} first Elements Should Match ${first} <first id=”?”>*</first>
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.
- Args:
source: Path to an XML file, XML string or bytes, or a parsed element. tag: New tag name. xpath: XPath expression selecting the element to modify.
- Returns:
The root of the modified XML structure.
The element whose tag to set is specified using source and xpath. They have exactly the same semantics as with the [Get Element] keyword. The resulting XML structure is returned, and if the source is an already parsed XML structure, it is also modified in place.
```robotframework * Test Cases * Set element tag
${root} = Parse XML ${XML} Set Element Tag ${root} new Should Be Equal ${root.tag} new Set Element Tag ${root} xxx xpath=second/child Element Should Exist ${root} second/xxx Element Should Not Exist ${root} second/child
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.
- Args:
source: Path to an XML file, XML string or bytes, or a parsed element. tag: New tag name. xpath: XPath expression selecting elements to modify.
- Returns:
The root of the modified XML structure.
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.
- Args:
source: Path to an XML file, XML string or bytes, or a parsed element. text: New text for the element. tail: New tail text for the element. xpath: XPath expression selecting the element to modify.
- Returns:
The root of the modified XML structure.
The element whose text to set is specified using source and xpath. They have exactly the same semantics as with the [Get Element] keyword. The resulting XML structure is returned, and if the source is an already parsed XML structure, it is also modified in place.
Element’s text and tail text are changed only if new text and/or tail values are given. See [Element attributes] section for more information about [text] and [tail] in general.
```robotframework * Test Cases * Set element text
${root} = Parse XML ${XML} Set Element Text ${root} new text xpath=first Element Text Should Be ${root} new text xpath=first Set Element Text ${root} tail=& xpath=html/p/b Element Text Should Be ${root} Text with bold&italics. xpath=html/p normalize_whitespace=True Set Element Text ${root} slanted !! xpath=html/p/i Element Text Should Be ${root} Text with bold&slanted!! xpath=html/p normalize_whitespace=True
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.
- Args:
source: Path to an XML file, XML string or bytes, or a parsed element. text: New text for the elements. tail: New tail text for the elements. xpath: XPath expression selecting elements to modify.
- Returns:
The root of the modified XML structure.
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 name of the specified element to value.
- Args:
source: Path to an XML file, XML string or bytes, or a parsed element. name: Name of the attribute to set. value: Value to assign to the attribute. xpath: XPath expression selecting the element to modify.
- Returns:
The root of the modified XML structure.
The element whose attribute to set is specified using source and xpath. They have exactly the same semantics as with the [Get Element] keyword. The resulting XML structure is returned, and if the source is 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.
```robotframework * Test Cases * Set element attribute
${root} = Parse XML ${XML} Set Element Attribute ${root} attr value Element Attribute Should Be ${root} attr value Set Element Attribute ${root} id new xpath=first Element Attribute Should Be ${root} id new xpath=first
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 name of the specified elements to value.
- Args:
source: Path to an XML file, XML string or bytes, or a parsed element. name: Name of the attribute to set. value: Value to assign to the attribute. xpath: XPath expression selecting elements to modify.
- Returns:
The root of the modified XML structure.
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 name from the specified element.
- Args:
source: Path to an XML file, XML string or bytes, or a parsed element. name: Name of the attribute to remove. xpath: XPath expression selecting the element to modify.
- Returns:
The root of the modified XML structure.
The element whose attribute to remove is specified using source and xpath. They have exactly the same semantics as with the [Get Element] keyword. The resulting XML structure is returned, and if the source is 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.
```robotframework * Test Cases * Remove element attribute
${root} = Parse XML ${XML} Remove Element Attribute ${root} id xpath=first Element Should Not Have Attribute ${root} id xpath=first
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 name from the specified elements.
- Args:
source: Path to an XML file, XML string or bytes, or a parsed element. name: Name of the attribute to remove. xpath: XPath expression selecting elements to modify.
- Returns:
The root of the modified XML structure.
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.
- Args:
source: Path to an XML file, XML string or bytes, or a parsed element. xpath: XPath expression selecting the element to modify.
- Returns:
The root of the modified XML structure.
The element whose attributes to remove is specified using source and xpath. They have exactly the same semantics as with the [Get Element] keyword. The resulting XML structure is returned, and if the source is 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.
```robotframework * Test Cases * Remove element attributes
${root} = Parse XML ${XML} Remove Element Attributes ${root} xpath=first Element Should Not Have Attribute ${root} id xpath=first
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.
- Args:
source: Path to an XML file, XML string or bytes, or a parsed element. xpath: XPath expression selecting elements to modify.
- Returns:
The root of the modified XML structure.
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.
- Args:
source: Path to an XML file, XML string or bytes, or a parsed element. element: Element to add as a path, string, or parsed element. index: Optional position among child elements. xpath: XPath expression selecting the parent element.
- Returns:
The root of the modified XML structure.
The element to whom to add the new element is specified using source and xpath. They have exactly the same semantics as with the [Get Element] keyword. The resulting XML structure is returned, and if the source is an already parsed XML structure, it is also modified in place.
The element to 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.).
```robotframework * Test Cases * Add element
${root} = Parse XML ${XML} Add Element ${root} <new id=”x”><c1/></new> Add Element ${root} <c2/> xpath=new Add Element ${root} <c3/> index=1 xpath=new ${new} = Get Element ${root} new Elements Should Be Equal ${new} <new id=”x”><c1/><c3/><c2/></new>
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 xpath from the source structure.
- Args:
source: Path to an XML file, XML string or bytes, or a parsed element. xpath: XPath expression selecting the element to remove. remove_tail: Remove the element’s tail text.
- Returns:
The root of the modified XML structure.
- Raises:
AssertionError: If
xpathdoes not match exactly one element.
The element to remove from the source is specified with xpath using the same semantics as with the [Get Element] keyword. The resulting XML structure is returned, and if the source is an already parsed XML structure, it is also modified in place.
The keyword fails if xpath does 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_tail a true value. See the [Element attributes] section for more information about tail in general.
```robotframework * Test Cases * Remove element
${root} = Parse XML ${XML} Remove Element ${root} xpath=second Element Should Not Exist ${root} xpath=second Remove Element ${root} xpath=html/p/b remove_tail=True Element Text Should Be ${root} Text with italics. xpath=html/p normalize_whitespace=True
- remove_elements(source: Source, xpath: str = '', remove_tail: bool = False) Element[source]
Removes all elements matching xpath from the source structure.
- Args:
source: Path to an XML file, XML string or bytes, or a parsed element. xpath: XPath expression selecting elements to remove. remove_tail: Remove tail text of removed elements.
- Returns:
The root of the modified XML structure.
The elements to remove from the source are specified with xpath using the same semantics as with [Get Elements] keyword. The resulting XML structure is returned, and if the source is an already parsed XML structure, it is also modified in place.
It is not a failure if xpath matches 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_tail argument similarly as with [Remove Element].
```robotframework * Test Cases * Remove elements
${root} = Parse XML ${XML} Remove Elements ${root} xpath=*/child Element Should Not Exist ${root} xpath=second/child Element Should Not Exist ${root} xpath=third/child
- clear_element(source: Source, xpath: str = '.', clear_tail: bool = False) Element[source]
Clears the contents of the specified element.
- Args:
source: Path to an XML file, XML string or bytes, or a parsed element. xpath: XPath expression selecting the element to clear. clear_tail: Remove the element’s tail text.
- Returns:
The root of the modified XML structure.
The element to clear is specified using source and xpath. They have exactly the same semantics as with the [Get Element] keyword. The resulting XML structure is returned, and if the source is 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_tail a true value. See the [Element attributes] section for more information about tail in general.
```robotframework * Test Cases * Clear element
${root} = Parse XML ${XML} Clear Element ${root} xpath=first ${first} = Get Element ${root} xpath=first Elements Should Be Equal ${first} <first/> Clear Element ${root} xpath=html/p/b clear_tail=True Element Text Should Be ${root} Text with italics. xpath=html/p normalize_whitespace=True Clear Element ${root} Elements Should Be Equal ${root} <example/>
Use [Remove Element] to remove the whole element.
- copy_element(source: Source, xpath: str = '.') Element[source]
Returns a copy of the specified element.
- Args:
source: Path to an XML file, XML string or bytes, or a parsed element. xpath: XPath expression selecting the element to copy.
- Returns:
A deep copy of the element.
The element to copy is specified using source and xpath. They have exactly the same semantics as with the [Get Element] keyword.
If the copy or the original element is modified afterward, the changes have no effect on the other.
```robotframework * Test Cases * Copy element
${root} = Parse XML ${XML} ${elem} = Get Element ${root} xpath=first ${copy1} = Copy Element ${elem} ${copy2} = Copy Element ${root} xpath=first Set Element Text ${root} new text xpath=first Set Element Attribute ${copy1} id new Elements Should Be Equal ${elem} <first id=”1”>new text</first> Elements Should Be Equal ${copy1} <first id=”new”>text</first> Elements Should Be Equal ${copy2} <first id=”1”>text</first>
- element_to_string(source: Source, xpath: str = '.', encoding: str | None = None) bytes | str[source]
Returns the string representation of the specified element.
- Args:
source: Path to an XML file, XML string or bytes, or a parsed element. xpath: XPath expression selecting the element to convert. encoding: Optional encoding. If given, returns bytes.
- Returns:
String or bytes representation of the element.
The element to convert to a string is specified using source and xpath. They have exactly the same semantics as with the [Get Element] keyword.
The string is returned as Unicode by default. If encoding argument 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.
- Args:
source: Path to an XML file, XML string or bytes, or a parsed element. level: Log level to use. xpath: XPath expression selecting the element to log.
- Returns:
The logged string representation of the element.
The element specified with source and xpath is first converted into a string using [Element To String] keyword internally. The resulting string is then logged using the given level.
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.
- Args:
source: Path to an XML file, XML string or bytes, or a parsed element. path: Path where the XML file is saved. encoding: Encoding used when saving the file.
The element to save is specified with source using the same semantics as with the [Get Element] keyword.
The file where the element is saved is denoted with path and the encoding to use with encoding. 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.
- Args:
source: Path to an XML file, XML string or bytes, or a parsed element. expression: XPath expression to evaluate. context: XPath expression selecting the context element.
- Returns:
The result of the xpath evaluation.
- Raises:
RuntimeError: If the library is not running in lxml mode.
The element in which context the expression is executed is specified using source and context arguments. They have exactly the same semantics as source and xpath arguments have with the [Get Element] keyword.
The xpath expression to evaluate is given as expression argument. The result of the evaluation is returned as-is.
```robotframework * Test Cases * Evaluate xpath
${count} = Evaluate Xpath ${XML} count(third/*) Should Be Equal ${count} ${3} ${text} = Evaluate Xpath ${XML} string(descendant::second[last()]/@id) Should Be Equal ${text} child ${bold} = Evaluate Xpath ${XML} boolean(preceding-sibling::*[1] = ‘bold’) context=html/p/i Should Be Equal ${bold} ${True}
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>>}
- ROBOT_LIBRARY_DOC_FORMAT = 'MARKDOWN'
- ROBOT_LIBRARY_SCOPE = 'GLOBAL'
- ROBOT_LIBRARY_VERSION = '(.*)'
- 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 option 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 option 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 option 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 option 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 option 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 option 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'