text:
Table of Contents
Robot Framework is a Python-based, extensible keyword-driven test automation framework for end-to-end acceptance testing and acceptance-test-driven development (ATDD). It can be used for testing distributed, heterogeneous applications, where verification requires touching several technologies and interfaces.
Robot Framework is a generic, application and technology independent framework. It has a highly modular architecture illustrated in the diagram below.
The test data is in simple, easy-to-edit tabular format. When Robot Framework is started, it processes the test data, executes test cases and generates logs and reports. The core framework does not know anything about the target under test, and the interaction with it is handled by test libraries. Libraries can either use application interfaces directly or use lower level test tools as drivers.
Following screenshots show examples of the test data and created reports and logs.
The number one place to find more information about Robot Framework is the project web site at http://robotframework.org. This User Guide is naturally available there but you can also find more documentation, an issue tracker, downloads, source code and links to other related projects. Robot Framework is hosted on Google Code which provides excellent free services for open source projects.
There are several Robot Framework mailing lists where to ask and search for more information. The mailing list archives are open for everyone (including the search engines) and everyone can also join these lists freely. Only list members can send mails, though, and to prevent spam new users are moderated which means that it might take a little time before your first message goes through. Do not be afraid to send question to mailing lists but remember How To Ask Questions The Smart Way.
Robot Framework itself, test libraries and supporting tools distributed with it, as well as this user guide and other provided documentation have the following copyright statement.
Copyright 2008-2010 Nokia Siemens Networks Oyj Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
There are several ways to install Robot Framework:
Installation packages are available from http://downloads.robotframework.org, and source code from http://source.robotframework.org.
Robot Framework runs both on Python and Jython, and you need to have at least one of them to be able to use it. However, some of the provided installers only work with Python, so installing it is always recommended.
Starting from Robot Framework 2.5, Python 2.5 is the minimum supported Python version. Earlier versions support Python 2.3 or newer. On most UNIX-like systems, you have Python installed by default. If you are on Windows or otherwise need to install Python yourself, your best place to start is probably the Python homepage. There you can download a suitable installer and get more information about the installation and Python in general.
Robot Framework is currently not compatible with Python 3.x versions because Python 3.0 was intentionally backwards incompatible with earlier Python releases.
On Windows, and especially on Windows Vista, it is recommended to install Python to all users, and to run the installation as an administrator.
Using test libraries implemented with Java or using Java tools directly requires running Robot Framework on Jython, which in turn requires Java Runtime Environment (JRE). Jython 2.5 requires Java 1.5 or newer. Both Sun and IBM Java implementations are supported.
Starting from Robot Framework 2.5, the minimum supported Jython version is 2.5. Earlier Robot Framework versions support also Jython 2.2.
Installing Jython is a fairly easy procedure, and the first step is getting an installer from the Jython homepage. Note that the installer is an executable JAR package, which you need to run as java -jar jython_installer-<version>.jar. Depending on your system, the installer runs either in graphical or textual mode, but in both cases, the actual installation procedure is very easy.
There are three ways to install Robot Framework so that it can be run with Jython.
With all supported Jython versions, it is possible to install Robot Framework using Python and still start execution using Jython. When installing Robot Framework with Python, its installer tries to find the Jython executable on the system to create the jybot runner script correctly. Jython is found if:
Jython can be executed in the system directly (i.e. it is in the PATH).
An environment variable JYTHON_HOME is set and it points to the Jython installation directory.
The installer finds the Jython installation directory from the system. On Windows, it is searched from the C:\ and D:\ drives, and on other systems from the /usr/local and /opt directories. The directory is found if it is under the searched directories mentioned above, or one level deeper. For example, the following Jython installation directories would be found by the installer:
C:\APPS\Jython2.5.1 D:\Jython251 /usr/local/jython2.5.1 /opt/whatever/Jython251
With Jython 2.5, it is possible to install Robot Framework without having Python available by installing from source.
It is possible to do manual installation.
You can get Robot Framework source code either directly from version control or as a source distribution package that needs to be extracted somewhere. In both cases, you should have a directory containing the source code, documentation, tools, templates, and so on.
You should be able to install Robot Framework to any environment where Python runs using a source distribution. The installation is done by running the following command from the command line in the extracted directory:
python setup.py install
setup.py is a standard Python installer script. It can take several parameters allowing, for example, installation into non-default locations not requiring administrative rights. It is also used for creating distribution packages.
install.py is a custom uninstallation script for Robot Framework. It can also be used for installation, but it simply uses setup.py, and thus is totally equivalent to the command above.
It is possible to install Robot Framework 2.5 also using Jython. In this case the pybot runner script is not created.
With the installation you get a rather long output, and something like the following text should appear at the end. The actual output obviously depends on your environment.
Creating Robot Framework runner scripts... Installation directory: /usr/lib/python2.5/site-packages/robot Python executable: /usr/bin/python Jython executable: /cygdrive/c/jython2.5/jython.bat (found from system) Pybot script: /usr/bin/pybot Jybot script: /usr/bin/jybot Rebot script: /usr/bin/rebot
There are separate graphical installers for 32 bit (more common) and 64 bit Windows systems. The former installer has name in format robotframework-<version>.win32.exe and the latter robotframework-<version>.win-amd64.exe. The installation itself requires only double clicking the appropriate installer and following instructions.
After the installation you probably want to set the environment so that Robot Framework runner scripts can be executed easily. Notice that the framework is automatically installed under the Python installation and that location cannot be altered at this point.
With Python 2.6 and 2.7 you need to add the Python installation directory into PATH environment variable before running the Robot Framework installer. Setting up environment section has more information about setting environment variables.
On Windows Vista and Windows 7 installing Robot Framework requires administrator privileges. Select Run as administrator from the context menu when starting the installer.
An obvious precondition for using Easy Install is to have it installed, and you can refer to its documentation on how to do that on your operating system. The command to install Robot Framework with Easy Install depends on whether you want to install the latest version or some specific version:
easy_install robotframework # latest version easy_install robotframework==2.1.3 # specified version
If you need to use a proxy to access the Internet, you can tell Easy Install to use it by setting the http_proxy environment variable.
On Windows the pybot, jybot and rebot runner scripts are not updated when using Easy Install. A workaround is running robot_postinstall.py script manually afterwards. The installation output tells where the post-install script is located, and you can either double click it or run it from the command line. Path to the script depends on your Python installation, but the command to run should be something like python C:\Python25\Scripts\robot_postinstall.py.
Updating the runner scripts is slightly fragile process in general and it may not work with Easy Install on all environments. If the runner scripts do not work after installation, they need to fixed manually.
The One Click Installer installs Robot Framework and its preconditions Python and Jython (optional). It also automatically sets up environment so that Robot Framework runner scripts, as well as Python and Jython executables are in PATH.
The One Click Installer works only on Windows XP (32 bit).
The One Click Installer requires that you have downloaded all the required component installers and have them in the same directory with it. More detailed instructions and details about the supported installers are available at One Click Installer's documentation.
You should use this installer ONLY if you do not previously have Python or Jython installed. In that case, and also if you want to have a custom installation, you need to install the needed components separately.
If you do not want to install Python, or for some other reason do not want to use any automatic way of installing Robot Framework, you can always do it manually following these steps:
Starting from Robot Framework 2.5.2, it is also distributed as a standalone robotframework-<version>.jar, which contains both Jython and Robot Framework. It is an easy way to get everything if you do not need to run tests with Python. After you have downloaded the jar file, you can execute it like:
java -jar robotframework-2.5.2.jar --help java -jar robotframework-2.5.2.jar mytests.txt java -jar robotframework-2.5.2.jar --variable name:value mytests.txt
If you need to post-process outputs, rebot must be given as the first argument to the jar file:
java -jar robotframework-2.5.2.jar rebot --help java -jar robotframework-2.5.2.jar rebot output.xml java -jar robotframework-2.5.2.jar rebot --name Combined outputs/*.xml
When an automatic installer is used, the Robot Framework code is copied into a directory containing external Python modules. The actual location is platform-specific, but on computers with a UNIX-like operating system, it is normally something like /usr/lib/[PythonVer]/site-packages, and on Windows it is [PythonInstallationDir]\Lib\site-packages. The actual Robot Framework code is in a directory named robot, or when using Easy Install in directory robotframework[RobotVer].py[PythonVer].egg/robot.
Robot Framework runner scripts (pybot, jybot and rebot) are created and copied into another platform-specific location. On UNIX-like systems, they normally go to /usr/bin and are thus immediately available from the command line. On Windows, the operating system does not provide a similar natural place, and Python copies these scripts into [PythonInstallationDir]\Scripts.
After the installation, you probably want to make Robot Framework's runner scripts easily available from the command line. On UNIX-like systems, that should be the case automatically, but for example on Windows, it is not. In environments where runners are not available, the directory containing them must be set to the PATH environment variable.
Setting the PATH environment variable on Windows:
Python installer on Windows does not create [PythonInstallationDir]\Scripts directory, but it is automatically created during Robot Framework installation.
To verify that the installation and environment setup were successful, type:
$ pybot --version Robot Framework 2.5 (Python 2.6.5 on darwin)
To verify that Robot Framework works also with Jython, type:
$ jybot --version Robot Framework 2.5 (Jython 2.5.1 on java1.6.0_07)
In both cases, the exact version and platform information can, of course, differ from these. On Jython, you may also get some notifications from Jython package manager upon the first execution.
If Robot Framework has been installed using a source distribution, it can be uninstalled with command:
python install.py uninstall
If Robot Framework is installed from a binary distribution, it can be uninstalled via the mechanism offered by the operating system. For example, in Windows you simply go to Control Panel > Add/Remove Programs, where Robot Framework is listed under Python.
If uninstallation fails somehow or you have used Easy Install, Robot Framework can be uninstalled by removing the framework code and runner scripts manually.
The procedure when upgrading or downgrading Robot Framework depends on the versions used:
With source distributions, you first need to get the new package, and after that run the following command, which automatically takes care of the uninstallation:
python install.py reinstall
With Easy Install you can simply run:
easy_install robotframework==<new-version>
Regardless on the version or installation method, you do not need to reinstall preconditions or set the PATH environment variable again.
Robot Framework Quick Start Guide acts also as a standalone demo. It is part of the source distribution (under doc/quickstart/ directory), and also available as a separate download from project web pages.
Additionally, both external SeleniumLibrary and SwingLibrary have easily executable demos available. The former contains a simple standalone HTTP server and an application that is used as a system under test, and the latter has a small Swing application. The actual test case files and scripts for running demos on different systems are also provided.
This section covers Robot Framework's overall test data syntax. The following sections will explain how to actually create test cases, test suites and so on.
The hierarchical structure for arranging test cases is built as follows:
In addition to this, there are:
Robot Framework test data is defined in tabular format, using either the hypertext markup language (HTML), tab-separated values (TSV), plain text, or reStructuredText (reST) formats. Robot Framework selects a parser for the test data based on the file extension. The extension is case-insensitive, and the recognized extensions are .html, .htm and .xhtml for HTML, .tsv for TSV, .txt for plain text, and .rst or .rest for reStructuredText.
Different test data templates are available for HTML and TSV formats to make it easier to get started writing tests.
In HTML files, the test data is defined in separate tables (see the example below). Robot Framework recognizes these test data tables based on the text in their first cell. Everything outside recognized tables is ignored.
|Hello, world!
|Test Case
|My Test
|Example test
|My Keyword
|Another Test
|Should Be Equal
|Hello, world!
|My Keyword
|Directory Should Exist
Test data in HTML files can be edited with whichever editor you prefer, but a graphic editor, where you can actually see the tables, is recommended. There is also a tool called RIDE available that is designed for editing the test data.
HTML entity references (for example, ä) are supported. Additionally, any encoding can be used, assuming that it is specified in the data file. Normal HTML files must use the META element as in the example below:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
XHTML files should use the XML preamble as in this example:
<?xml version="1.0" encoding="Big5"?>
If no encoding is specified, Robot Framework uses ISO-8859-1 by default.
The TSV format can be used in Robot Framework's test data for all the same purposes as HTML. In a TSV file, all the data is in one large table. Test data tables are recognized from one or more asterisks (*), followed by a normal table name and an optional closing asterisks. Everything before the first recognized table is ignored similarly as data outside tables in HTML data.
|Hello, world!
|*Test Case*
|My Test
|Example test
|My Keyword
|Another Test
|Should Be Equal
|Hello, world!
|My Keyword
|Directory Should Exist
You can create and edit TSV files in any spreadsheet program, such as Microsoft Excel. Select the tab-separated format when you save the file and remember to set the file extension to .tsv. It is also a good idea to turn all automatic corrections off and configure the tool to treat all values in the file as plain text.
TSV files are relatively easy to edit with any text editor, especially if the editor supports visually separating tabs from spaces. The TSV format is also supported by RIDE.
Robot Framework parses TSV data by first splitting all the content into rows and then rows into cells on the basis of the tabular characters. Spreadsheet programs sometimes surround cells with quotes (for example, "my value") and Robot Framework removes them. Possible quotes inside the data are doubled (for example, "my ""quoted"" value") and also this is handled correctly. If you are using a spreadsheet program to create TSV data, you should not need to pay attention to this, but if you create data programmatically, you have to follow the same quoting conventions as spreadsheets.
TSV files are always expected to use UTF-8 encoding. Because ASCII is a subset of UTF-8, plain ASCII is naturally supported too.
The plain text format is technically otherwise similar to the TSV format but the separator between cells is different. The TSV format uses tabs, but in the plain text format you can use either two or more spaces or a pipe character surrounded with spaces ( | ). In both cases the test data tables must have one or more asterisk before its name similarly as with the TSV format, and everything before the first table is ignored.
The plain text format is only supported in Robot Framework 2.1.1 and newer.
Starting from Robot Framework 2.1.2 tabs in plain text files are automatically converted to two spaces. This allows using a single tab as a separator similarly as in the TSV format. Notice, however, that in the plain text format multiple tabs are considered to be a single separator whereas in the TSV format every tab would be a separator.
The number of spaces used as separator can vary, as long as there are at least two spaces, and it is thus possible to align the data nicely. This is a clear benefit over editing the TSV format in a text editor because with TSV the alignment cannot be controlled.
***Settings*** Library OperatingSystem ***Variables*** ${MESSAGE} Hello, world! ***Test Cases*** My Test [Documentation] Example test Log ${MESSAGE} My Keyword /tmp Another Test Should Be Equal ${MESSAGE} Hello, world! ***Keywords*** My Keyword [Arguments] ${path} Directory Should Exist ${path}
Because space is used as separator, all empty cells must be escaped with ${EMPTY} variable or a single backslash. Otherwise handling whitespace is not different than in other test data because leading, trailing, and consecutive spaces must always be escaped.
The biggest problem of the space delimited format is that visually separating keywords form arguments can be tricky. This is a problem especially if keywords take a lot of arguments and/or arguments contain spaces. In such cases the pipe and space delimited variant can work better because it makes the cell boundary more visible.
| *Setting* | *Value* | | Library | OperatingSystem | | *Variable* | *Value* | | ${MESSAGE} | Hello, world! | | *Test Case* | *Action* | *Argument* | | My Test | [Documentation] | Example test | | | Log | ${MESSAGE} | | | My Keyword | /tmp | | Another Test | Should Be Equal | ${MESSAGE} | Hello, world! | *Keyword* | | My Keyword | [Arguments] | ${path} | | Directory Should Exist | ${path}
A plain text file can contain test data in both space-only and space-and-pipe separated formats, but a single line must always use the same separator. Pipe and space separated lines are recognized by the mandatory leading pipe, but the pipe at the end of the line is optional. There must always be at least one space on both sides of the pipe (except at the beginning and end) but there is no need to align the pipes other than if it makes the data more clear.
There is no need to escape empty cells (other than the trailing empty cells) when using the pipe and space separated format. The only thing to take into account is that possible pipes surrounded by spaces in the actual test data must be escaped with a backslash:
| ${file count} = | Execute Command | ls -1 *.txt \| wc -l | | Should Be Equal | ${file count} | 42 |
One of the biggest benefit of the plain text format over HTML and TSV is that editing it using normal text editors is very easy. For Emacs there is even a special robot-mode.el that provides syntax highlighting and keyword completion. The plain text format is also supported by RIDE, although it only supports the space separated variant.
Similarly as with the TSV test data, plain text files are always expected to use UTF-8 encoding. As a consequence also ASCII files are supported.
reStructuredText (reST) is a easy-to-read plaintext markup syntax that is commonly used for documentation of Python projects (including Python itself, as well as this user guide). Using reST with Robot Framework allows you to mix richly formatted documents and tables that specify test data in a concise text format that is easy to work with using simple text editors, diff tools, and source control systems. The support for reStructuredText was added to Robot Framework in version 2.1.
Tools to process reStructuredText are freely available as part of the docutils project, and there is a quick reference guide that shows the most common formatting constructs including the tables used by Robot Framework. Notice that Robot Framework converts test data in reST format internally to HTML before starting to actually parse it. The data must thus follow reST syntax strictly or otherwise processing it will not succeed.
Using reST files with Robot Framework requires the Python docutils module to be installed.
In reST files, test data is defined in tables within the document, similar to the HTML format. Robot Framework identifies test data tables based on the text in the first cell and all content outsided of the recognized table types is ignored.
An example of each of the four types of test data dable is shown below using the reST Simple Tables syntax. Note that \ or .. must be used to indicate an empty cell in the first column of the table:
============ ================ ======= ======= Setting Value Value Value ============ ================ ======= ======= Library OperatingSystem ============ ================ ======= ======= ============ ================ ======= ======= Variable Value Value Value ============ ================ ======= ======= ${MESSAGE} Hello, world! ============ ================ ======= ======= ============ =================== ============ ============= Test Case Action Argument Argument ============ =================== ============ ============= My Test [Documentation] Example test \ Log ${MESSAGE} \ My Keyword /tmp \ Another Test Should Be Equal ${MESSAGE} Hello, world! ============ =================== ============ ============= ============ ====================== ============ ========== Keyword Action Argument Argument ============ ====================== ============ ========== My Keyword [Arguments] ${path} \ Directory Should Exist ${path} ============ ====================== ============ ==========
Test data in reST files can be edited with any text editor. It is recommended that the editor be configured to use a monospace font to aid with alignment of table elements.
Note that RIDE does not support direct editing of test data in reST source files.
Unlike HTML or TSV formats, Robot Framework does not parse reST files directly. Instead, docutils is used to automatically transform reST source files into temporary HTML files that are subsequently read by Robot. These temporary files are removed immediately after being read. This HTML file generation and cleanup is handled internally by Robot Framework, it does not require the user to directly invoke docutils tools.
If reST file is not syntactically correct (a malformed table for example), the reST-to-HTML conversion will not take place and no test cases will be read from that file. When this occurs, Robot Framework will show the docutils error message in it's console output showing the filename, line number, source context, and type of error.
Test data is structured in four types of tables listed below. These test data tables are identified by the first cell of the table, and the last column in the table below lists different aliases that can be used as a table name.
|Table name
|Used for
|Setting table
1) Importing test libraries, resource files and variable files
2) Defining metadata for test suites and test cases
|Setting, Settings, Metadata
|Variable table
|Defining variables that can be used elsewhere in the test data
|Variable, Variables
|Test case table
|Creating test cases from available keywords
|Test Case, Test Cases
|Keyword table
|Creating user keywords from existing lower-level keywords
|Keyword, Keywords, User Keyword, User Keywords
When Robot Framework parses the test data, it ignores:
When Robot Framework ignores some data, this data is not available in any resulting reports and, additionally, most tools used with Robot Framework also ignore them. To add information that is visible in Robot Framework outputs, or available to, for example, RIDE, place it to the documentation or other metadata of test cases or suites, or log with the Log or Comment keywords available from the BuiltIn library.
The escape character for the Robot Framework parser is the backslash (\). The escape character can be used as follows:
Robot Framework handles whitespace, such as spaces, newlines and tabs, the same way as they are handled in HTML. This means that Robot Framework:
To prevent Robot Framework from parsing data according to these rules, a backslash can be used:
Another, and often clearer, possibility for representing leading, trailing, or consecutive spaces is using built-in variable ${SPACE}. The extended variable syntax even allows syntax like ${SPACE * 8} which makes handling consecutive spaces very simple.
Possible unescaped whitespace character after the \n is ignored to allow wrapping long lines containing newlines. This means that two lines\nhere and two lines\n here are equivalent. An exception to this rule is that the whitespace character is not ignored inside the extended variable syntax.
If there is more data than readily fits a row, it possible to use ellipsis (...) to continue the previous line. In test case and user keyword tables, the ellipsis must be preceded by at least one empty cell. In settings and variable tables, it can be placed directly under the setting or variable name.
In all tables, all empty cells before the ellipsis are ignored.
Additionally, values of settings that take only one value (mainly documentations) can be split to several columns. These values will be then catenated together with spaces when the test data is parsed.
All these syntaxes are illustrated in the following examples. In the first three tables test data has not been split, and the following three illustrate how fewer columns are needed after splitting the data to several rows.
|Default Tags
|Test Case
|Documentation for this test case. This can get quite long...
|Do X
|${var} =
|Get X
|Default Tags
|Test Case
|for this
|test case.
|This can get
|Do X
|${var} =
|Get X
Empty cells before ellipsis are allowed generally only in Robot Framework 2.5.2 and newer. In earlier versions a single leading empty cell is allowed inside for loops but not otherwise.
In the plain text markup for reST tables, there are two types of table syntax that can be used to create test data. When using the Simple Tables syntax, a \ or .. is required in the first cell of a continued row in addition to the ... required by Robot Framework.
Here is an example using reST Simple Table format:
=========== ================ ============== ========== ========== Test Case Action Argument Argument Argument =========== ================ ============== ========== ========== Example [Documentation] Documentation for this test case. \ ... This can get quite long... \ [Tags] t-1 t-2 t-3 \ ... t-4 t-5 \ Do X one two three \ ... four five six \ ${var} = Get X 1 2 \ ... 3 4 5 \ ... 6 =========== ================ ============== ========== ==========
For Grid Table syntax, the first cell in a continued row may be blank, and the second cell should contain ... as with HTML tables:
+-----------+-------------------+---------------+------------+------------+ | Test Case | Action | Argument | Argument | Argument | +===========+===================+===============+============+============+ | Example | [Documentation] | Documentation | for this | test case. | +-----------+-------------------+---------------+------------+------------+ | | ... | This can get | quite | long... | +-----------+-------------------+---------------+------------+------------+ | | [Tags] | t-1 | t-2 | t-3 | +-----------+-------------------+---------------+------------+------------+ | | ... | t-4 | t-5 | | +-----------+-------------------+---------------+------------+------------+ | | Do X | one | two | three | +-----------+-------------------+---------------+------------+------------+ | | ... | four | five | six | +-----------+-------------------+---------------+------------+------------+ | | ${var} = | Get X | 1 | 2 | +-----------+-------------------+---------------+------------+------------+ | | ... | 3 | 4 | 5 | +-----------+-------------------+---------------+------------+------------+ | | ... | 6 | | | +-----------+-------------------+---------------+------------+------------+
This section describes the overall test case syntax. Organizing test cases into test suites using test case files and test suite directories is discussed in the next section.
Test cases are constructed in test case tables from the available keywords. Keywords can be imported from test libraries or resource files, or created in the keyword table of the test case file itself.
The first column in the test case table contains test case names. A test case starts from the row with something in this column and continues to the next test case name or to the end of the table. It is an error to have something between the table headers and the first test.
The second column normally has keyword names. An exception to this rule is setting variables from keyword return values, when the second and possibly also the subsequent columns contain variable names and a keyword name is located after them. In either case, columns after the keyword name contain possible arguments to the specified keyword.
|Test Case
|Valid Login
|Open Login Page
|Input Name
|Input Password
|Submit Credentials
|Welcome Page Should Be Open
|Setting Variables
|Do Something
|first argument
|second argument
|${value} =
|Get Some Value
|Should Be Equal
|Expected value
Test cases can also have their own settings. Setting names are always in the second column, where keywords normally are, and their values are in the subsequent columns. Setting names have square brackets around them to distinguish them from keywords. The available settings are listed below and explained later in this section.
|Test Case
|Test With Settings
|Another dummy test
|Hello, world!
The earlier examples have already demonstrated keywords taking different arguments, and this section discusses this important functionality more thoroughly. How to actually implement user keywords and library keywords with different arguments is discussed in separate sections.
Keywords can accept zero or more arguments, and some arguments may have default values. What arguments a keyword accepts depends on its implementation, and typically the best place to search this information is keyword's documentation. In the examples in this section the documentation is expected to be generated using the libdoc.py tool, but the same information is available on documentation generated by generic documentation tools such as javadoc.
Most keywords have a certain number of arguments that must always be given. In the keyword documentation this is denoted by specifying the argument names separated with a comma like first, second, third. The argument names actually do not matter in this case, except that they should explain what the argument does, but it is important to have exactly the same number of arguments as specified in the documentation. Using too few or too many arguments will result in an error.
The test below uses keywords Create Directory and Copy File from the OperatingSystem library. Their arguments are specified as path and source, destination which means that they take one and two arguments, respectively. The last keyword, No Operation from BuiltIn, takes no arguments.
|Test Case
|Create Directory
|Copy File
|No Operation
Arguments often have default values which can either be given or not. In the documentation the default value is typically separated from the argument name with an equal sign like name=default value, but with keywords implemented using Java there may be multiple implementations of the same keyword with different arguments instead. It is possible that all the arguments have default values, but there cannot be any positional arguments after arguments with default values.
Using default values is illustrated by the example below that uses Create File keyword which has arguments path, content=, encoding=UTF-8. Trying to use it without any arguments or more than three arguments would not work.
|Test Case
|Create File
|Create File
|Hyvä esimerkki
|Create File
|Hyvä esimerkki
It is also possible to create keywords that accept any number of arguments. These arguments can be combined with mandatory arguments and arguments with default values, but the so called varargs are always the last ones. In the documentation they typically have an asterisk before the argument name like *varargs , but there are again differences with Java libraries.
Remove Files and Join Paths keywords used in the example below have arguments *paths and base, *parts, respectively. The former can be used with any number of arguments, but the latter requires at least one argument.
|Test Case
|Remove Files
|@{paths} =
|Join Paths
When a keyword accepts more than one argument with a default value, overriding only the last one using positional argument is not possible. For example, if a keyword having arguments arg1=a, arg2=b, arg3=c is used as in the test below, its arguments arg1 and arg2 both get an empty string as value instead of their default values.
|Test Case
|Positional Arguments
|1st and 2nd
|argument get
|empty strings
|Example Keyword
To make giving only some of the arguments that expect default values easier, new named arguments syntax was added in Robot Framework 2.5. With this syntax the arguments that need to override their default values are given immediately after the required arguments in format argname=value. The arguments that should use defaults can be simply be left out. How this works in practice is illustrated by the example test below that uses the same keyword as the above example. In this example the arguments that are not specified will get their default values.
|Test Case
|Named Arguments
|Not specified
|arguments get
|default values
|Example Keyword
|Example Keyword
The named argument syntax can naturally be used with arguments accepting default values also when no arguments are left away. This can make argument meanings more clear than when only the value is shown. Naming the required arguments this way is not possible, though. Additionally, it is not possible to give first named arguments and then varargs.
The biggest limitation of the name arguments functionality is that it currently works only with user keywords and with library keywords implemented with Python that use either the static library API or the hybrid library API. It is possible that support for Java libraries and for the dynamic library API is added in the future. Until that it is possible to create user keywords that wrap the incompatible keywords.
When the named argument syntax is used with user keywords, the argument names are given without the ${} decoration. For example, user keyword with arguments ${arg1}=default, ${arg2}=second must be used like arg2=override.
The named argument syntax is used only when the part of the argument before the equal sign matches the name of an argument with a default value. This matching is started from the end of the given argument list and stopped when there is no match. In those rare cases when there are accidental matches, it is possible to use \ to escape this syntax like nomatch\=here.
The named argument syntax is both case and space sensitive. The former means that if you have an argument arg, you must use it like arg=<value>, and Arg=<value> or ARG=<value> do not work. The latter means that spaces are not allowed before the = sign, and possible spaces after it are considered part of the default value itself.
The following example demonstrates using named arguments in different scenarios, including in test library imports.
|Test Case
|Open connection
|List files
|List files
|List files
|Execute command
|ls ${options} ${path}
A totally different approach to specify arguments is embedding them into keyword names. This syntax is, at least currently, only supported by user keywords.
The test case name comes directly from the Test Case table: it is exactly what is entered into the test case column. Test cases in one test suite should have unique names. Pertaining to this, you can also use the automatic variable ${TEST_NAME} within the test itself to refer to the test name. It is available whenever a test is being executed, including all user keywords, as well as the test setup and the test teardown.
The [Documentation] setting allows you to set a free documentation for a test case. That text is shown in the command line output, as well as the resulting test logs and test reports. If the documentation is long, it can be split into several cells that are catenated together with spaces. It is possible to use simple HTML formatting and variables can be used to make the documentation dynamic. Possible non-existing variables in documentation are just left unchanged starting from Robot Framework 2.1 version.
|Test Case
|Simple documentation
|No Operation
|This documentation is a bit longer and
|it has been split into several columns.
|No Operation
|*This is bold*, _this italic_ and
|here is a link: http://robotframework.org
|No Operation
|Executed at ${HOST} by ${USER}
|No Operation
It is important that test cases have clear and descriptive names, and in that case they normally do not need any documentation. If the logic of the test case needs documenting, it is often a sign that keywords in the test case need better names and they are to be enhanced, instead of adding extra documentation. Finally, metadata, such as the environment and user information in the last example above, is often better specified using tags.
Using tags in Robot Framework is a simple, yet powerful mechanism for classifying test cases. Tags are free text and they can be used at least for the following purposes:
In this section it is only explained how to set tags for test cases, and different ways to do it are listed below. These approaches can naturally be used together.
Tags are free text, but they are normalized so that they are converted to lowercase and all spaces are removed. If a test case gets the same tag several times, other occurrences than the first one are removed. Tags can be created using variables, assuming that those variables exist.
|Force Tags
|Default Tags
|Test Case
|No own tags
|This test has tags
|owner-john, smoke, req-42
|No Operation
|With own tags
|This test has tags
|not_ready, owner-mrx, req-42
|No Operation
|Own tags with variables
|This test has tags
|host-10.0.1.42, req-42
|No Operation
|Empty own tags
|This test has tags
|No Operation
|Set Tags and Remove Tags Keywords
|This test has tags
|mytag, owner-john
|Set Tags
|Remove Tags
Robot Framework has similar test setup and teardown functionality as many other test automation frameworks. In short, a test setup is something that is executed before a test case, and a test teardown is executed after a test case. In Robot Framework setups and teardowns are just normal keywords with possible arguments.
Setup and teardown are always a single keyword. If they need to take care of multiple separate tasks, it is possible to create higher-level user keywords for that purpose. An alternative solution is executing multiple keywords using the BuiltIn keyword Run Keywords that was added in Robot Framework 2.5.
The test teardown is special in two ways. First of all, it is executed also when a test case fails, so it can be used for clean-up activities that must be done regardless of the test case status. Starting from Robot Framework 2.5, all the keywords in the teardown are also executed even if one of them fails. This continue on failure functionality can be used also with normal keywords, but inside teardowns it is on by default.
The easiest way to specify a setup or a teardown for test cases in a test case file is using the Test Setup and Test Teardown settings in the Setting table. Individual test cases can also have their own setup or teardown. They are defined with the [Setup] or [Teardown] settings in the test case table and they override possible Test Setup and Test Teardown settings. Having no keyword after a [Setup] or [Teardown] setting means having no setup or teardown.
|Test Setup
|Open Application
|App A
|Test Teardown
|Close Application
|Test Case
|Default values
|Setup and teardown
|from setting table
|Do Something
|Overridden setup
|Own setup, teardown
|from setting table
|Open Application
|App B
|Do Something
|No teardown
|Default setup, no
|teardown at all
|Do Something
|Using variables
|Setup and teardown
|given as variables
|Do Something
Often when creating use-case-like test cases, the terms precondition and postcondition are preferred over the terms setup and teardown. Robot Framework supports also this terminology, so that a precondition is a synonym to a setup and a postcondition to a teardown.
|Test Setup
|Test Precondition
|Test Teardown
|Test Postcondition
The name of the keyword to be executed as a setup or a teardown can be a variable. This facilitates having different setups or teardowns in different environments by giving the keyword name as a variable from the command line.
Test suites can have a setup and teardown of their own. A suite setup is executed before any test cases or sub test suites in that test suite, and similarly a suite teardown is executed after them.
Test templates convert the normal keyword-driven test cases into data-driven tests. Whereas the body of the normal test case is constructed from keywords and their possible arguments, test cases with template define only the arguments for the template keyword. This is illustrated by the following example test cases that are functionally fully identical.
|Test Case
|Normal test case
|Example keyword
|first argument
|second argument
|Templated test case
|Example keyword
|first argument
|second argument
As the example above illustrates, it is possible to specify the template for an individual test case using the [Template] setting. An alternative approach is using the Test Template setting in the Setting table, in which case the template is applied for all test cases in that test case file. The [Template] setting overrides the possible template set in the Setting table, and an empty value for [Template] means that the test has no template even when Test Template is used.
If a templated test case has multiple data rows in its body, like in the example below, the template is applied for all the rows. This means that the same keyword is executed multiple times, once with data on each row. Templated tests are also special so that all the rounds are executed even if there are failures. It is possible to use this kind of continue on failure mode with normal tests too, but with the templated tests the mode is on automatically.
|Test Case
|Templated test case
|Example keyword
|first round 1
|first round 2
|second round 1
|second round 2
|third round 1
|third round 2
If templates are used with for loops, the template is applied for all the steps inside the loop. The continue on failure mode is in use also in this case, which means that all the steps are executed with all the looped elements even if there are failures.
|Test Case
|Template and for
|Example keyword
|2nd arg
|1st arg
The main use case for test templates is reducing duplication with data-driven tests. Instead of repeating the same keyword with all the tests in a file, it is possible to use it only once in the Setting table. This usage is illustrated more thoroughly in the next section.
Test templates is a new feature in Robot Framework 2.5.
It is currently not possibly to specify the template keyword using variables. This limitation may be lifted in the future versions.
There are several different ways in which test cases may be written. Test cases that describe some kind of workflow may be written either in keyword-driven or behavior-driven style. Data-driven style can be used to test the same workflow with varying input data.
Workflow tests, such as the Valid Login test described earlier, are constructed from several keywords and their possible arguments. Their normal structure is that first the system is taken into the initial state (Open Login Page in the Valid Login example), then something is done to the system (Input Name, Input Password, Submit Credentials), and finally it is verified that the system behaved as expected (Welcome Page Should Be Open).
Another style to write test cases is the data-driven approach where test cases use only one higher-level keyword, normally created as a user keyword, that hides the actual test workflow. These tests are very useful when there is a need to test the same scenario with different input and/or output data. It would be possible to repeat the same keyword with every test, but the test template functionality allows specifying the keyword to use only once.
|Test Template
|Login with invalid credentials should fail
|Test Case
|User Name
|Invalid User Name
|Invalid Password
|Invalid User Name And Password
|Empty User Name
|Empty Password
|Empty User Name And Password
The above example has six separate tests, one for each invalid user/password combination, and the example below illustrates how to have only one test with all the combinations. When using test templates, all the rounds in a test are executed even if there are failures, so there is no real functional difference between these two styles. In the above example separate combinations are named so it is easier to see what they test, but having potentially large number of these tests may mess-up statistics. Which style to use depends on the context and personal preferences.
|Test Case
|User Name
|Invalid Password
|Login with invalid credentials should fail
In both of the above examples, column headers have been changed to match the data. This is possible because on the first row other cells except the first one are ignored.
It is also possible to write test cases as requirements that also non-technical project stakeholders must understand. These Executable Requirements are a corner stone of a process commonly called Acceptance Test Driven Development (ATDD).
One way to write these requirements/tests is Given-When-Then style popularized by Behavior Driven Development (BDD). When writing test cases in this style, the initial state is usually expressed with a keyword starting with word Given, the actions are described with keyword starting with When and the expectations with a keyword starting with Then. Keyword starting with And may be used if a step has more than one action.
|Test Case
|Valid Login
|Given login page is open
|When valid username and password are inserted
|and credentials are submitted
|Then welcome page should be open
Prefixes Given, When, Then and And are dropped when matching keywords are searched, if no match with the full name is found. This works for both user keywords and library keywords. For example, Given login page is open in the above example can be implemented as user keyword either with or without the word Given. Ignoring prefixes also allows using the same keyword with different prefixes. For example Welcome page should be open could also used as And welcome page should be open.
When writing concrete examples it is useful to be able pass actual data to keyword implementations. User keywords support this by allowing embedding arguments into keyword name.
Robot Framework test cases are created in test case files, which can be organized into directories. These files and directories create a hierarchical test suite structure.
Robot Framework test cases are created using test case tables in test case files. Such a file automatically creates a test suite from all the test cases it contains. There is no upper limit for how many test cases there can be, but it is recommended to have less than ten, unless the data-driven approach is used, where one test case consists of only one high-level keyword.
The following settings in the Setting table can be used to customize the test suite:
Test case files can be organized into directories, and these directories create higher-level test suites. A test suite created from a directory cannot have any test cases directly, but it contains other test suites with test cases, instead. These directories can then be placed into other directories creating an even higher-level suite. There are no limits for the structure, so test cases can be organized as needed.
When a test directory is executed, the files and directories it contains are processed recursively as follows:
If a file or directory that is processed does not contain any test cases, it is silently ignored (a message is written to the syslog) and the processing continues.
A test suite created from a directory can have similar settings as a suite created from a test case file. Because a directory alone cannot have that kind of information, it must be placed into a special test suite initialization file. Initialization files have the same structure and syntax as test case files, except that they cannot have test case tables and not all settings are supported.
An initialization file name must always be of the format __init__.ext, where the extension must match one of the supported file formats (for example, __init__.html or __init__.txt). The name format is borrowed from Python, where files named in this manner denote that a directory is a module.
The main usage for initialization files is specifying test suite related settings similarly as in test case files, but setting some test case related settings is also possible. Variables and keywords created or imported in initialization files are not available in the lower level test suites, but resource files can be used if there is a need to share them.
How to use different settings in the initialization files:
|Example suite
|Suite Setup
|Do Something
|Force Tags
|Hello, world!
|Do Something
|Some Keyword
|Another Keyword
The test suite name is constructed from the file or directory name. The name is created so that the extension is ignored, possible underscores are replaced with spaces, and names fully in lower case are title cased. For example, some_tests.html becomes Some Tests and My_test_directory becomes My test directory.
The rules for creating test suite names changed slightly in Robot Framework 2.5.
The file or directory name can contain a prefix to control the execution order of the suites. The prefix is separated from the base name by two underscores and, when constructing the actual test suite name, both the prefix and underscores are removed. For example files 01__some_tests.txt and 02__more_tests.txt create test suites Some Tests and More Tests, respectively, and the former is executed before the latter.
The documentation for a test suite is set using the Documentation setting in the Setting table. It can be used in test case files or, with higher-level suites, in test suite initialization files. Test suite documentation has exactly the same characteristics regarding to where it is shown and how it can be created as test case documentation.
|An example test suite
|documentation with
|*some* _formatting_.
|See test documentation
|for more documentation
Both the name and documentation of the top-level test suite can be overridden in test execution. This can be done with the command line options --name and --doc, respectively, as explained in section Setting metadata.
Test suites can also have other metadata than the documentation. This metadata is defined in the Setting table using the Metadata setting. Metadata set in this manner is shown in test reports and logs.
The name and value for the metadata are located in the columns following Metadata. The value is handled similarly as documentations, which means that it can be split into several cells (joined together with spaces), simple HTML formatting works and even variables can be used.
|More Info
|For more information
|about *Robot Framework*
|see http://robotframework.org
|Executed At
For top-level test suites, it is possible to set metadata also with the --metadata command line option. This is discussed in more detail in section Setting metadata.
Prior to Robot Framework 2.5 the free metadata was specified with syntax like Meta: <name>, where <name> was the metadata name and the value was defined in subsequent column. Robot Framework 2.5 still supports this old format but it will be deprecated in the future.
Not only test cases but also test suites can have a setup and a teardown. A suite setup is executed before running any of the suite's test cases or child test suites, and a test teardown is executed after them. All test suites can have a setup and a teardown; with suites created from a directory they must be specified in a test suite initialization file.
Similarly as with test cases, a suite setup and teardown are keywords that may take arguments. They are defined in the Setting table with Suite Setup and Suite Teardown settings, respectively. They also have similar synonyms, Suite Precondition and Suite Postcondition, as a test case setup and teardown have. Keyword names and possible arguments are located in the columns after the setting name.
If a suite setup fails, all test cases in it and its child test suites are immediately assigned a fail status and they are not actually executed. This makes suite setups ideal for checking preconditions that must be met before running test cases is possible.
A suite teardown is normally used for cleaning up after all the test cases have been executed. It is executed even if the setup of the same suite fails. If the suite teardown fails, all test cases in the suite are marked failed, regardless of their original execution status. Starting from Robot Framework 2.5, all the keywords in suite teardowns are executed even if one of them fails.
The name of the keyword to be executed as a setup or a teardown can be a variable. This facilitates having different setups or teardowns in different environments by giving the keyword name as a variable from the command line.
Test libraries contain those lowest-level keywords, often called library keywords, which actually interact with the system under test. All test cases always use keywords from some library, often through higher-level user keywords. This section explains how to take test libraries into use and how to use the keywords they provide. Creating test libraries is described in a separate section.
Instructions for taking test libraries into use are given in the subsections below.
Test libraries are normally imported using the Library setting in the Setting table and having the library name in the subsequent column. The library name is case-sensitive (it is the name of the module or class implementing the library and must be exactly correct), but any spaces in it are ignored. With Python libraries in modules or Java libraries in packages, the full name including the module or package name must be used.
In those cases where the library needs arguments, they are listed in the columns after the library name. It is possible to use default values, variable number of arguments, and named arguments in test library imports similarly as with arguments to keywords. Both the library name and arguments can be set using variables.
It is possible to import test libraries in test case files, resource files and test suite initialization files. In all these cases, all the keywords in the imported library are available in that file. With resource files, those keywords are also available in other files using them.
Another possibility to take a test library into use is using the keyword Import Library from the BuiltIn library. This keyword takes the library name and possible arguments similarly as the Library setting. Keywords from the imported library are available in the test suite where the Import Library keyword was used. This approach is useful in cases where the library is not available when the test execution starts and only some other keywords make it available.
|Test Case
|Do Something
|Import Library
|KW From Mylibrary
The most common way to specify a test library to import is using its name, like it has been done in all the examples in this section. In these cases Robot Framework tries to find the class or module implementing the library from the library search path. Basically, this means that the library code and all its possible dependencies must be in PYTHONPATH or, when running tests on Jython, in a CLASSPATH. Setting the library search path is explained in a section of its own. Libraries can also set the search path automatically or have special instructions on how to do it. All standard libraries, for example, are in the library search path automatically.
The biggest benefit of this approach is that when the library search path has been configured, often using a custom start-up script, normal users do not need to think where libraries actually are installed. The drawback is that getting your own, possible very simple, libraries into the search path may require some additional configuration.
Another mechanism for specifying the library to import is using a path to it in the file system. This path is considered relative to the directory where current test data file is situated similarly as paths to resource and variable files. The main benefit of this approach is that there is no need to configure the library search path.
If the library is a file, the path to it must contain extension. For Python libraries the extension is naturally .py and for Java libraries it can either be .class or .java, but the class file must always be available. If Python library is implemented as a directory, the path to it must have a trailing forward slash (/). Following examples demonstrate these different usages.
A limitation of this approach is that libraries implemented as Python classes must be in a module with the same name as the class. Additionally, importing libraries distributed in JAR or ZIP packages is not possible with this mechanism.
The library name is shown in test logs before keyword names, and if multiple keywords have the same name, they must be used so that the keyword name is prefixed with the library name. The library name is got normally from the module or class name implementing it, but there are some situations where changing it is desirable:
The basic syntax for specifying the new name is having the text WITH NAME (case-insensitive) after the library name and then having the new name in the next cell. The specified name is shown in logs and must be used in the test data when using keywords' full name (LibraryName.Keyword Name).
Possible arguments to the library are placed into cells between the original library name and the WITH NAME text. The following example illustrates how the same library can be imported several times with different arguments:
|Test Case
|My Test
|LocalLib.Some Keyword
|some arg
|second arg
|RemoteLib.Some Keyword
|another arg
|LocalLib.Another Keyword
Setting a custom name to a test library works both when importing a library in the Setting table and when using the Import Library keyword.
Some test libraries are distributed with Robot Framework and these libraries are called standard libraries. These are the available standard libraries:
The BuiltIn library is special, because it is taken into use automatically and thus its keywords are always available. Other standard libraries need to be imported in the same way as any other libraries, but there is no need to install them. Additionally, they work when running tests both with Python and Jython (with the Screenshot library as an exception).
New standard libraries can, and will, be added in the future. If you have an idea for a new standard library, or even have one that could be incorporated immediately, please contact Robot Framework developers. In general, a library is a good candidate to be added into standard libraries if it is generic, works on both Python and Jython without any external dependencies, and is adequately tested and documented.
The BuiltIn library provides a set of generic keywords needed often. It is imported automatically and thus always available. The provided keywords can be used, for example, for verifications (e.g. Should Be Equal, Should Contain), conversions (e.g. Convert To Integer) and for various other purposes (e.g. Log, Sleep, Run Keyword If, Set Global Variable).
The names of the keywords in the BuiltIn library have been renamed in Robot Framework version 1.8. All the old keywords still work, but the long names (the names visible in log files) of the keywords that are deprecated begin with DeprecatedBuiltIn. (for example, DeprecatedBuiltIn.Equals). It is highly recommended to use the new names of the keywords as the old versions will be removed altogether in the future.
For more information, see the BuiltIn library documentation.
The OperatingSystem library enables various operating system related tasks to be performed in the system where Robot Framework is running. It can, among other things, execute commands (e.g. Run), create and remove files and directories (e.g. Create File, Remove Directory), check whether files or directories exists or contain something (e.g. File Should Exist, Directory Should Be Empty) and manipulate environment variables (e.g. Set Environment Variable).
The names of the keywords in the OperatingSystem library have been renamed in Robot Framework 1.8 similarly as the names of the BuiltIn keywords.
For more information, see the OperatingSystem library documentation.
The Telnet library makes it possible to connect to Telnet servers and execute commands on the opened connections.
For more information, see the Telnet library documentation.
The Collections library 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).
For more information, see the Collections library documentation.
The String library enables manipulating strings (e.g. Replace String With Regexp, Split To Lines) and verifying their contents (e.g. Should Be String).
For more information, see the String library documentation. This library is new in Robot Framework 2.1.
The Dialogs library provides means for pausing the test execution and getting input from users. The dialogs are slightly different depending on are tests run on Python or Jython but they provide the same functionality.
For more information, see the Dialogs library documentation. This library is new in Robot Framework 2.1.
The Screenshot library has keywords to capture and store screenshots of the whole desktop. This library is implemented with Java AWT APIs, so it can be used only when running Robot Framework on Jython.
For more information, see the Screenshot library documentation.
The Remote library is totally different than the other standard libraries. It does not have any keywords of its own but it works as a proxy between Robot Framework and actual test library implementations. These libraries can be running on other machines than the core framework and can even be implemented using languages not supported by Robot Framework natively.
See separate Remote library interface section for more information about the concept. This library is new in Robot Framework 2.1.
Any test library that is not one of the standard libraries is, by definition, an external library. Robot Framework developers provide some generic libraries, such as SeleniumLibrary and SwingLibrary, which are not packaged with the framework itself, because they require external dependencies. Generic libraries can also be provided by other parties, and most teams have also some custom libraries only for themselves.
Different external libraries can have a totally different mechanism for installing and introducing them. Quite often they also require some other dependencies to be installed separately. All libraries should have clear instructions on this and preferably automate the installation.
See Creating test libraries section for more information about how to create new test libraries for your own or generic usage.
Variables are an integral feature of Robot Framework, and they can be used in most places in test data. Most commonly, they are used in arguments for keywords in test case tables and keyword tables, but also all settings allow variables in their values. A normal keyword name cannot be specified with a variable, but the BuiltIn keyword Run Keyword can be used to get the same effect.
Robot Framework itself has two kinds of variables, scalars and lists, and they have the syntaxes ${SCALAR} and @{LIST}, respectively. In addition to this, environment variables can be used directly with the syntax %{VARIABLE}.
Using scalar variables and list variables with the same base name, for example ${VAR} and @{VAR}, has been deprecated in Robot Framework 2.5. For more information, see issue 484 in the issue tracker.
The use of variables is recommended in the following cases:
If a nonexistent variable is used in the test data, the keyword using it fails. If the same syntax that is used for variables is needed as a literal string, it must be escaped with a backslash as in \${NAME}.
Different variable types are briefly described in this section. The creation and usage of variables is described in more detail in the following subsections.
Robot Framework variables, similarly as keywords, are case-insensitive, and also spaces and underscores are ignored. However, it is recommended to use all capital letters with global variables (for example, ${PATH} or ${TWO_WORDS}) and small letters with variables that are only available in certain test cases or user keywords (for example, ${my_var} or ${myVar}). Much more importantly, though, cases should be used consistently.
Unlike in some programming languages where similar variable syntax is used, curly braces ({ and }) are mandatory in Robot Framework test data. Basically, variable names can have any characters between the curly braces. However, using only alphabetic characters from a to z, numbers, underscore and space is recommended, and it is even a requirement for using the extended variable syntax.
When scalar variables are used in the test data, they are replaced with the value they are assigned to. While scalar variables are most commonly used for simple strings, you can assign any objects, including lists, to them. The scalar variable syntax, for example ${NAME}, should be familiar to most users, as it is also used, for example, in shell scripts and Perl programming language.
The example below illustrates the usage of scalar variables. Assuming that the variables ${GREET} and ${NAME} are available and assigned to strings Hello and world, respectively, both the example test cases are equivalent.
|Test Case
|Hello, world!!
When a scalar variable is used as the only value in a test data cell, the scalar variable is replaced with the value it has. The value may be any object. When a scalar variable is used in a test data cell with anything else (constant strings or other variables), its value is first converted into a Unicode string and then catenated to whatever is in that cell. Converting the value into a string means that the object's method __unicode__ (in Python, with __str__ as a fallback) or toString (in Java) is called.
Variable values are used as-is without conversions also when passing arguments to keywords using the named arguments syntax like argname=${var}.
The example below demonstrates the difference between having a variable in a cell alone or with other content. First, let us assume that we have a variable ${STR} set to a string Hello, world! and ${OBJ} set to an instance of the following Java object:
public class MyObj {
public String toString() {
return "Hi, tellus!";
With these two variables set, we then have the following test data:
|Test Case
|I said "${STR}"
|You said "${OBJ}"
Finally, when this test data is executed, different keywords receive the arguments as explained below:
Converting variables to Unicode obviously fails if the variable cannot be represented as Unicode. This can happen, for example, if you try to use byte sequences as arguments to keywords so that you catenate the values together like ${byte1}${byte2}. A workaround is creating a variable that contains the whole value and using it alone in the cell (e.g. ${bytes}) because then the value is used as-is.
List variables are compound variables that can have several values assigned to them. In short, they are always lists and can contain an unlimited number of entries (also empty lists are possible). The main benefit of list variables is that they allow you to assign a name for a larger data set. While list variables normally contain only strings, other content is also possible.
When you use a list variable in test data, then the elements of the list are inserted as new cells in the test data. Thus, if the list variable contains two elements, the cell containing the list variable is turned into two cells with the content of the list variable. Note that cells with list variables should not contain other content. The list variable syntax, @{NAME}, is borrowed from Perl.
Assuming that the list variable @{USER} is set to the value ['robot','secret'], the following two test cases are equivalent.
|Test Case
|User Name
|List Variable
It is also possible to access a certain value from the list variable with the syntax @{NAME}[i], where i is the index of the selected value. Indexes start from zero, and trying to access a value with too large an index causes an error. List items accessed in this manner can be used similarly as scalar variables:
|Test Case
|Title Should Be
|Welcome robot!
|List Variable
|Title Should Be
|Welcome @{USER}[0]!
It is possible to use list variables as scalar variables containing lists simply by replacing @ with $. This makes it possible to use list variables with list related keywords, for example, from from BuiltIn and Collections libraries. This feature works only if there is no scalar variable with same basename as the list variable has. In these cases the scalar variable has precedence and its value is used instead.
|Test Case
|@{items} =
|Create List
|Length Should Be
|Append To List
|Length Should Be
|Remove From List
|Length Should Be
|Log Many
List variables can be used only with some of the settings. They can be used in arguments to imported libraries and variable files, but library and variable file names themselves cannot be list variables. Also with setups and teardowns list variable can not be used as the name of the keyword, but can be used in arguments. With tag related settings they can be used freely. Using scalar variables is possible in those places where list variables are not supported.
|# This works
|# This works
|# This does not work
|Suite Setup
|Some Keyword
|# This works
|Suite Setup
|# This works
|Suite Setup
|# This does not work
|Default Tags
|# This works
Robot Framework allows using environment variables in the test data using the syntax %{ENV_VAR_NAME}. They are limited to string values.
Environment variables set in the operating system before the test execution are available during it, and it is possible to create new ones with the keyword Set Environment Variable or delete existing ones with the keyword Delete Environment Variable, both available in the OperatingSystem library. Because environment variables are global, environment variables set in one test case can be used in other test cases executed after it. However, changes to environment variables are not effective after the test execution.
|Test Case
|Env Variables
|Current user: %{USER}
Variables can spring into existence from different sources as described in the subsections below.
The most common source for variables are Variable tables in test case files and resource files. Variable tables are convenient, because they allow creating variables in the same place as the rest of the test data, and the needed syntax is very simple. Their main disadvantage is that they only enable assigning variables into strings or a list of strings. If other value types are needed, variable files are probably a better option.
The simplest possible variable assignment is setting a string into a scalar variable. This is done by giving the variable name (including ${}) in the first column of the Variable table and the value in the second one. If the second column is empty, an empty string is set as a value. Also an already defined variable can be used in the value.
|Robot Framework
It is also possible, but not obligatory, to use the equals sign = after the variable name to make assigning variables slightly more explicit.
|Robot Framework
Creating list variables is as easy as creating scalar variables. Again, the variable name is in the first column of the Variable table and values in the subsequent columns. A list variable can have any number of values, starting from zero, and if many values are needed, they can be split into several rows.
Variable files are the most powerful mechanism for creating different kind of variables. It is possible to assign variables to any object using them, and they also enable creating variables dynamically. The variable file syntax and taking variable files into use is explained in section Resource and variable files.
Variables can be set from the command line either individually with the --variable (-v) option or using a variable file with the --variablefile (-V) option. Variables set from the command line are globally available for all executed test data files, and they also override possible variables with the same names in the Variable table and in variable files imported in the test data.
The syntax for setting individual variables is --variable name:value, where name is the name of the variable without ${} and value is its value. Several variables can be set by using this option several times. Only scalar variables can be set using this syntax and they can only get string values. Many special characters are difficult to represent in the command line, but they can be escaped with the --escape option.
--variable EXAMPLE:value
--variable HOST:localhost:7272 --variable USER:robot
--variable ESCAPED:Qquotes_and_spacesQ --escape quot:Q --escape space:_
In the examples above, variables are set so that
The basic syntax for taking variable files into use from the command line is --variablefile path/to/variables.py, and Taking variable files into use section has more details. What variables actually are created depends on what variables there are in the referenced variable file.
If both variable files and individual variables are given from the command line, the latter have higher priority. Additionally, if multiple variable files have same variables, the ones in the file specified first are taken into use.
Return values from keywords can also be set into variables. This allows communication between different keywords even in different test libraries. The syntax for a simple case is illustrated in the example below:
|Test Case
|${x} =
|Get X
|an argument
|We got ${x}!
In the example above, the value returned by the Get X keyword is first set into the variable ${x} and then used by the Log keyword. This syntax works in all cases where a keywords returns something, and the variable is set to whatever value returned by the keyword. Having the equals sign = after the variable name is not obligatory, but recommended, because it makes the assignment more explicit.
If a keyword returns a list, it is also possible to assign the return value into several scalar variables and/or one list variable. Starting from Robot Framework 2.5 this works with all list-like objects, but prior to it only Python lists and tuples and Java arrays were supported.
|Test Case
|Return Multiple
|${scalar} =
|Get 3
|${c} =
|Get 3
|@{rest} =
|Get 3
|@{list} =
|Get 3
Assuming that the keyword Get 3 returns a list [1, 2, 3], the following variables are created:
Variables set in this manner are otherwise similar to any other variables, but they are available only within the scope of the test case or keyword where they are created. Thus it is not possible, for example, to set a variable in one test case and use it in another. This is because, in general, automated test cases should not depend on each other, and accidentally setting a variable that is used elsewhere could cause hard-to-debug errors. If there is a genuine need for setting a variable in one test case and using it in another, it is possible to use built-in keywords as explained in the next section.
The BuiltIn library has keywords Set Test Variable, Set Suite Variable and Set Global Variable which can be used for setting variables dynamically during the test execution. If a variable already exists within the new scope, its value will be overwritten, and otherwise a new variable is created.
Variables set with Set Test Variable keyword are available everywhere within the scope of the currently executed test case. For example, if you set a variable in a user keyword, it is available both in the test case level and also in all other user keywords used in the current test. Other test cases will not see variables set with this keyword.
Variables set with Set Suite Variable keyword are available everywhere within the scope of the currently executed test suite. Setting variables with this keyword thus has the same effect as creating them using the Variable table in the test data file or importing them from variable files. Other test suites, including possible child test suites, will not see variables set with this keyword.
Variables set with Set Global Variable keyword are globally available in all test cases and suites executed after setting them. Setting variables with this keyword thus has the same effect as creating from the command line using the options --variable or --variablefile. Because this keyword can change variables everywhere, it should be used with care.
Robot Framework provides some built-in variables that are available automatically.
Built-in variables related to the operating system ease making the test data operating-system-agnostic.
|An absolute path to the directory where the test data file is located. This variable is case-sensitive.
|An absolute path to the system temporary directory. In UNIX-like systems this is typically /tmp, and in Windows c:\Documents and Settings\<user>\Local Settings\Temp.
|An absolute path to the directory where test execution was started from. New in Robot Framework 2.1.
|The system directory path separator. / in UNIX-like systems, \ in Windows.
|The system path element separator. : in UNIX-like systems and ; in Windows.
|Test Case
|Create File
|Some text here
|Set Environment Variable
The variable syntax can be used for creating both integers and floating point numbers, as illustrated in the example below. This is useful when a keyword expects to get an actual number, and not a string that just looks like a number, as an argument.
|Test Case
|Example 1A
|# Connect gets two strings as arguments
|Example 1B
|# Connect gets a string and an integer
|Example 2
|Do X
|# Do X gets floating point numbers 3.14 and -0.0001
Also Boolean values and Python None and Java null can be created using the variable syntax similarly as numbers.
|Test Case
|Set Status
|# Set Status gets Boolean true as an argument
|Create Y
|# Create Y gets a string and Boolean false
|Do XYZ
|# Do XYZ gets Python None as an argument
|${ret} =
|Get Value
|# Checking that Get Value returns Java null
|Should Be Equal
These variables are case-insensitive, so for example ${True} and ${true} are equivalent. Additionally, ${None} and ${null} are synonyms, because when running tests on the Jython interpreter, Jython automatically converts None and null to the correct format when necessary.
It is possible to create spaces and empty strings using variables ${SPACE} and ${EMPTY}, respectively. These variables are useful, for example, when there would otherwise be a need to escape spaces or empty cells with a backslash. If more than one space is needed, it is possible to use the extended variable syntax like ${SPACE * 5}. In the following exmaple, Should Be Equal keyword gets identical arguments but those using variables are easier to understand than those using backslashes.
|Test Case
|One Space
|Should Be Equal
|\ \
|Four Spaces
|Should Be Equal
|\ \ \ \ \
|Ten Spaces
|Should Be Equal
|\ \ \ \ \ \ \ \ \ \ \
|Quoted Space
|Should Be Equal
|" "
|Quoted Spaces
|Should Be Equal
|" \ "
|Should Be Equal
Some automatic variables can also be used in the test data. These variables can have different values during the test execution and some of them are not even available all the time.
|The name of the current test case.
|Test case
|Contains the tags of the current test case in alphabetical order.
|Test case
|The status of the current test case, either PASS or FAIL.
|Test teardown
|The possible error message of the current test case.
|Test teardown
|The name of the previous test case, or an empty string if no tests have been executed yet.
|The status of the previous test case: either PASS, FAIL or an empty string when no tests have been executed.
|The possible error message of the previous test case.
|The full name of the current test suite.
|An absolute path to the suite file or directory. New in Robot Framework 2.5.
|The status of the current test case, either PASS or FAIL.
|Suite teardown
|The full message of the current test suite, including statistics.
|Suite teardown
|An absolute path to the current output file. Has different values during execution when outputs are split.
|An absolute path to the current log file or string NONE when no log file is created. Has different values during execution when outputs are split.
|An absolute path to the report file or string NONE when no report is created.
|An absolute path to the summary file or string NONE when no summary is created.
|An absolute path to the debug file or string NONE when no debug file is created.
|An absolute path to the output directory.
Variables coming from different sources have different priorities and are available in different scopes.
Variables from the command line
Variables set in the command line have the highest priority of all variables that can be set before the actual test execution starts. They override possible variables created in Variable tables in test case files, as well as in resource and variable files imported in the test data.
Individually set variables (--variable option) override the variables set using variable files (--variablefile option). Additionally, if multiple variable files have same variables, the ones in the file specified first have the highest priority.
Variable table in a test case file
Variables created using the Variable table in a test case file are available for all the test cases in that file. These variables override possible variables with same names in imported resource and variable files.
Variables created in the variable tables are available in all other tables in the file where they are created. This means that they can be used also in the Setting table, for example, for importing more variables from resource and variable files.
Imported resource and variable files
Variables imported from the resource and variable files have the lowest priority of all variables created in the test data. Variables from resource files and variable files have the same priority. If several resource and/or variable file have same variables, the ones in the file imported first are taken into use.
If a resource file imports resource files or variable files, variables in its own Variable table have a higher priority than variables it imports. All these variables are available for files that import this resource file.
Note that variables imported from resource and variable files are not available in the Variable table of the file that imports them. This is due to the Variable table being processed before the Setting table where the resource files and variable files are imported.
Variables set during test execution
Variables set during the test execution either using return values from keywords or built-in keywords Set Test/Suite/Global Variable always override possible existing variables in the scope where they are set. In a sense they thus have the highest priority, but on the other hand they do not affect variables outside the scope they are defined.
Built-in variables
Built-in variables like ${TEMPDIR} and ${TEST_NAME} have the highest priority of all variables. They cannot be overridden using Variable table or from command line, but even they can be reset during the test execution. An exception to this rule are number variables, which are resolved dynamically if no variable is found otherwise. They can thus be overridden, but that is generally a bad idea. Additionally ${CURDIR} is special because it is replaced already during the test data processing time.
Depending on where and how they are created, variables can have a global, test suite, test case or user keyword scope.
Global scope
Global variables are available everywhere in the test data. These variables are normally set from the command line with the --variable and --variablefile options, but it is also possible to create new global variables or change the existing ones with the BuiltIn keyword Set Global Variable anywhere in the test data. Additionally also built-in variables are global.
It is recommended to use capital letters with all global variables.
Test suite scope
Variables with the test suite scope are available anywhere in the test suite where they are defined or imported. They can be created in Variable tables, imported from resource and variable files, or set during the test execution using the BuiltIn keyword Set Suite Variable.
The test suite scope is not recursive, which means that variables available in a higher-level test suite are not available in lower-level suites. If necessary, resource and variable files can be used for sharing variables.
Since these variables can be considered global in the test suite where they are used, it is recommended to use capital letters also with them.
Test case scope
Variables created in test cases from the return values of keywords have a test case scope and they are available only in that test case. Another possibility to create them is using the BuiltIn keyword Set Test Variable anywhere in that particular test case. Test case variables are local and should use lower-case letters.
User keyword scope
User keywords get their own variables from arguments passed to them and return values from the keywords they use. Also these variables are local and should use lower-case letters.
Extended variable syntax can be used with objects set into scalar variables. It allows accessing the attributes of the object (for example, ${obj.name} or ${obj.some_attr}), and even calling its methods (for example, ${obj.get_name()} or ${obj.getSomething('arg')}).
Extended variable syntax is a powerful feature, but it should be used with care. Accessing attributes is normally not a problem, on the contrary, as one variable with an object having several attributes is often better than having several variables. On the other hand, calling methods, especially when they are used with arguments, can make the test data complicated. If that happens, it is recommended to move the code into a test library.
The most common usages of extended variable syntax are illustrated in the example below. First assume that we have the following variable file and test case:
class MyObject:
def __init__(self, name):
self.name = name
def greet(self, who):
return '%s says hello to %s' % (self.name, who)
def __str__(self):
return self.name
OBJECT = MyObject('Robot')
DICTIONARY = { 1: 'one', 2: 'two', 3: 'three'}
|Test Case
When this test data is executed, the keywords get the arguments as explained below:
The extended variable syntax is evaluated in the following order:
If the object that is used is implemented with Java, the extended variable syntax allows you to access attributes using so-called bean properties. In essence, this means that if you have an object with the getName method set into a variable ${OBJ}, then the syntax ${OBJ.name} is equivalent to, but clearer than ${OBJ.getName()}. Thus the Python object used in the previous example could be replaced with the following Java implementation:
public class MyObject:
private String name;
public MyObject(String name) {
name = name;
public String getName() {
return name;
public String greet(String who) {
return name + " says hello to " + who;
public String toString() {
return name;
Many standard Python objects, including strings and numbers, have methods that can be used with the extended variable syntax either explicitly or implicitly. Sometimes this can be really useful and reduce the need for setting temporary variables, but it is also easy to overuse it and create really cryptic test data. Following examples show few pretty good usages.
|Test Case
|${string} =
|Set Variable
|# Logs 'ABC'
|${string * 2}
|# Logs 'abcabc'
|${number} =
|Set Variable
|${number * 10}
|# Logs -20
|# Logs 2
Note that even though abs(number) is recommended over number.__abs__() in normal Python code, using ${abs(number)} does not work. This is because the variable name must be in the beginning of the extended syntax. Using __xxx__ methods in the test data like this is already a bit questionable, and it is normally better to move this kind of logic into test libraries.
Variables are allowed also inside variables, and when this syntax is used, variables are resolved from the inside out. For example, if you have a variable ${var${x}}, then ${x} is resolved first. If it has the value name, the final value is then the value of the variable ${varname}. There can be several nested variables, but resolving the outermost fails, if any of them does not exist.
In the example below, Do X gets the value ${JOHN_HOME} or ${JANE_HOME}, depending on if Get Name returns john or jane. If it returns something else, resolving ${${name}_HOME} fails.
|Test Case
|${name} =
|Get Name
|Do X
Keyword tables are used to create new higher-level keywords by combining existing keywords together. These keywords are called user keywords to differentiate them from lowest level library keywords that are implemented in test libraries. The syntax for creating user keywords is very close to the syntax for creating test cases, which makes it easy to learn.
In many ways, the overall user keyword syntax is identical to the test case syntax. User keywords are created in keyword tables which differ from test case tables only by the name that is used to identify them. User keyword names are in the first column similarly as test cases names. Also user keywords are created from keywords, either from keywords in test libraries or other user keywords. Keyword names are normally in the second column, but when setting variables from keyword return values, they are in the subsequent columns.
|Open Login Page
|Open Browser
|Title Should Be
|Login Page
|Title Should Start With
|${title} =
|Get Title
|Should Start With
Most user keywords take some arguments. This important feature is used already in the second example above, and it is explained in detail later in this section, similarly as user keyword return values.
User keywords can be created in test case files, resource files, and test suite initialization files. Keywords created in resource files are available for files using them, whereas other keywords are only available in the files where they are created.
User keywords can have similar settings as test cases, and they have the same square bracket syntax separating them from keyword names. All available settings are listed below and explained later in this section.
The user keyword name is defined in the first column of the user keyword table. Of course, the name should be descriptive, and it is acceptable to have quite long keyword names. Actually, when creating use-case-like test cases, the highest-level keywords are often formulated as sentences or even paragraphs.
User keywords can have a documentation that is set with the [Documentation] setting, exactly as test case documentation. This setting documents the user keyword in the test data. It is also shown in a more formal keyword documentation, which the libdoc.py tool can create from resource files. Finally, the first line of the documentation, everything until the first \n sequence, is shown as a keyword documentation in test logs.
Sometimes keywords need to be removed, replaced with new ones, or deprecated for other reasons. User keywords can be marked deprecated by starting the documentation with *DEPRECATED*, which will cause a warning when the keyoword is used. For more information, see Deprecating keywords section.
Most user keywords need to take some arguments. The syntax for specifying them is probably the most complicated feature normally needed with Robot Framework, but even that is relatively easy, particularly in most common cases. Arguments are normally specified with the [Arguments] setting, and argument names use the same syntax as variables, for example ${arg}.
The simplest way to specify arguments (apart from not having them at all) is using only positional arguments. In most cases, this is all that is needed.
The syntax is such that first the [Arguments] setting is given and then argument names are defined in the subsequent cells. Each argument is in its own cell, using the same syntax as with variables. The keyword must be used with as many arguments as there are argument names in its signature. The actual argument names do not matter to the framework, but from users' perspective they should should be as descriptive as possible. It is recommended to use lower-case letters in variable names, either as ${my_arg}, ${my arg} or ${myArg}.
|One Argument
|Got argument ${arg_name}
|Three Arguments
|1st argument: ${arg1}
|2nd argument: ${arg2}
|3rd argument: ${arg3}
Positional arguments are probably sufficient in most situations. However, sometimes it is useful to be able to have a keyword that takes a different number of arguments and has default values for those that are not given. User keywords also allow this, and the needed new syntax does not add very much to the already discussed basic syntax. In short, default values are added to arguments, so that first there is the equals sign (=) and then the value, for example ${arg}=default. There can be many arguments with defaults, but they all must be given after the normal positional arguments.
The syntax for default values is space sensitive. Spaces before the = sign are not allowed, and possible spaces after it are considered part of the default value itself.
|One Argument With Default Value
|${arg}=default value
|This keyword takes
|0-1 arguments
|Got argument ${arg}
|Two Arguments With Defaults
|${arg1}=default 1
|${arg2}=default 2
|This keyword takes
|0-2 arguments
|1st argument ${arg1}
|2nd argument ${arg2}
|One Required And One With Default
|This keyword takes
|1-2 arguments
|Required: ${required}
|Optional: ${optional}
When a keyword accepts several arguments with default values and only some of them needs to be overridden, it is often handy to use the named arguments syntax. When this syntax is used with user keywords, the arguments are specified without the ${} decoration. For example, the second keyword above could be used like below and ${arg1} would still get its default value.
|Test Case
|Two Arguments With Defaults
|arg2=new value
As all Pythonistas must have already noticed, the syntax for specifying default arguments is heavily inspired by Python syntax for function default values.
Sometimes even default values are not enough and there is a need for a keyword accepting any number of arguments. User keywords support also this. All that is needed is having list variable such as @{varargs} as the last argument in the keyword signature. This syntax can be combined with the previously described positional arguments and default values, and at the end the list variable gets all the leftover arguments that do not match other arguments. The list variable can thus have any number of items, even zero.
|Any Number Of Arguments
|Log Many
|One Or More Arguments
|Log Many
|Required, Default, Varargs
|Required: ${req}
|Optional: ${opt}
Notice that if the last keyword above is used with more than one argument, the second argument ${opt} always gets the given value instead of the default value. This happens even if the given value is empty. The last example also illustrates how a variable number of arguments accepted by a user keyword can be used in a for loop. This combination of two rather advanced functions can sometimes be very useful.
Again, Pythonistas probably notice that the variable number of arguments syntax is very close to the one in Python.
Robot Framework has, starting from 2.1.1 version, also another approach to pass arguments to user keywords than specifying them in cells after the keyword name as explained in the previous section. This method is based on embedding the arguments directly into the keyword name, and its main benefit is making it easier to use real and clear sentences as keywords. It has always been possible to use keywords like Select dog from list and Selects cat from list, but all such keywords must have been implemented separately. The idea of embedding arguments into the keyword name is that all you need is a keyword with name like Select ${animal} from list.
|Select ${animal} from list
|Open Page
|Pet Selection
|Select Item From List
Keywords using embedded arguments cannot take any "normal" arguments (specified with [Arguments] setting) but otherwise they are created just like other user keywords. The arguments used in the name will naturally be available inside the keyword and they have different value depending on how the keyword is called. For example ${animal} in the previous has value dog if the keyword is used like Select dog from list. Obviously it is not mandatory to use all these arguments inside the keyword, and they can thus be used as wildcards.
These kind of keywords are also used the same way as other keywords except that spaces and underscores are not ignored in their names. They are, however, case-insensitive like other keywords. For example the keyword in the example above could be used like select x from list but not like Select x fromlist.
Embedded arguments do not support default values or variable number of arguments like traditional arguments do. Using variables when calling these keywords is possible but that can reduce readability. Notice also that embedded arguments only work with user keywords.
One tricky part in using embedded arguments is making sure that the values used when calling the keyword match the correct arguments. This is a problem especially if there are multiple arguments and characters separating them may also appear in the given values. For example Select ${city} ${team} leads to unexpected results if used with city containing too parts like Select Los Angeles Lakers. One solution to this problem is quoting the arguments like Select "${city}" "${team}" or separating them from each others otherwise, but sometimes it is easiest to just use positional arguments instead.
The same problem occurs often when trying to create keywords ignoring given/when/then/and prefixes. For example ${name} goes home matches Given Janne goes home so that ${name} gets value Given Janne. Quotes around the variable, like "${name}" goes home resolve also this problem.
The biggest benefit of having arguments as part of the keyword name is that it makes it easier to use higher-level sentence-like keywords when writing test cases in behavior-driven style. The example below illustrates this. Notice also that prefixes Given, When and Then are left out of the keyword definitions.
|Test Case
|Add two numbers
|Given I have Calculator open
|When I add 2 and 40
|Then result should be 42
|Add negative numbers
|Given I have Calculator open
|When I add 1 and -2
|Then result should be -1
|I have ${program} open
|Start Program
|I add ${number 1} and ${number 2}
|Input Number
|${number 1}
|Push Button
|Input Number
|${number 2}
|Push Button
|Result should be ${expected}
|${result} =
|Get Result
|Should Be Equal
Embedded arguments feature in Robot Framework is inspired by how step definitions are created in a popular BDD tool called Cucumber.
Similarly as library keywords, also user keywords can return values. Return values are defined with the [Return] setting. The values can then be assigned to variables in test cases or other user keywords.
In a typical case, a user keyword returns one value and it can be set to a scalar variable. This is done by having the return value in the next cell after the [Return] setting. User keywords can also return several values, which can then be assigned into several scalar variables at once, to a list variable, or to scalar variables and a list variable. Several values can be returned simply by specifying those values in different cells after the [Return] setting.
|Test Case
|One Return Value
|${ret} =
|Return One Value
|Some Keyword
|Multiple Values
|${c} =
|Return Three Values
|@{list} =
|Return Three Values
|@{rest} =
|Return Three Values
|Return One Value
|Do Something
|${value} =
|Get Some Value
|Return Three Values
User keywords and variables in test case files and test suite initialization files can only be used in files where they are created, but resource files provide a mechanism for sharing them. Since the resource file structure is very close to test case files, it is easy to create them.
Variable files provide a powerful mechanism for creating and sharing variables. For example, they allow values other than strings and enable creating variables dynamically. Their flexibility comes from the fact that they are created using Python code, which also makes them somewhat more complicated than Variable tables.
Resource files are imported using the Resource setting in the Settings table. The path to the resource file is given in the cell after the setting name.
If the path is given in an absolute format, it is used directly. In other cases, the resource file is first searched relatively to the directory where the importing file is located. If the file is not found there, it is then searched from the directories in PYTHONPATH. The path can contain variables, and it is recommended to use them to make paths system-independent (for example, ${RESOURCES}/login_resources.html or ${RESOURCE_PATH}). Additionally, slashes ("/") in the path are automatically changed to backslashes ("\") on Windows.
The user keywords and variables defined in a resource file are available in the file that takes that resource file into use. Similarly available are also all keywords and variables from the libraries, resource files and variable files imported by the said resource file.
The higher-level structure of resource files is the same as that of test case files otherwise, but, of course, they cannot contain Test Case tables. Additionally, the Setting table in resource files can contain only import settings (Library, Resource, Variables) and Documentation. The Variable table and Keyword table are used exactly the same way as in test case files.
If several resource files have a user keyword with the same name, they must be used so that the keyword name is prefixed with the resource file name without the extension (for example, myresources.Some Keyword and common.Some Keyword). Moreover, if several resource files contain the same variable, the one that is imported first is taken into use.
Keywords created in a resource file can be documented using [Documentation] setting. Starting from Robot Framework 2.1 also the resource file itself can have Documentation in the Setting table similarly as test suites.
Both libdoc.py and RIDE use these documentations, and they are naturally available for anyone opening resource files. The first line of the documentation of a keyword is logged when it is run, but otherwise resource file documentations are ignored during the test execution.
|An example resource file
|Open Login Page
|Opens browser
|to login page
|Open Browser
|Title Should Be
|Login Page
|Input Name
|Input Text
|Input Password
|Input Text
Variable files contain variables that can be used in test data. Variables can also be created using variable tables or set from the command line, but variable files allow creating them dynamically and their variables can contain any objects.
Variable files are created using the Python code, and technically they are Python modules. There are two different possibilities for creating variables:
All test data files can import variables using the Variables setting in the Setting table, in the same way as resource files are imported using the Resource setting. Similarly to resource files, the path to the imported variable file is considered relative to the directory where the importing file is, and if not found, it is searched from the directories in PYTHONPATH. The path can also contain variables, and slashes are converted to backslashes on Windows. If an argument file takes arguments, they are specified in the cells after the path and also they can contain variables.
All variables from a variable file are available in the test data file that imports it. If several variable files are imported and they contain a variable with the same name, the one in the earliest imported file is taken into use. Additionally, variables created in Variable tables and set from the command line override variables from variable files.
Another way to take variable files into use is using the command line option --variablefile. Variable files are referenced using a path to them, and possible arguments are joined to the path with a colon (:):
--variablefile myvariables.py --variablefile path/variables.py --variablefile /absolute/path/common.py --variablefile taking_arguments.py:arg1:arg2
Variables in these files are globally available in all test data files, similarly as individual variables set with the --variable option. If both --variablefile and --variable options are used and there are variables with same names, those that are set individually with --variable option take precedence.
When variable files are taken into use, they are imported as Python modules and all their global attributes that do not start with an underscore (_) are considered to be variables. Because variable names are case-insensitive, both lower- and upper-case names are possible, but in general, capital letters are recommended for global variables and attributes.
VARIABLE = "An example string"
ANOTHER_VARIABLE = "This is pretty easy!"
STRINGS = ["one", "two", "kolme", "four"]
In the example above, variables ${VARIABLE}, ${ANOTHER_VARIABLE}, and so on, are created. The first two variables are strings, the third one is an integer and the last two are lists. All these variables are scalar variables, even the ones containing lists as values. To create list variables, the variable name must be prefixed with LIST__ (note the two underscores).
LIST__STRINGS = ["list", "of", "strings"]
LIST__MIXED = ["first value", -1.1, None, True]
The variables in both the examples above could be created also using the Variable table below.
|An example string
|This is pretty easy!
|first value
Variables in variable files are not limited to having only strings or other base types as values like variable tables. Instead, their variables can contain any objects. In the example below, the variable ${MAPPING} contains a Java hashtable with two values (this example works only when running tests on Jython).
from java.util import Hashtable
MAPPING = Hashtable()
MAPPING.put("one", 1)
MAPPING.put("two", 2)
The second example creates ${MAPPING} as a Python dictionary and also has two variables created from a custom object implemented in the same file.
MAPPING = {'one': 1, 'two': 2}
class MyObject:
def __init__(self, name):
self.name = name
OBJ1 = MyObject('John')
OBJ2 = MyObject('Jane')
Because variable files are created using a real programming language, they can have dynamic logic for setting variables.
import os
import random
import time
USER = os.getlogin() # current login name
RANDOM_INT = random.randint(0, 10) # random integer in range [0,10]
CURRENT_TIME = time.asctime() # timestamp like 'Thu Apr 6 12:45:21 2006'
if time.localtime()[3] > 12:
AFTERNOON = True
AFTERNOON = False
The example above uses standard Python libraries to set different variables, but you can use your own code to construct the values. The example below illustrates the concept, but similarly, your code could read the data from a database, from an external file or even ask it from the user.
import math
def get_area(diameter):
radius = diameter / 2
area = math.pi * radius * radius
return area
AREA1 = get_area(1)
AREA2 = get_area(2)
When Robot Framework processes variable files, all their attributes that do not start with an underscore are expected to be variables. This means that even functions or classes created in the variable file or imported from elsewhere are considered variables. For example, the last example would contain the variables ${math} and ${get_area} in addition to ${AREA1} and ${AREA2}.
Normally the extra variables do not cause problems, but they could override some other variables and cause hard-to-debug errors. One possibility to ignore other attributes is prefixing them with an underscore:
import math as _math
def _get_area(diameter):
radius = diameter / 2.0
area = _math.pi * radius * radius
return area
AREA1 = _get_area(1)
AREA2 = _get_area(2)
If there is a large number of other attributes, instead of prefixing them all, it is often easier to use a special attribute __all__ and give it a list of attribute names to be processed as variables.
import math
__all__ = ['AREA1', 'AREA2']
def get_area(diameter):
radius = diameter / 2.0
area = math.pi * radius * radius
return area
AREA1 = get_area(1)
AREA2 = get_area(2)
The __all__ attribute is also, and originally, used by Python to decide which attributes to import when using the syntax from modulename import *.
An alternative syntax for getting variables is having a special get_variables function (also camelCase syntax getVariables is possible) in the variable file. In this case, Robot Framework calls that function and it returns variables as a Python dictionary or its subclass or a Java Map, with variable names as keys and variable values as values. (Note: Prior to Robot Framework 2.5 only Python dictionaries were supported.) Variables are considered to be scalars, unless prefixed with LIST__, and values can contain anything. The example below is identical to the first examples of creating variables directly.
def get_variables():
variables = { "VARIABLE ": "An example string",
"ANOTHER_VARIABLE": "This is pretty easy!",
"STRINGS": ["one", "two", "kolme", "four"],
"LIST__STRINGS": ["list", "of", "strings"],
"LIST__MIXED": ["first value", -1.1, None, True] }
return variables
get_variables can also take arguments, which facilitates changing what variables actually are created. Arguments to the function are set just as any other arguments for a Python function. When taking variable files into use in the test data, arguments are specified in cells after the path to the variable file, and in the command line they are separated from the path with a colon.
The dummy example below shows how to use arguments with variable files. In a more realistic example, the argument could be a path to an external text file or database where to read variables from.
variables1 = { 'scalar': 'Scalar variable',
'LIST__list': ['List','variable'] }
variables2 = { 'scalar' : 'Some other value',
'LIST__list': ['Some','other','value'],
'extra': 'variables1 does not have this at all' }
def get_variables(arg):
if arg == 'one':
return variables1
return variables2
The most notable benefit of using get_variables instead of defining variables directly as global attributes of the variable file is the ability to use arguments. On the other hand, the main drawback is that this approach always requires some actual programming.
Keywords that are used with Robot Framework are either library keywords or user keywords. The former come from standard libraries or external libraries, and the latter are either created in the same file where they are used or then imported from resource files. When many keywords are in use, it is quite common that some of them have the same name, and this section describes how to handle possible conflicts in these situations.
When only a keyword name is used and there are several keywords with that name, Robot Framework attempts to determine which keyword has the highest priority based on its scope. The keyword's scope is determined on the basis of how the keyword in question is created:
Scopes alone are not a sufficient solution, because there can be keywords with the same name in several libraries or resources, and thus, they provide a mechanism to use only the keyword of the highest priority. In such cases, it is possible to use the full name of the keyword, where the keyword name is prefixed with the name of the resource or library and a dot is a delimiter.
With library keywords, the long format means only using the format LibraryName.Keyword Name. For example, the keyword Run from the OperatingSystem library could be used as OperatingSystem.Run, even if there was another Run keyword somewhere else. If the library is in a module or package, the full module or package name must be used (for example, com.company.Library.Some Keyword). If a custom name is given to a library using the WITH NAME syntax, the specified name must be used also in the full keyword name.
Resource files are specified in the full keyword name, similarly as library names. The name of the resource is derived from the basename of the resource file without the file extension. For example, the keyword Example in a resource file myresources.html can be used as myresources.Example. Note that this syntax does not work, if several resource files have the same basename. In such cases, either the files or the keywords must be renamed. The full name of the keyword is case-, space- and underscore-insensitive, similarly as normal keyword names.
Starting from Robot Framework 2.1 it is possible to use the keyword Set Library Search Order from BuiltIn library to specify the priority order between test libraries that are in use. If multiple keywords with the same name are found, libraries implementing them are gone through in the library search order. The first library containing the keyword is selected and the keyword from that library is used. If keyword is not found, test execution fails.
There is no need to use the long format LibraryName.Keyword Name notation when library search order is set. This makes it easier to to use multiple instances of the same library as Set Library Search Order keyword can be used to switch between the libraries. This enables using same user keywords instead of duplicating those for all the library instances.
Library search order is valid in the suite level meaning it is available only in the suite where it was set.
Keywords may be problematic in situations where they take exceptionally long to execute or just hang endlessly. Robot Framework allows you to set timeouts both for test cases and user keywords, and if a test or keyword is not finished within the specified time, the keyword that is currently being executed is forcefully stopped. Stopping keywords in this manner may leave the library or system under test to an unstable state, and timeouts are recommended only when there is no safer option available. In general, libraries should be implemented so that keywords cannot hang or that they have their own timeout mechanism, if necessary.
The test case timeout can be set either by using the Test Timeout setting in the Setting table or the [Timeout] setting in the Test Case table. Test Timeout in the Setting table defines a default test timeout value for all the test cases in the test suite, whereas [Timeout] in the Test Case table applies a timeout to an individual test case and overrides the possible default value.
Regardless of where the test timeout is defined, the first cell after the setting name contains the duration of the timeout. The duration must be given in Robot Framework's time format, that is, either directly in seconds or in a format like 1 minute 30 seconds. It must be noted that there is always some overhead by the framework, and timeouts shorter than one second are thus not recommended.
The default error message displayed when a test timeout occurs is Test timeout <time> exceeded. It is also possible to use custom error messages, and these messages are written into the cells after the timeout duration. The message can be split into multiple cells, similarly as documentations. Both the timeout value and the error message may contain variables.
If there is a timeout, the keyword running is stopped at the expiration of the timeout and the test case fails. However, keywords executed as test teardown are not interrupted if a test timeout occurs, because they are normally engaged in important clean-up activities. If necessary, it is possible to interrupt also these keywords with user keyword timeouts.
|Test Timeout
|2 minutes
|Test Case
|Default Timeout
|Timeout from the Setting table is used
|Some Keyword
|Override default, use 10 seconds timeout
|Some Keyword
|Custom Message
|Override default and use custom message
|1min 10s
|This is my custom error.
|It continues here.
|Some Keyword
|It is possible to use variables too
|Some Keyword
|No Timeout
|Empty timeout means no timeout even when
|Test Timeout has been used
|Some Keyword
A timeout can be set for a user keyword using the [Timeout] setting in the Keyword table. The syntax for setting it, including how timeout values and possible custom messages are given, is identical to the syntax used with test case timeouts. If no custom message is provided, the default error message Keyword timeout <time> exceeded is used if a timeout occurs.
|Timed Keyword
|Set only the timeout value
|and not the custom message.
|1 minute 42 seconds
|Do Something
|Do Something Else
|Timed-out Wrapper
|This keyword is a wrapper
|that adds a timeout to another keyword.
|2 minutes
|Original Keyword didn't finish in 2 minutes
|Original Keyword
A user keyword timeout is applicable during the execution of that user keyword. If the total time of the whole keyword is longer than the timeout value, the currently executed keyword is stopped. User keyword timeouts are applicable also during a test case teardown, whereas test timeouts are not.
If both the test case and some of its keywords (or several nested keywords) have a timeout, the active timeout is the one with the least time left.
Using timeouts might cause test to be executed slower if the Python interpreter is used. The slowing down is caused by Python's threading implementation. For more information see issue 497.
Repeating same actions several times is quite a common need in test automation. With Robot Framework, test libraries can have any kind of loop constructs, and most of the time loops should be implemented in them. Robot Framework also has its own For loop syntax, which is useful, for example, when there is a need to repeat keywords from different libraries.
For loops can be used with both test cases and user keywords. Except for really simple cases, user keywords are better, because they hide the complexity introduced by for loops. The basic for loop syntax, FOR item IN sequence, is derived from Python, but similar syntax is possible also in shell scripts or Perl.
In a normal For loop, one variable is assigned from a list of values, one value per iteration. The syntax starts with :FOR, where colon is required to separate the syntax from normal keywords. The next cell contains the loop variable, the subsequent cell must have IN, and the final cells contain values over which to iterate.
The keywords used in the For loop are on the next rows and they must be indented one cell to the right. The For loop ends when the indentation returns back to normal or the table ends. Having nested For loops directly is not supported, but it is possible to use a user keyword inside a For loop and have another For loop there.
|Test Case
|Example 1
|2nd keyword
|Outside loop
|Example 2
The For loop in Example 1 above is executed twice, so that first the loop variable ${animal} has the value cat and then dog. The loop consists of two Log keywords. In the second example, loop values are split into several rows and the loop is run altogether seven times.
For loops are most useful and also clearest when they are used with list variables. This is illustrated by the example below, where @{ELEMENTS} contains an arbitrarily long list of element names and keyword Start Element is used with all of them.
|Test Case
|Start Element
It is also possible to use several loop variables. The syntax is the same as with the normal For loop, but all loop variables are listed in the cells between :FOR and IN. There can be any number of loop variables, but the number of values must be evenly dividable by the number of variables.
This syntax naturally works both with and without list variables. In the former case, it is often possible to organize loop values below loop variables, as in the first part of the example below:
|Test Case
|Do X
|Y Should Be
Earlier For loops always iterated over a sequence, and this is also the most common use case. Sometimes it is still convenient to have a For loop that is executed a certain number of times, and Robot Framework has a special FOR index IN RANGE limit syntax for this purpose. This syntax is derived from the similar Python idiom.
Similarly as other For loops, the For in range loop starts with :FOR and the loop variable is in the next cell. In this format there can be only one loop variable and it contains the current loop index. The next cell must contain IN RANGE and the subsequent cells loop limits.
In the simplest case, only the upper limit of the loop is specified. In this case, loop indexes start from zero and increase by one until, but excluding, the limit. It is also possible to give both the start and end limits. Then indexes start from the start limit, but increase similarly as in the simple case. Finally, it is possible to give also the step value that specifies the increment to use. If the step is negative, it is used as decrement. All these possibilities are illustrated by the examples below.
|Test Case
|Only upper limit
|Loops over
|from 0
|to 9
|Start and end
|Loops over
|from 1
|to 10
|Also step given
|Loops over
|5, 15,
|and 25
|Negative step
|Loops over
|13, 3,
|and -7
Normally for loop is executed until all the elements of the loop have been looped through or an error occurs and the test case or keyword fails. However sometimes execution of a for loop needs to be stopped before all elements of the loop have been gone through. BuiltIn keyword Exit For Loop can be used to exit the enclosing for loop.
Exit For Loop keyword can be used directly in a for loop or in a keyword that the for loop uses. In both cases the test execution continues after the for loop. If executed outside of a for loop, the test fails.
|Test Case
|Exit Example
|Run Keyword If
|'${var}' == 'EXIT'
|Exit For Loop
|Do Something
Exiting a for loop can also be initiated from a keyword in a test library by raising an exception with ROBOT_EXIT_FOR_LOOP attribute. Please see Stopping test execution for examples how to do this in Python and Java libraries.
Exit for loop functionality is new in Robot Framework 2.5.2.
For loops can be excessive in situations where there is only a need to repeat a single keyword. In these cases it is often easier to use BuiltIn keyword Repeat Keyword which was added in Robot Framework 2.0.4. This keyword takes a keyword and how many times to repeat it as arguments. The times to repeat the keyword can have an optional postfix times or x to make the syntax easier to read.
|Test Case
|Repeat Keyword
|Some Keyword
|Repeat Keyword
|42 times
|My Keyword
|Repeat Keyword
|Another KW
Robot Framework also had a special syntax for repeating a single keyword. This syntax was deprecated in the 2.0.4 version in favor of Repeat Keyword and it was removed in the 2.5 version.
In general, it is not recommended to have conditional logic in test cases, or even in user keywords, because it can make them hard to understand and maintain. Instead, this kind of logic should be in test libraries, where it can be implemented using natural programming language constructs. However, some conditional logic can be useful at times, and even though Robot Framework does not have an actual if/else construct, there are several ways to get the same effect.
Prior to the 2.5 version Robot Framework a had special syntax for executing keywords in parallel. This functionality was removed because it was rarely used and it never worked fully.
When parallel execution is needed, it must be implemented in test library level so that the library executes the code on background. Typically this means that the library needs a keyword like Start Something that starts the execution and returns immediately, and another keyword like Get Results From Something that waits until the result is available and returns it. See OperatingSystem library keywords Start Process and Read Process Output for an example.
Robot Framework test cases are executed from the command line, and the end result is, by default, an output file in XML format and an HTML report and log. After the execution, output files can be combined and otherwise post-processed with the rebot tool.
pybot [options] datasources jybot [options] datasources interpreter /path/to/robot/runner.py [options] datasources java -jar robotframework-<version>.jar [options] datasources
Test execution is normally started with the pybot or jybot commands. These commands are otherwise identical, but the former executes tests using the Python interpreter and the latter uses Jython. Which one to use depends on the needed test libraries. Some libraries use modules or syntax available only on Python, others use Java-based tools that require Jython, and some work on both. If you can use either pybot or jybot, the former is recommended, as Python is somewhat faster than Jython.
Starting from Robot Framework 2.5.2, it is also possible to get Robot Framework as a single jar file. In this case, Jython is bundled inside the jar, and the above discussion about Jython applies. Normal arguments to Robot Framework are given after the jar file name.
Another possibility for starting the test execution is running the runner.py script under the installed robot module directly. This method allows selecting the interpreter and setting command line options to it freely. The most common use case is altering the options controlling JVM maximum memory consumption.
Regardless of the runner script, the path (or paths) to the test data to be executed is given as an argument. Additionally, different command line options can be used to alter the test execution or generated outputs in some way.
Robot Framework test cases are created in files and directories, and they are executed by giving the path to the file or directory in question to the selected runner script. The path can be absolute or, more commonly, relative to the directory where tests are executed from. The given file or directory creates the top-level test suite, which gets its name, unless overridden with the --name option, from the file or directory name. Different execution possibilities are illustrated in the examples below. Note that in these examples, as well as in other examples in this section, only the pybot command is used, but jybot or a custom runner script could be used similarly.
pybot test_cases.html pybot path/to/my_tests/ pybot c:\robot\tests.txt
It is also possible to give paths to several test case files or directories at once, separated with spaces. In this case, Robot Framework creates the top-level test suite automatically, and the specified files and directories become its child test suites. The name of the created test suite is got from child suite names by catenating them together with an ampersand (&) and spaces. For example, the name of the top-level suite in the first example below is My Tests & Your Tests. These automatically created names are often quite long and complicated. In most cases, it is thus better to use the --name option for overriding it, as in the second example below:
pybot my_tests.html your_tests.html pybot --name Example path/to/tests/pattern_*.html
Robot Framework provides a number of command line options that can be used to control how test cases are executed and what outputs are generated. This section explains the option syntax, and what options actually exist. How they can be used is discussed elsewhere in this chapter.
When options are used, they must always be given between the runner script and the data sources. For example:
pybot -L debug my_tests.txt jybot --include smoke --variable HOST:10.0.0.42 path/to/tests/
Options always have a long name, such as --name, and the most frequently needed options also have a short name, such as -N. In addition to that, long options can be shortened as long as they are unique. For example, --logle DEBUG works, while --lo log.html does not, because the former matches only --loglevel, but the latter matches several options. Short and shortened options are practical when executing test cases manually, but long options are recommended in start-up scripts, because they are easier to understand.
The long option format is case-insensitive, which facilitates writing option names in an easy-to-read format. For example, --SuiteStatLevel is equivalent to, but easier to read than --suitestatlevel.
Most of the options require a value, which is given after the option name. Both short and long options accept the value separated from the option name with a space, as in --include tag or -i tag. With long options, the separator can also be the equals sign, for example --include=tag, and with short options the separator can be omitted, as in -itag.
Some options can be specified several times. For example, --variable VAR1:value --variable VAR2:another sets two variables. If the options that take only one value are used several times, the value given last is effective.
Many of the options take arguments as simple patterns. This means that * and ? can be used as special characters, so that the former matches any string (even an empty string) and the latter matches any single character. For example, --include prefix-* matches all tags starting with prefix-, and --include a??? matches any tag that is four characters long and starts with a character a.
The most visible output from test execution is the output displayed in the command line. All executed test suites and test cases, as well as their statuses, are shown there in real time. The example below shows the output from executing a simple test suite with only two test cases:
============================================================================== Example test suite ============================================================================== First test :: Possible test documentation | PASS | ------------------------------------------------------------------------------ Second test | FAIL | Error message is displayed here ============================================================================== Example test suite | FAIL | 2 critical tests, 1 passed, 1 failed 2 tests total, 1 passed, 1 failed ============================================================================== Output: /path/to/output.xml Report: /path/to/report.html Log: /path/to/log.html
The command line output is very limited, and separate output files are normally needed for investigating the test results. As the example above shows, three output files are generated by default. The first one is in XML format and contains all the information about test execution. The second is a higher-level report and the third is a more detailed log file. These files and other possible output files are discussed in more detail in the section Different output files.
Runner scripts communicate the overall test execution status to the system running them using return codes. When the execution starts successfully and no critical test fail, the return code is zero. All possible return codes are explained in the table below.
|All critical tests passed.
|Returned number of critical tests failed.
|250 or more critical failures.
|Help or version information printed.
|Invalid test data or command line options.
|Test execution stopped by user.
|Unexpected internal error.
Return codes should always be easily available after the execution, which makes it easy to automatically determine the overall execution status. For example, in bash shell the return code is in special variable $?, and in Windows it is in %ERRORLEVEL% variable. If you use some external tool for running tests, consult its documentation for how to get the return code.
During the test execution there can be unexpected problems like failing to import a library or a resource file or a keyword being deprecated. Depending on the severity such problems are categorized as errors or warnings and they are written into the console (using the standard error stream), shown on a separate Test Execution Errors section in log files, and also written into Robot Framework's own system log. Normally these errors are generated by Robot Framework core, but libraries can use log level WARN to write warnings. Example below illustrates how errors and warnings look like in the log file.
Because spaces are used for separating options from each other, it is problematic to use them in option values. Some options, such as --name, automatically convert underscores to spaces, but with others spaces must be escaped. Additionally, many special characters are complicated to use on the command line. Because escaping complicated characters with a backslash or quoting the values does not always work too well, Robot Framework has its own generic escaping mechanism. Another possibility is using argument files where options can be specified in the plain text format. Both of these mechanisms work when executing tests and when post-processing outputs, and also some of the external supporting tools have the same or similar capabilities.
In Robot Framework's command line escaping mechanism, problematic characters are escaped with freely selected text. The command line option to use is --escape (short version -E), which takes an argument in the format what:with, where what is the name of the character to escape and with is the string to escape it with. Characters that can be escaped are listed in the table below:
|Name to use
|Name to use
The following examples make the syntax more clear. In the first example, the metadata X gets the value Value with spaces, and in the second example variable ${VAR} is assigned to "Hello, world!":
--escape space:_ --metadata X:Value_with_spaces -E space:SP -E quot:QU -E comma:CO -E exclam:EX -v VAR:QUHelloCOSPworldEXQU
Note that all the given command line arguments, including paths to test data, are escaped. Escape character sequences thus need to be selected carefully.
Problematic characters can often be handled easily using argument files. These files can contain both command line options and paths to the test data, one per line. They are taken into use with --argumentfile option (short option -A) along with possible other command line options. Argument files can contain any characters without escaping, but spaces in the beginning and end of lines are ignored. Additionally, empty lines and lines starting with a hash mark (#) are ignored:
--doc This is an example (where "special characters" are ok!) --metadata X:Value with spaces --variable VAR:Hello, world! # This is a comment path/to/my/tests
Starting from Robot Framework 2.5 it is possible to have also non-ASCII characters in argument files. For this to work, the argument file must be saved using UTF-8 encoding.
Another important usage for argument files is specifying input files or directories in certain order. This can be very useful if the alphabetical default execution order is not suitable:
--name My Example Tests tests/some_tests.html tests/second.html tests/more/tests.html tests/more/another.html tests/even_more_tests.html
When an argument file is used on the command line, its contents are placed to the original list of arguments to the same place where the argument file option was. Argument files can be used either alone so that they contain all the options and paths to the test data, or along with other options and paths. It is possible to use --argumentfile option multiple times or even recursively:
pybot --argumentfile all_arguments.txt pybot --name example --argumentfile other_options_and_paths.txt pybot --argumentfile default_options.txt --name example my_tests.html pybot -A first.txt -A second.txt -A third.txt some_tests.tsv
Both when executing test cases with pybot or jybot and when post-processing reports with rebot, it is possible to get command line help with the option --help and its short version -h. These help texts have a short general overview and briefly explain the available command line options.
All runner scripts also support getting the version information with the option --version. This information also contains Python or Jython version and the platform type:
$ pybot --version Robot Framework 2.0.3 (Python 2.5.1 on cygwin) C:\>jybot --version Robot Framework 2.0.3 (Jython 2.2 on java1.5.0_16) C:\>rebot --version Rebot 2.0.3 (Python 2.5.2 on win32)
Test cases are often executed automatically by a continuous integration system or some other mechanism. In such cases, there is a need to have a script for starting the test execution, and possibly also for post-processing outputs somehow. Similar scripts are also useful when running tests manually, especially if a large number of command line options are needed or setting up the test environment is complicated.
In UNIX-like environments, shell scripts provide a simple but powerful mechanism for creating custom start-up scripts. Windows batch files can also be used, but they are more limited and often also more complicated. A platform-independent alternative is using Python or some other high-level programming language. Regardless of the language, it is recommended that long option names are used, because they are easier to understand than the short names.
In the first examples, the same web tests are executed with different browsers and the results combined afterwards. This is easy with shell scripts, as practically you just list the needed commands one after another:
pybot --variable BROWSER:Firefox --name Firefox --log none --report none --output out/fx.xml login
pybot --variable BROWSER:IE --name IE --log none --report none --output out/ie.xml login
rebot --name Login --splitoutputs 1 --outputdir out --output login.xml out/fx.xml out/ie.xml
Implementing the above example with Windows batch files is not very complicated, either. The most important thing to remember is that because pybot and rebot are implemented as batch files, call must be used when running them from another batch file. Otherwise execution would end when the first batch file is finished.
@echo off
call pybot --variable BROWSER:Firefox --name Firefox --log none --report none --output out\fx.xml login
call pybot --variable BROWSER:IE --name IE --log none --report none --output out\ie.xml login
call rebot --name Login --splitoutputs 1 --outputdir out --output login.xml out\fx.xml out\ie.xml
In the next examples, JAR files under the lib directory are put into CLASSPATH before starting the test execution. In these examples, start-up scripts require that paths to the executed test data are given as arguments. It is also possible to use command line options freely, even though some options have already been set in the script. All this is relatively straight-forward using bash:
for jar in lib/*.jar; do
export CLASSPATH=$cp
jybot --ouputdir /tmp/logs --splitoutputs 2 $*
Implementing this using Windows batch files is slightly more complicated. The difficult part is setting the variable containing the needed JARs inside a For loop, because, for some reason, that is not possible without a helper function.
@echo off
set CP=.
for %%jar in (lib\*.jar) do (
call :set_cp %%jar
set CLASSPATH=%CP%
jybot --ouputdir c:\temp\logs --splitoutputs 2 %*
goto :eof
:: Helper for setting variables inside a for loop
set CP=%CP%;%1
goto :eof
Sometimes there is need to alter the Java startup parameters. The most common use case is increasing the JVM maximum memory size as the default value may not be enough for creating reports and logs when outputs are very big. How to give the parameters to Java depends on the Jython version.
With Jython 2.2 you need to modify the Jython start-up script (jython shell script or jython.bat batch file) by adding the needed options (e.g. -Xmx1024m which sets the maximum memory to 1024 megabytes) to the java command. On Windows the final command could look like this:
"C:\Java\jre1.6.0\bin\java.exe" -Xmx1024m -Dpython.home="C:\Jython22" -classpath "C:\Jython22\jython.jar;%CLASSPATH%" org.python.util.jython %ARGS%
With Jython 2.5 it is also possible, and easier, to give the Java parameters with -J option to the Jython interpreter. This means that you can modify the jybot start-up script instead of Jython scripts. The last line of the jybot script can, again in Windows, be edited like below:
%jython% -J-Xmx1024m %runner% %*
A test case can fail because the system under test does not work correctly, in which case the test has found a bug, or because the test itself is buggy. The error message explaining the failure is shown on the command line output and in the report file, and sometimes the error message alone is enough to pinpoint the problem. More often that not, however, log files are needed because they have also other log messages and they show which keyword actually failed.
When a failure is caused by the tested application, the error message and log messages ought to be enough to understand what caused it. If that is not the case, the test library does not provide enough information and needs to be enhanced. In this situation running the same test manually, if possible, may also reveal more information about the issue.
Failures caused by test cases themselves or by keywords they use can sometimes be hard to debug. If the error message, for example, tells that a keyword is used with wrong number of arguments fixing the problem is obviously easy, but if a keyword is missing or fails in unexpected way finding the root cause can be harder. The first place to look for more information is the execution errors section in the log file. For example, an error about a failed test library import may well explain why a test has failed due to a missing keyword.
If the log file does not provide enough information by default, it is possible to execute tests with a lower log level. For example tracebacks showing where in the code the failure occurred are logged using the DEBUG level, and this information is invaluable when the problem is in an individual keyword.
If the log file still does not have enough information, it is a good idea to enable the syslog and see what information it provides. It is also possible to add some keywords to the test cases to see what is going on. Especially BuiltIn keywords Log and Log Variables are useful. If nothing else works, it is always possible to search help from mailing lists or elsewhere.
This section describes how the test suite structure created from the parsed test data is executed, how to continue executing a test case after failures, and how to stop the whole test execution gracefully.
Test cases are always executed within a test suite. A test suite created from a test case file has tests directly, whereas suites created from directories have child test suites which either have tests or their own child suites. By default all the tests in an executed suite are run, but it is possible to select tests using options --test, --suite, --include and --exclude. Suites containing no tests are ignored.
The execution starts from the top-level test suite. If the suite has tests they are executed one-by-one, and if it has suites they are executed recursively in depth-first order. When an individual test case is executed, the keywords it contains are run in a sequence. Normally the execution of the current test ends if any of the keywords fails, but it is also possible to continue after failures. The exact execution order and how possible setups and teardowns affect the execution are discussed in the following sections.
Setups and teardowns can be defined on test case and test suite level.
If a test suite has a setup, it is executed before its tests and child suites. If the suite setup passes, test execution continues normally. If it fails, all the test cases the suite and its child suites are marked failed with a message Setup of the parent suite failed.. The tests and possible suite setups and teardowns in the child test suites are not executed.
Suite setups are often used for setting up the test environment. Because tests are not run if the suite setup fails, it is easy to use suite setups for verifying that the environment is in state in which the tests can be executed.
If a test suite has a teardown, it is executed after all its test cases and child suites. Suite teardowns are executed regardless of the test status and even if the matching suite setup fails. If the suite teardown fails, all tests in the suite are marked failed afterwards in reports and logs.
Suite teardowns are mostly used for cleaning up the test environment after the execution. To ensure that all these tasks are done, all the keywords used in the teardown are executed even if some of them fail.
Possible test setup is executed before the keywords of the test case. If the setup fails, the keywords are not executed. The main use for test setups is setting up the environment for that particular test case.
Possible test teardown is executed after the test case has been executed. It is executed regardless of the test status and also if the setup of the test has failed.
Similarly as suite teardown, test teardowns are used mainly for cleanup activities. Also they are executed fully even if some of their keywords fail.
Test cases in a test suite are executed in the same order as they are defined in the test case file. Test suites inside a higher level test suite are executed in case-insensitive alphabetical order based on the file or directory name. If multiple files and/or directories are given from the command line, they are executed in the order they are given.
If there is a need to use certain test suite execution order inside a directory, it is possible to add prefixes like 01 and 02 into file and directory names. Such prefixes are not included in the generated test suite name if they are separated from the base name of the suite with two underscores:
01__my_suite.html -> My Suite 02__another_suite.html -> Another Suite
If the alphabetical ordering of test suites inside suites is problematic, a good workaround is giving them separately in the required order. This easily leads to overly long start-up commands, but argument files allow listing files nicely one file per line.
It is also possible to randomize the execution order using the --runmode option.
Normally test cases are stopped immediately when any of their keywords fail. This behavior shortens test execution time and prevents subsequent keywords hanging or otherwise causing problems if the system under test is in unstable state. This has the drawback that often subsequent keywords would give more information about the state of the system.
Before Robot Framework 2.5 the only way to handle failures so that test execution is not terminated immediately was using BuiltIn keywords Run Keyword And Ignore Error and Run Keyword And Expect Error. Using these keywords for this purpose often added extra complexity to test cases, and in Robot Framework 2.5 the following features were added to make continuing after failures easier.
Library keywords report failures using exceptions, and it is possible to use special exceptions to tell the core framework that execution can continue regardless the failure. How these exceptions can be created is explained in the test library API chapter.
When a test ends and there has been one or more continuable failure, the test will be marked failed. If there are more than one failure, all of them will be enumerated in the final error message:
Several failures occurred: 1) First error message. 2) Second error message ...
Test execution ends also if a normal failure occurs after continuable failures. Also in that case all the failures will be listed in the final error message.
The return value from failed keywords, possibly assigned to a variable, is always the Python None.
BuiltIn keyword Run Keyword And Continue On Failure allows converting any failure into a continuable failure. These failures are handled by the framework exactly the same way as continuable failures originating from library keywords.
To make it sure that all the cleanup activities are taken care of, the continue on failure mode is automatically on in test and suite teardowns. In practice this means that in teardowns all the keywords in all levels are always executed.
When using test templates, all the data rows are always executed to make it sure that all the different combinations are tested. In this usage continuing is limited to the top-level keywords, and inside them the execution ends normally if there are non-continuable failures.
Sometimes there is a need to stop the test execution before all the tests have finished, but so that logs and reports are created. Different ways how to accomplish this are explained below. In all these cases the remaining test cases are marked failed.
Most of these features are new in Robot Framework 2.5. Only the ExitOnFailure mode is supported in earlier versions.
The execution is stopped when Ctrl-C is pressed in the console where the tests are running. When running the tests on Python, the execution is stopped immediately, but with Jython it ends only after the currently executing keyword ends.
If Ctrl-C is pressed again, the execution ends immediately and reports and logs are not created.
On Unix-like machines it is possible to terminate test execution using signals INT and TERM. These signals can be sent from the command line using kill command, and sending signals can also be easily automated.
Signals have the same limitation on Jython as pressing Ctrl-C. Similarly also the second signal stops the execution forcefully.
The execution can be stopped also by the executed keywords. There is a separate Fatal Error BuiltIn keyword for this purpose, and custom keywords can use fatal exceptions when they fail.
If option --runmode is used with value ExitOnFailure (case-insensitive), the execution of tests stops immediately if a critical test fails and the remaining tests are marked as failed.
By default teardowns for tests and suites that have been started are executed even if test execution is stopped using one of the methods above. This allows clean-up activities to be run regardless how execution ends.
Starting from Robot Framework 2.5.2, teardowns are skipped when the execution is stopped if the --runmode SkipTeardownOnExit command line option is used. This can be useful if clean-up takes a lot of time.
XML output files that are generated during the test execution can be post-processed afterwards by the rebot tool, which is an integral part of Robot Framework. It is used automatically when test reports and logs are generated during the test execution, but there are also good grounds for using it separately after the execution.
The basic syntax for using rebot is exactly the same as when starting test execution, return codes are the same, and also most of the command line options are identical. The main difference is that arguments to rebot are XML output files instead of test data files or directories.
You can use rebot for creating the same reports and logs that are created automatically during the test execution. Of course, it is not sensible to create the exactly same files, but, for example, having one report with all test cases and another with only some subset of tests can be useful. Another common usage is creating only the output file when running tests (log and report generation can be disabled with options --log NONE and --report NONE) and generating logs and reports later. Tests can, for example, be executed on different environments, output files collected to a central place, and reports and logs created there. If generating reports and logs takes a lot of time when running tests on Jython, it is a good idea to try if using rebot, which always runs on Python, is any faster.
rebot output.xml rebot path/to/output_file.xml rebot --include smoke --name Smoke_Tests c:\results\output.xml
When using Robot Framework jar distribution, rebot is started with command:
java -jar robotframework-<version>.jar rebot
All normal command line options can be used when executing rebot from jar.
When running tests with Jython, the default JVM maximum memory size may not be enough for creating reports and logs if output files are very large. If that happens, you can either increase the JVM's maximum memory, or disable creating reports and logs when tests are executed and use rebot to generate them afterwards.
The most important feature of rebot is its ability to combine outputs from different test execution rounds. This capability allows, for example, running the same test cases on different environments and generating an overall report from all outputs. Combining outputs is extremely easy, all that needs to be done is giving several output files as arguments:
rebot output1.xml output2.xml rebot outputs/*.xml
When outputs are combined, a new top-level test suite is created so that test suites in the given output files are its child suites. This works the same way when multiple test data files or directories are executed, and also in this case the name of the top-level test suite is created by joining child suite names with an ampersand (&) and spaces. These automatically generated names are not that good, and it is often a good idea to use --name to give a more meaningful name:
rebot --name Browser_Compatibility firefox.xml opera.xml safari.xml ie.xml rebot --include smoke --name Smoke_Tests c:\results\*.xml
This section explains different command line options that can be used for configuring the test execution or post-processing outputs. Options related to generated output files are discussed in the next section.
Robot Framework offers several command line options for selecting which test cases to execute. The same options also work when post-processing outputs with the rebot tool.
Test suites and test cases can be selected by their names with the command line options --suite (-s) and --test (-t), respectively. Both of these options can be used several times to select several test suites or cases. Arguments to these options are case- and space-insensitive, and there can also be simple patterns matching multiple names. If both the --suite and --test options are used, only test cases in matching suites with matching names are selected.
--test Example --test mytest --test yourtest --test example* --suite example-?? --suite mysuite --test mytest --test your*
Using the --suite option is more or less the same as executing only the appropriate test case file or directory. One major benefit is the possibility to select the suite based on its parent suite. The syntax for this is specifying both the parent and child suite names separated with a dot. In this case, the possible setup and teardown of the parent suite are executed.
--suite parent.child --suite myhouse.myhousemusic --test jack*
Selecting individual test cases with the --test option is very practical when creating test cases, but quite limited when running tests automatically. The --suite option can be useful in that case, but in general, selecting test cases by tag names is more flexible.
It is possible to include and exclude test cases by tag names with the --include (-i) and --exclude (-e) options, respectively. When the former is used, only test cases having a matching tag are selected, and with the latter, test cases having a matching tag are not. If both are used, only tests with a tag matching the former option, and not with a tag matching the latter, are selected.
--include example --exclude not_ready --include regression --exclude long_lasting
Both --include and --exclude can be used several times to match multiple tags, and their arguments can be simple patterns. In these cases, the rules for selecting test cases apply, so that test cases with a tag matching any include patterns are selected, and tests with a tag matching exclude patterns are not. It is also possible to select only test cases that have two or more specified tags by separating the tags either with & or AND (case-sensitive). Starting from Robot Framework 2.1.3, only tests with a certain tag, but without any others, can be selected by separating these tags with NOT (case-sensitive). If any of the patterns between multiple NOT is matching, the test case is not selected.
--include req-* --include regressionANDiter-42 --include tag1&tag2&tag3&tag4 --exclude regressionNOTowner-* --include tag1NOTtag2NOTtag3&tag4 (includes tests which have `tag1`, but not tests which additionally have `tag2` or both tags `tag3` and `tag4`)
Selecting test cases by tags is a very flexible mechanism and allows many interesting possibilities:
The final result of test execution is determined on the basis of critical tests. If a single critical test fails, the whole test run is considered failed. On the other hand, non-critical test cases can fail and the overall status is still passed.
By default, all test cases are critical, but this can be changed with the --critical (-c) and --noncritical (-n) options. These options specify which test cases are consider critical based on tags, similarly as --include and --exclude are used to select test cases by tag names. If only --critical is used, test cases with a matching tag are critical. If only --noncritical is used, tests without a matching tag are critical. Finally, if both are used, only test with a critical tag but without a non-critical tag are considered critical. Both of these options accept simple patterns and can be given several times:
--critical regression --noncritical not_ready --critical iter-* --critical req-* --noncritical req-6??
The most common use case for setting criticality is having test cases that are not ready or test features still under development in the test execution. Of course, these tests could be excluded from the test execution altogether with the --exclude option, but including them as non-critical tests enables you to see when they start to pass.
Starting from Robot Framework 2.1 criticality set when tests are executed is not stored anywhere. If you want to keep same criticality when post-processing outputs with rebot, you need to use --critical and/or --noncritical also with it:
# Use rebot to create new log and report from the output created during execution pybot --critical regression --outputdir all my_tests.html rebot --name Smoke --include smoke --critical regression --outputdir smoke all/output.xml # No need to use --critical/--noncritical when no log or report is created jybot --log NONE --report NONE my_tests.html rebot --critical feature1 output.xml
When Robot Framework parses test data, test suite names are created from file and directory names. The name of the top-level test suite can, however, be overridden with the command line option --name (-N). Underscores in the given name are converted to spaces automatically, and words in the name capitalized.
In addition to defining documentation in the test data, documentation of the top-level suite can be given from the command line with the option --doc (-D). Underscores in the given documentation are converted to spaces, and it may contain simple HTML formatting.
Free test suite metadata may also be given from the command line with the option --metadata (-M). The argument must be in the format name:value, where name the name of the metadata to set and value is its value. Underscores in the name and value are converted to spaces, and the latter may contain simple HTML formatting. This option may be used several times to set multiple metadata.
When a test library is taken into use, Robot Framework uses the Python or Jython interpreter to import a module implementing the library from the system. The location where these modules are searched from is called PYTHONPATH, and when running tests on Jython, also Java CLASSPATH is used.
Adjusting the library search path so that libraries are found is a requirement for successful test execution. In addition to find test libraries, the search path is also used to find listeners set on the command line. There are various ways to alter PYTHONPATH and CLASSPATH, but regardless of the selected approach, it is recommended to use a custom start-up script.
Python and Jython installations put their own library directories into PYTHONPATH automatically. This means that test libraries packaged using Python's own packaging system are automatically installed into a location that is in the library search path. Robot Framework also puts the directory containing its standard libraries and the directory where tests are executed from into PYTHONPATH.
There are several ways to alter PYTHONPATH in the system, but the most common one is setting an environment variable with the same name before the test execution. Jython actually does not use PYTHONPATH environment variable normally, but Robot Framework ensures that locations listed in it are added into the library search path regardless of the interpreter.
CLASSPATH is used only with Jython, and the most common way to alter it is setting an environment variable similarly as with PYTHONPATH. Note that instead of CLASSPATH, it is always possible to use PYTHONPATH with Jython, even with libraries and listeners implemented with Java.
Robot Framework also has a separate command line option --pythonpath (-P) for adding directories or archives into PYTHONPATH. Multiple paths can be given by separating them with a colon (:) or using this option several times. The given path can also be a glob pattern matching multiple paths, but then it normally must be escaped.
--pythonpath libs/ --pythonpath /opt/testlibs:mylibs.zip:yourlibs --pythonpath mylib.jar --pythonpath lib/STAR.jar --escape star:STAR
Variables can be set from the command line either individually using the --variable (-v) option or through variable files with the --variablefile (-V) option. Variables and variable files are explained in separate chapters, but the following examples illustrate how to use these options:
--variable name:value --variable OS:Linux --variable IP:10.0.0.42 --variablefile path/to/variables.py --variablefile myvars.py:possible:arguments:here --variable ENVIRONMENT:Windows --variablefile c:\resources\windows.py
Robot Framework supports so called dry run mode where the tests are run normally otherwise, but the keywords coming from the test libraries are not executed at all. The dry run mode can be used to validate the test data; if the dry run passes, the data should be syntactically correct. This mode is triggered using option --runmode DryRun (case-insensitive) and it is supported starting from Robot Framework 2.5.
The dry run execution may fail for following reasons:
- Using keywords that are not found.
- Using keywords with wrong number of arguments.
- Using user keywords that have invalid syntax.
In addition to these failures, normal execution errors are shown, for example, when test library or resource file imports cannot be resolved.
The dry run mode does not validate variables. This limitation may be lifted in the future releases.
The --runmode option can also be used to randomize the test execution order. This is done using the different values explained below.
pybot --runmode random:test my_test.txt
The width of the test execution output in the console is set using the option --monitorwidth (-W). The default value for the monitor width is 78 characters.
The --monitorcolors (-C) option is used to control whether colors should be used in the monitor output. These so-called ANSI colors do not work on Windows by default, but they ought to work on all UNIX-like systems. This option has three possible, case-insensitive values:
pybot --monitorwidth 140 --monitorcolors OFF tests.html > output.txt
So-called listeners can be used for monitoring the test execution. They are taken into use with the command line option --listener, and the specified listeners must be in the module search path similarly as test libraries.
Several output files are created when tests are executed, and all of them are somehow related to test results. This section discusses what outputs are created, how to configure where they are created, and how to fine-tune their contents.
This section explains what different output files can be created and how to configure where they are created. Output files are configured using command line options, which get the path to the output file in question as an argument. A special value NONE (case-insensitive) can be used to disable creating a certain output file.
All output files can be set using an absolute path, in which case they are created to the specified place, but in other cases, the path is considered relative to the output directory. The default output directory is the directory where the execution is started from, but it can be altered with the --outputdir (-d) option. The path set with this option is, again, relative to the execution directory, but can naturally be given also as an absolute path. Regardless of how a path to an individual output file is obtained, its parent directory is created automatically, if it does not exist already.
Output files contain all the test execution results in XML format. Log, report, and summary files are generated based on output files, and output files can also be combined and otherwise post-processed after the test execution.
The command line option --output (-o) determines where output files are created. Output files are always created when tests are executed, and unless outputs are splitted, only one output file is created. The default name for the output file is output.xml. If outputs are splitted to several output files, they are named by postfixing the name of the first output file with sequence numbers. When post-processing outputs, new output files are not created unless --output (-o) option is explicitly used.
Log files contain details about the executed test cases in HTML format. They have a hierarchical structure showing test suite, test case and keyword details. Log files are needed nearly every time when test results are to be investigated in detail. Even though log files also have statistics, report and summary files are better for getting an higher-level overview.
The command line option --log (-l) determines where log files are created. Unless the special value NONE is used, log files are always created and their default name is log.html.
Report files contain an overview of the test execution results in HTML format. They have statistics based on tags and executed test suites, as well as a list of all executed test cases. When both reports and logs are generated, the report has links to the log file for easy navigation to more detailed information. It is easy to see the overall test execution status from report, because its background color is green, if all critical tests pass, and bright red otherwise.
The command line option --report (-r) determines where report files are created. Similarly as log files, reports are always created unless NONE is used as a value, and their default name is report.html.
Summary files contain the same statistics as reports, and their background color is similarly green or red, depending on the overall test execution status. However, they have no test case details, which makes them much smaller. They are useful when a large number of test cases is executed and a very high-level overview is needed.
Summary files are not generated by default. When they are needed, they can be created using the command line option --summary (-S).
Debug files are plain text files that are written during the test execution. All messages got from test libraries are written to them, as well as information about started and ended test suites, test cases and keywords. Debug files can be used for monitoring the test execution. This can be done using, for example, a separate file viewing tool, or in UNIX-like systems, simply with the tail -f command.
Debug files are not created unless the command line option --debugfile (-b) is used explicitly.
All output files listed in this section can be automatically timestamped with the option --timestampoutputs (-T), which is one of the rare options taking no value. When this option is used, a timestamp in the format YYYYMMDD-hhmmss is placed between the extension and the basename of each file. The example below would, for example, create such output files as output-20080604-163225.xml and mylog-20080604-163225.html.
pybot --timestampoutputs --log mylog.html --report NONE tests.html
The default titles for log, report and summary files are generated by prefixing the name of the top-level test suite wtih Test Log, Test Report or Summary Report. Custom titles can be given from the command line using the options --logtitle, --reporttitle and --summarytitle, respectively. With all these options, underscores in the given title are converted to spaces automatically.
pybot --logtitle Smoke_Test_Log --reporttitle Smoke_Test_Report --include smoke mytests rebot --summarytitle Overview --summary overview.html --log none --report none *.xml
By default the report file and the summary file have a green background when all the critical tests pass and a red background otherwise. These colors can be customized by using the --reportbackground command line option, which takes two or three colors separated with a colon as an argument:
--reportbackground blue:red --reportbackground green:yellow:red --reportbackground #00E:#E00
If you specify two colors, the first one will be used instead of the default green color and the second instead of the default red. This allows, for example, using blue instead of green to make backgrounds easier to separate for color blind people.
If you specify three colors, the first one will be used when all the test succeed, the second when only non-critical tests have failed, and the last when there are critical failures. This feature thus allows using a separate background color, for example yellow, when non-critical tests have failed.
The specified colors are used as a value for the body element's background CSS property. The value is used as-is and can be a HTML color name (e.g. red), a hexadecimal value (e.g. #F00), or an RGB value (e.g. rgb(255,0,0). The default green and red colors are specified using hexadecimal values #9F6 and #F33, respectively.
Messages in log files can have different log levels. Some of the messages are written by Robot Framework itself, but also executed keywords can log information using different levels. The available log levels are:
By default, log messages below the INFO level are not logged, but this threshold can be changed from the command line using the --loglevel (-L) option. This option takes any of the available log levels as an argument, and that level becomes the new threshold level. A special value NONE can also be used to disable logging altogether.
Starting from Robot Framework 2.5.2, it is possible to use the --loglevel option also when post-processing outputs with rebot. This allows, for example, running tests initially with the TRACE level, and generating smaller log files for normal viewing later with the INFO level. By default all the messages included during execution will be included also with rebot. Messages ignored during the execution cannot be recovered.
Another possibility to change the log level is using the BuiltIn keyword Set Log Level in the test data. It takes the same arguments as the --loglevel option, and it also returns the old level so that it can be restored later, for example, in a test teardown.
When executing a large number of test cases, the size of log files can increase to the extent that opening them into a browser is slow. Additionally, since log files can be created only after output files are ready, they are available only after the test execution. This is not a problem if the test execution time is short, but with long-running tests it is better to be able to investigate the first failures while the rest of the tests are still running.
Splitting outputs provides a solution for both of these problems. First of all, splitting logs means that individual log files are smaller and thus faster to open. If outputs are split while executing test cases, the lower-level log files are also created immediately when the equivalent output files are ready. Notifications about created files can be received through the listener interface, and automatic variables ${LOG_FILE} and ${OUTPUT_FILE} always contain the path to the current file.
Outputs are split from a certain test suite level. Suites below this level will get their own outputs, and everything above the level will be in an index file, which has links to lower-level files. Only output files and log files are split, and they are always split from the same level. Splitting outputs gives the best results when test cases are organized into a relatively balanced hierarchical structure.
Splitting can be activated with the command line option --splitoutputs, which takes the split level as an argument. Index files have the same name as the output and log would have without splitting, and lower-level files get a running counter between the basename and extension.
Explaining how splitting outputs actually works is easiest with examples, and it is also a good idea to experiment with real test data. In these examples we assume that test cases are organized into test suites hierarchically in the following way:
project |-- component_a | |-- feature_a1 | | |-- a11.html | | `-- a12.html | `-- feature_a2 | `-- a21.html |-- component_b | `-- feature_b1 | |-- b11.html | `-- b21.html `-- component_c |-- c1.html |-- c2.html `-- c3.html
In the first example these test cases are executed so that they are split right below the top-level test suite. The command line to use is as follows, and the following table lists all the created output files:
pybot --splitoutputs 1 project
|Created File
|Information about the Project test suite, excluding its child test suites. Lower-level output files are referenced.
|Information about the whole Component A suite.
|Information about the whole Component B suite.
|Information about the whole Component C suite.
|A log file created from output.xml, lower-level log files are linked.
|A log file created from output-001.xml.
|A log file created from output-002.xml.
|A log file created from output-003.xml.
|A normal report file.
The fact that output files are split is transparent when post-processing outputs afterwards, and it is enough to point rebot to the index file. Splitting works with rebot regardless of whether outputs are split earlier or not. Outputs created by the first example could thus by re-split, for example, as:
rebot --splitoutputs 2 output.xml
In this example, splitting is done from the second level. The table below again lists created the files, and because rebot does not create new output files by default, they are not listed in the table.
|Created File
|Information about the Project and all the Component ? suites, but not their child suites. Lower-level log files are linked.
|The whole Feature A1 test suite.
|The whole Feature A2 test suite.
|The whole Feature B1 test suite.
|The whole C1 test suite.
|The whole C2 test suite.
|The whole C3 test suite.
|A normal report file.
The last example splits outputs from the third level. It also shows how to configure output file names when splitting:
rebot --splitoutputs 3 --log mylog.html --report none output.xml
|Created File
|Information about the Project test suite all the way to its second-level child suites. This includes test cases in the C? suites. Lower-level logs are linked.
|The whole A11 test suite.
|The whole A12 test suite.
|The whole A21 test suite.
|The whole B11 test suite.
|The whole B12 test suite.
If a split level higher than three is used with this test data, all the information ends up to index files. The end result is thus exactly the same as if outputs were not split at all.
There are several command line options that can be used to configure and adjust the contents of the Statistics by Tag, Statistics by Suite and Test Details by Tag tables in different output files. All these options work both when executing test cases and when post-processing outputs.
When a deeper suite structure is executed, showing all the test suite levels in the Statistics by Suite table may make the table somewhat difficult to read. You can control the number of levels displayed with the command line option --suitestatlevel. It takes the required level as an integer, and if 0 is used, the whole table is removed.
When many tags are used, the Statistics by Tag table can become quite congested. If this happens, the command line options --tagstatinclude and --tagstatexclude can be used to select which tags to display, similarly as --include and --exclude are used to select test cases:
--tagstatinclude some-tag --tagstatinclude another-tag --tagstatexclude owner-* --tagstatinclude prefix-* --tagstatexclude prefix-13
These settings affect also the Test Details by Tag table, so that it has details only by the selected tags. This can make the report considerably smaller, which is why excluding tags that are not interesting can be recommended.
The command line option --tagstatcombine can be used to generate aggregate tags that combine statistics from multiple tags. These new combined tags are shown in the Statistics by Tag table, and the matching tests are listed in the Test Details by Tag table. There are three somewhat different ways for giving arguments for this option:
The following examples illustrate these usages, and the figure below shows a snippet of the resulting Statistics by Tag table when the example test data is executed with these options:
--tagstatcombine owner-* --tagstatcombine smokeANDmytag --tagstatcombine smokeNOTowner-janne*
As the above example shows, the name of the added combined statistic is, by default, generated from the given pattern. In certain situations this name can look pretty cryptic and, starting from Robot Framework 2.0.2, it is possible to specify a more descriptive name. This name is given after the pattern separating it with a colon (:). Example below generates combined tag so that the name shown in reports and logs is Critical Tests:
--tagstatcombine *NOTnon-critical:Critical_Tests
You can add external links to the Statistics by Tag table by using the command line option --tagstatlink. Arguments to this option are given in the format tag:link:name, where tag specifies the tags to assign the link to, link is the link to be created, and name is the name to give to the link.
tag may be a single tag, but more commonly a simple pattern where * matches anything and ? matches any single character. When tag is a pattern, the matches to wildcards may be used in link with the syntax %N, where "N" is the index of the match starting from 1.
The following examples illustrate the usage of this option, and the figure below shows a snippet of the resulting Statistics by Tag table when example test data is executed with these options:
--tagstatlink mytag:http://www.google.com:Google --tagstatlink jython-bug-*:http://bugs.jython.org/issue_%1:Jython-bugs --tagstatlink owner-*:mailto:%firstname.lastname@example.com?subject=Acceptance_Tests:Send_Mail
These options are available only when post-processing outputs with rebot.
When combining outputs, it is possible to set the start and end time of the combined test suite using the options --starttime and --endtime, respectively. This is convenient, because by default, combined suites do not have these values. When both the start and end time are given, the elapsed time is also calculated based on them. Otherwise the elapsed time is got by adding the elapsed times of the child test suites together.
Times must be given as timestamps in the format YYYY-MM-DD hh:mm:ss.mil, where all separators are optional and the parts from milliseconds to hours can be omitted. For example, 2008-06-11 17:59:20.495 is equivalent both to 20080611-175920.495 and 20080611175920495, and also mere 20080611 would work.
rebot --starttime 20080611-17:59:20.495 output1.xml output2.xml rebot --starttime 20080611-175920 --endtime 20080611-180242 *.xml
Most of the content of output files comes from keywords and especially their log messages. When creating higher level reports, log files are not necessarily needed at all, and then keywords and their messages just take space unnecessarily. In these situations, the command line option --removekeywords can be used to dispose of unnecessary keywords. It has two possible values:
Removing keywords makes output files considerably smaller and thus faster to process further. Even when keywords are removed, names, arguments and statuses of top-level keywords are preserved, so it is still possible to create log files and see the high-level structure of each test case.
Robot Framework has its own plain-text system log where it writes information about
- Processed and skipped test data files
- Imported test libraries, resource files and variable files
- Executed test suites and test cases
- Created outputs
Normally users never need this information, but it can be useful when investigating problems with test libraries or Robot Framework itself. A system log is not created by default, but it can be enabled by setting the environment variable ROBOT_SYSLOG_FILE so that it contains a path to the selected file.
A system log has the same log levels as a normal log file, with the exception that instead of FAIL it has the ERROR level. The threshold level to use can be altered using the ROBOT_SYSLOG_LEVEL environment variable like shown in the example below. Possible unexpected errors and warnings are written into the system log in addition to the console and the normal log file.
export ROBOT_SYSLOG_FILE=/tmp/syslog.txt
export ROBOT_SYSLOG_LEVEL=DEBUG
pybot --name Syslog_example path/to/tests
Robot Framework's actual testing capabilities are provided by test libraries. There are many existing libraries, some of which are even bundled with the core framework, but there is still often a need to create new ones. This task is not too complicated because, as this chapter illustrates, Robot Framework's library API is simple and straightforward.
Robot Framework itself is written with Python and naturally test libraries extending it can be implemented using the same language. When running the framework on Jython, libraries can also be implemented using Java. Pure Python code works both on Python and Jython, assuming that it does not use syntax or modules that are not available on Jython. When using Python, it is also possible to implement libraries with C using Python C API, although it is often easier to interact with C code from Python libraries using ctypes module.
Libraries implemented using these natively supported languages can also act as wrappers to functionality implemented using other programming languages. A good example of this approach is the Remote library, and another widely used approaches is running external scripts or tools as separate processes.
Python Tutorial for Robot Framework Test Library Developers covers enough of Python language to get started writing test libraries using it. It also contains a simple example library and test cases that you can execute and otherwise investigate on your machine.
Robot Framework has three different test library APIs.
Static API
The simplest approach is having a module (in Python) or a class (in Python or Java) with methods which map directly to keyword names. Keywords also take the same arguments as the methods implementing them. Keywords report failures with exceptions, log by writing to standard output and can return values using the return statement.
Dynamic API
Dynamic libraries are classes that implement a method to get the names of the keywords they implement, and another method to execute a named keyword with given arguments. The names of the keywords to implement, as well as how they are executed, can be determined dynamically at runtime, but reporting the status, logging and returning values is done similarly as in the static API.
Hybrid API
This is a hybrid between the static and the dynamic API. Libraries are classes with a method telling what keywords they implement, but those keywords must be available directly. Everything else except discovering what keywords are implemented is similar as in the static API.
All these APIs are described in this chapter. Everything is based on how the static API works, so its functions are discussed first. How the dynamic library API and the hybrid library API differ from it is then discussed in sections of their own.
The examples in this chapter are mainly about using Python, but they should be easy to understand also for Java-only developers. In those few cases where APIs have differences, both usages are explained with adequate examples.
Test libraries can be implemented as Python modules and Python or Java classes.
The name of a test library that is used when a library is imported is the same as the name of the module or class implementing it. For example, if you have a Python module MyLibrary (that is, the file MyLibrary.py), it will create a library with a name MyLibrary. Similarly, a Java class YourLibrary, when it is not in any package, creates a library with exactly that name.
Python classes are always inside a module. If the name of a class implementing a library is the same as the name of the module, Robot Framework allows dropping the module name when importing the library. For example, the class MyLib in the MyLib.py file can be used as a library with the name MyLib. If the module name and class name are different, libraries must be taken into use using both module and class names, such as mymodule.MyLibrary.
Java classes in a non-default package must be taken into use with the full name. For example, the class MyLib in the com.mycompany.myproject package must be imported with the name com.mycompany.myproject.MyLib.
If the library name is really long, for example when the Java package name is long, it is recommended to give the library a simpler alias by using the WITH NAME syntax.
All test libraries implemented as classes can take arguments. These arguments are specified in the Setting table after the library name, and when Robot Framework creates an instance of the imported library, it passes them to its constructor. Libraries implemented as a module cannot take any arguments, so trying to use those results in an error.
The number of arguments needed by the library is the same as the number of arguments accepted by the library's constructor. The default values and variable number of arguments work similarly as with keyword arguments, with the exception that there is no variable argument support for Java libraries. Arguments passed to the library, as well as the library name itself, can be specified using variables, so it is possible to alter them, for example, from the command line.
Example implementations, first one in Python and second in Java, for the libraries used in the above example:
from example import Connection
class MyLibrary:
def __init__(self, host, port=80):
self._conn = Connection(host, int(port))
def send_message(self, message):
public class AnotherLib {
private String setting = null;
public AnotherLib(String setting) {
setting = setting;
public void doSomething() {
if setting.equals("42") {
// do something ...
Libraries implemented as classes can have an internal state, which can be altered by keywords and with arguments to the constructor of the library. Because the state can affect how keywords actually behave, it is important to make sure that changes in one test case do not accidentally affect other test cases. These kind of dependencies may create hard-to-debug problems, for example, when new test cases are added and they use the library inconsistently.
Robot Framework attempts to keep test cases independent from each other: by default, it creates new instances of test libraries for every test case. However, this behavior is not always desirable, because sometimes test cases should be able to share a common state. Additionally, all libraries do not have a state and creating new instances of them is simply not needed.
Test libraries can control when new libraries are created with a class attribute ROBOT_LIBRARY_SCOPE . This attribute must be a string and it can have the following three values:
When the TEST SUITE or GLOBAL scopes are used with test libraries that have a state, it is recommended that libraries have some special keyword for cleaning up the state. This keyword can then be used, for example, in a suite setup or teardown to ensure that test cases in the next test suites can start from a known state. For example, SeleniumLibrary uses the GLOBAL scope to enable using the same browser in different test cases without having to reopen it, and it also has the Close All Browsers keyword for easily closing all open browsers.
Example Python library using the TEST SUITE scope:
class ExampleLibrary:
def __init__(self):
self._counter = 0
def count(self):
self._counter += 1
print self._counter
def clear_counter(self):
self._counter = 0
Example Java library using the GLOBAL scope:
public class ExampleLibrary {
public static final String ROBOT_LIBRARY_SCOPE = "GLOBAL";
private int counter = 0;
public void count() {
counter += 1;
public void clearCounter() {
counter = 0;
When a test library is taken into use, Robot Framework tries to determine its version. This information is then written into the syslog to provide debugging information. Library documentation tool libdoc.py also writes this information into the keyword documentations it generates.
Version information is read from attribute ROBOT_LIBRARY_VERSION, similarly as test library scope is read from ROBOT_LIBRARY_SCOPE. If ROBOT_LIBRARY_VERSION does not exist, information is tried to be read from __version__ attribute. These attributes must be class or module attributes, depending whether the library is implemented as a class or a module. For Java libraries the version attribute must be declared as static final.
An example Python module using __version__:
__version__ = '0.1'
def keyword():
A Java class using ROBOT_LIBRARY_VERSION:
public class VersionExample {
public static final String ROBOT_LIBRARY_VERSION = "1.0.2";
public void keyword() {
When the static library API is used, Robot Framework uses reflection to find out what methods the library implements. With dynamic library API and hybrid library API, keyword names are got from the library directly. Naturally, Robot Framework can see only the public methods and it also excludes all methods starting with an underscore. With Java libraries, also methods that are implemented in java.lang.Object and not overridden are ignored.
Keyword names used in the test data are compared with method names to find the method implementing these keywords. Name comparison is case-insensitive, and also spaces and underscores are ignored. For example, the method hello maps to the keyword name Hello, hello or even h e l l o. Similarly both the do_nothing and doNothing methods can be used as the Do Nothing keyword in the test data.
Example Python library implemented as a module in the MyLibrary.py file:
def hello(name):
print "Hello, %s!" % name
def do_nothing():
Example Java library implemented as a class in the MyLibrary.java file:
public class MyLibrary {
public void hello(String name) {
System.out.println("Hello, " + name + "!");
public void doNothing() {
The example below illustrates how the example libraries above can be used. If you want to try this yourself, make sure that the library is in the library search path.
|Test Case
|My Test
|Do Nothing
With a static and hybrid API, the information on how many arguments a keyword needs is got directly from the method that implements it. Libraries using the dynamic library API have other means for sharing this information, so this section is not relevant to them.
The most common and also simplest situation is when a keyword needs an exact number of arguments. In this case, both the Python and Java methods simply take exactly those arguments. For example, a method implementing a keyword with no arguments takes no arguments either, a method implementing a keyword with one argument also takes one argument, and so on.
Example Python keywords taking different numbers of arguments:
def no_arguments():
print "Keyword got no arguments"
def one_argument(arg):
print "Keyword got one argument '%s'" % arg
def multiple_arguments(a1, a2, a3):
print "Keyword got three arguments '%s', '%s' and '%s'" % (a1, a2, a3)
It is often useful that some of the arguments that a keyword uses have default values. Python and Java have different syntax for handling default values to methods, and the natural syntax of these languages can be used when creating test libraries for Robot Framework.
In Python a method has always exactly one implementation and possible default values are specified in the method signature. The syntax, which is familiar to all Python programmers, is illustrated below:
def one_default(arg='default'):
print "Argument has value '%s'" % arg
def multiple_defaults(arg1, arg2='default 1', arg3='default 2'):
print "Got arguments %s, %s and %s" % (arg1, arg2, arg3)
The first example keyword above can be used either with zero or one arguments. If no arguments are given, arg gets the value default. If there is one argument, arg gets that value, and calling the keyword with more than one argument fails. In the second example, one argument is always required, but the second and the third one have default values, so it is possible to use the keyword with one to three arguments.
|Test Case
|One Default
|One Default
|Multiple Defaults
|required arg
|Multiple Defaults
|required arg
|Multiple Defaults
|required arg
|optional 1
|optional 2
In Java one method can have several implementations with different signatures. Robot Framework regards all these implementations as one keyword, which can be used with different arguments. This syntax can thus be used to provide support for the default values. This is illustrated by the example below, which is functionally identical to the earlier Python example:
public void oneDefault(String arg) {
System.out.println("Argument has value '" + arg "'");
public void oneDefault() {
public void multipleDefaults(String arg1, String arg2, String arg3) {
System.out.println("Got arguments " + arg1 + ", " + arg2 + " and " + arg3);
public void multipleDefaults(String arg1, String arg2) {
multipleDefaults(arg1, arg2, "default 2");
public void multipleDefaults(String arg1) {
multipleDefaults(arg1, "default 1");
Robot Framework supports also keywords that take any number of arguments. Similarly as with the default values, the actual syntax to use in test libraries is different in Python and Java.
Python supports methods accepting any number of arguments. The same syntax works in libraries and, as the examples below show, it can also be combined with other ways of specifying arguments:
def any_arguments(*args):
print "Got arguments:"
for arg in args:
print arg
def one_required(required, *others):
print "Required: %s\nOthers:" % required
for arg in others:
print arg
def also_defaults(req, def1="default 1", def2="default 2", *rest):
print req, def1, def2, rest
|Test Case
|Any Arguments
|Any Arguments
|Any Arguments
|arg 1
|arg 2
|arg 2
|arg 4
|arg 5
|One Required
|required arg
|One Required
|required arg
|another arg
|yet another
|Also Defaults
|Also Defaults
|these two
|have defaults
|Also Defaults
Robot supports Java varargs syntax for defining variable number of arguments. Robot also will translate an array as the last argument in a keyword signature as a list of variable number of arguments. In this case, all leftover arguments to the keyword are packed into the list. This also works if the keyword is used with one argument less than the actual number of arguments in the signature - in this case the array at the end will be empty.
Robot's support for variable number of arguments in Java has one limitation: it only works if the method has only one signature. Thus it is not possible to have a Java keyword that has both the default values and a variable number of arguments. Of course, having a number of required arguments is still possible, as the examples below illustrate:
public void anyNumberOfArguments(String... varargs) {
System.out.println("Got arguments:");
for (String arg: varargs) {
public void oneArgumentRequired(String required, String... others) {
System.out.println("Required: " + required + "\nOthers:");
for (String arg: others) {
public void usingAnArray(String[] args) {
System.out.println("Got arguments:");
for (String arg: args) {
Normally keyword arguments come to Robot Framework as strings. If keywords require some other types, it is possible to either use variables or convert strings to required types inside keywords. With Java keywords base types are also coerced automatically.
Because arguments in Python do not have any type information, there is no possibility to automatically convert strings to other types when using Python libraries. Calling a Python method implementing a keyword with a correct number of arguments always succeeds, but the execution fails later if the arguments are incompatible. Luckily with Python it is simple to convert arguments to suitable types inside keywords:
def connect_to_host(address, port=25):
port = int(port)
# ...
Arguments to Java methods have types, and starting from Robot Framework 2.1 all the base types are handled automatically. This means that arguments that are normal strings in the test data are coerced to correct type at runtime. The types that can be coerced are:
The coercion is done for arguments that have the same or compatible type across all the signatures of the keyword method. In the following example, the conversion can be done for keywords doubleArgument and compatibleTypes, but not for conflictingTypes.
public void doubleArgument(double arg) {}
public void compatibleTypes(String arg1, Integer arg2) {}
public void compatibleTypes(String arg2, Integer arg2, Boolean arg3) {}
public void conflictingTypes(String arg1, int arg2) {}
public void conflictingTypes(int arg1, String arg2) {}
The coercion works with the numeric types if the test data has a string containing a number, and with the boolean type the data must contain either string true or false. Coercion is only done if the original value was a string from the test data, but it is of course still possible to use variables containing correct types with these keywords. Using variables is the only option if keywords have conflicting signatures.
|Test Case
|Double Argument
|Double Argument
|# scientific notation
|Compatible Types
|Hello, world!
|Compatible Types
|Hi again!
|No Coercion
|Double Argument
|Conflicting Types
|# must use variables
|Conflicting Types
After a method implementing a keyword is called, it can use any mechanism to communicate with the system under test. It can then also send messages to Robot Framework's log file, return information that can be saved to variables and, most importantly, report if the keyword passed or not.
Reporting keyword status is done simply using exceptions. If an executed method raises an exception, the keyword status is FAIL, and if it returns normally, the status is PASS.
The error message shown in logs, reports and the console is created from the exception type and its message. With generic exceptions (for example, AssertionError, Exception, and RuntimeError), only the exception message is used, and with others, the message is created in the format ExceptionType: Actual message. In both cases, it is important for the users that the exception message is as informative as possible.
If the error message is longer than 40 lines, it will be automatically cut from the middle to prevent reports from getting too long and difficult to read. The full error message is always shown in the log message of the failed keyword.
The traceback of the exception is also logged using DEBUG log level. These messages are not visible in log files by default because they are very rarely interesting for normal users. When developing libraries, it is often a good idea to run tests using --loglevel DEBUG.
Starting from Robot Framework 2.5 it is possible to fail a test case so that the whole test execution is stopped. This is done simply by having a special ROBOT_EXIT_ON_FAILURE attribute with True value set on the exception raised from the keyword. This is illustrated in the examples below.
class MyFatalError(RuntimeError):
ROBOT_EXIT_ON_FAILURE = True
public class MyFatalError extends RuntimeException {
public static final boolean ROBOT_EXIT_ON_FAILURE = true;
Starting from Robot Framework 2.5 it is possible to continue test execution even when there are failures. The way to signal this from test libraries is adding a special ROBOT_CONTINUE_ON_FAILURE attribute with True value to the exception used to communicate the failure. This is demonstrated by the examples below.
class MyContinuableError(RuntimeError):
ROBOT_CONTINUE_ON_FAILURE = True
public class MyContinuableError extends RuntimeException {
public static final boolean ROBOT_CONTINUE_ON_FAILURE = true;
Exception messages are not the only way to give information to the users. In addition to that, methods can also send messages to log files simply by writing to standard output (stdout) or standard error (stderr), and they can even use different log levels.
By default, everything written by a method into standard output is written to the log file as a single entry with the log level INFO. Messages written into standard error are handled similarly otherwise, but they are echoed back to the original stderr after the keyword execution has finished. It is thus possible to use stderr if you need some messages to be visible on the console where tests are executed.
To use other log levels than INFO, or to create several messages, specify the log level explicitly by embedding the level into the message in the format *LEVEL* Actual log message, where *LEVEL* must be in the beginning of a line and LEVEL is one of the available logging levels TRACE, DEBUG, INFO, WARN and HTML.
Starting from Robot Framework 2.1 messages with WARN level are automatically written into the console and into separate Test Execution Errors section in log files. This makes warnings more visible than other messages and allows using them for reporting important but non-critical problems to users.
Everything normally logged by the library will be converted into a format that can be safely represented as HTML. For example, <b>foo</b> will be displayed in the log exactly like that and not as foo. If libraries want to use formatting, links, display images and so on, they can use a special pseudo log level HTML. Robot Framework will write these messages directly into the log with the INFO level, so they can use any HTML syntax they want. Notice that this feature needs to be used with care, because one badly placed </table> tag can ruin the log file quite badly.
In most cases, the INFO level is adequate. The levels below it, DEBUG and TRACE, are useful for writing debug information. These messages are normally not shown, but they can facilitate debugging possible problems in the library itself. The WARN level can be used to make messages more visible and HTML is useful if any kind of formatting is needed.
The following examples clarify how logging with different levels works. Java programmers should regard the code print 'message' as pseudocode meaning System.out.println("message");.
print 'Hello from a library.'
print '*WARN* Warning from a library.'
print '*INFO* Hello again!'
print 'This will be part of the previous message.'
print '*INFO* This is a new message.'
print '*INFO* This is <b>normal text</b>.'
print '*HTML* This is <b>bold</b>.'
print '*HTML* <a href="http://robotframework.org">Robot Framework</a>'
The final way for keywords to communicate back to the core framework is returning information retrieved from the system under test or generated by some other means. The returned values can be assigned to variables in the test data and then used as inputs for other keywords, even from different test libraries.
Values are returned using the return statement both from the Python and Java methods. Normally, one value is assigned into one scalar variable, as illustrated in the example below. This example also illustrates that it is possible to return any objects and to use extended variable syntax to access object attributes.
from mymodule import MyObject
def return_string():
return "Hello, world!"
def return_object(name):
return MyObject(name)
|${string} =
|Return String
|Should Be Equal
|Hello, world!
|${object} =
|Return Object
|Should Be Equal
Keywords can also return values so that they can be assigned into several scalar variables at once, into a list variable, or into scalar variables and a list variable. All these usages require that returned values are Python lists or tuples or in Java arrays, Lists, or Iterators.
def return_two_values():
return 'first value', 'second value'
def return_multiple_values():
return ['a', 'list', 'of', 'strings']
|${var2} =
|Return Two Values
|Should Be Equal
|first value
|Should Be Equal
|second value
|@{list} =
|Return Two Values
|Should Be Equal
|first value
|Should Be Equal
|second value
|@{li} =
|Return Multiple Values
|Should Be Equal
|${v1} ${v2}
|a list
|Should Be Equal
|@{li}[0] @{li}[1]
|of strings
A test library without documentation about what keywords it contains and what those keywords do is rather useless. To ease maintenance, it is highly recommended that library documentation is included in the source code and generated from it. Basically, that means using docstrings with Python and Javadoc with Java, as in the examples below.
class MyLibrary:
"""This is an example library with some documentation."""
def keyword_with_short_documentation(self, argument):
"""This keyword has only a short documentation"""
def keyword_with_longer_documentation(self):
"""First line of the documentation is here.
Longer documentation continues here and it can contain
multiple lines or paragraphs.
* This is an example library with some documentation.
public class MyLibrary {
* This keyword has only a short documentation
public void keywordWithShortDocumentation(String argument) {
* First line of the documentation is here.
* Longer documentation continues here and it can contain
* multiple lines or paragraphs.
public void keywordWithLongerDocumentation() {
Both Python and Java have tools for creating an API documentation of a library documented as above. However, outputs from these tools can be slightly technical for some users. Another alternative is using Robot Framework's own documentation tool libdoc.py. This tool can create a library documentation from both Python and Java libraries using the static library API, such as the ones above, but it also handles libraries using the dynamic library API and hybrid library API.
The first line of a keyword documentation is used for a special purpose and should contain a short overall description of the keyword. It is used as a short documentation, for example as a tool tip, by libdoc.py and also shown in the test logs. However, the latter does not work with Java libraries using the static API, because their documentations are lost in compilation and not available at runtime.
Any non-trivial test library needs to be thoroughly tested to prevent bugs in them. Of course, this testing should be automated to make it easy to rerun tests when libraries are changed.
Both Python and Java have excellent unit testing tools, and they suite very well for testing libraries. There are no major differences in using them for this purpose compared to using them for some other testing. The developers familiar with these tools do not need to learn anything new, and the developers not familiar with them should learn them anyway.
It is also easy to use Robot Framework itself for testing libraries and that way have actual end-to-end acceptance tests for them. There are plenty of useful keywords in the BuiltIn library for this purpose. One worth mentioning specifically is Run Keyword And Expect Error, which is useful for testing that keywords report errors correctly.
Whether to use a unit- or acceptance-level testing approach depends on the context. If there is a need to simulate the actual system under test, it is often easier on the unit level. On the other hand, acceptance tests ensure that keywords do work through Robot Framework. If you cannot decide, of course it is possible to use both the approaches.
After a library is implemented, documented, and tested, it still needs to be distributed to the users. With simple libraries consisting of a single file, it is often enough to ask the users to copy that file somewhere and set the library search path accordingly. More complicated libraries should be packaged to make the installation easier.
Since libraries are normal programming code, they can be packaged using normal packaging tools. With Python, good options include distutils, contained by Python's standard library, and the newer setuptools. A benefit of these tools is that library modules are installed into a location that is automatically in the library search path.
When using Java, it is natural to package libraries into a JAR archive. The JAR package must be put into the library search path before running tests, but it is easy to create a start-up script that does that automatically.
Sometimes there is a need to replace existing keywords with new ones or remove them altogether. Just informing the users about the change may not always be enough, and it is more efficient to get warnings at runtime. Starting from Robot Framework 2.0.2 this is possible by marking these keywords deprecated. This makes it easier to find old keywords from the test data and remove or replace them.
Keywords are deprecated by starting their documentation with *DEPRECATED*. When these keywords are executed, a warning containing rest of the short documentation is written both into the console and into separate Test Execution Errors section in log files. For example, if following keyword is executed there will be a warning like shown below in the log file.
def example_keyword(argument):
"""*DEPRECATED* Use keyword `Other Keyword` instead.
This keyword does something to given `argument` and returns the result.
return do_something(argument)
This deprecation system works with most test libraries and also with user keywords. The only exception are keywords implemented in a Java test library that uses the static library interface because their documentation is not available at runtime. With such keywords, it possible to use user keywords as wrappers and deprecate them.
There is a plan to implement a tool that can use the deprecation information for automatically replacing deprecated keywords. The tool will most likely get the name of the new keyword from the documentation so that it searches words inside backticks (`). Thus it would find Other Keyword from the earlier example. Note that libdoc.py also automatically creates internal links using the same syntax.
The dynamic API is in most ways similar to the static API. For example, reporting the keyword status, logging, and returning values works exactly the same way. Most importantly, there are no differences in importing dynamic libraries and using their keywords compared to other libraries, so you do not even need to know what APIs the libraries use.
The only difference between static and dynamic libraries is the way how Robot Framework discovers what keywords the library implements, what arguments and documentation they have and how those keywords are actually executed. With the static API, all this is done using reflection (except for the documentation of Java libraries), but dynamic libraries have special methods that are used for these purposes.
One of the benefits of the dynamic API is that you have more flexibility in organizing your library. With the static API, you have all keywords in one class (or module), whereas with the dynamic API, you can, for example, implement each keyword as a separate class, if you want. This use case is not so important with Python, because its dynamic capabilities and multi-inheritance already give plenty of flexibility and the hybrid library API is usually a better option.
Another major use case for the dynamic API is implementing a library so that it is only a proxy for an actual library on some other computer or another JVM. This kind of a proxy library can be very thin, and because keyword names are got dynamically, there is no need to update the proxy when new keywords are added into the actual library.
This section explains how the dynamic API works between Robot Framework and dynamic libraries. It does not matter for Robot Framework how these libraries are actually implemented (for example, how calls to the run_keyword method are mapped to a correct keyword implementation), and many different approaches are possible. However, if you use Java, you may want to examine JavaTools before implementing your own system. This collection of reusable tools supports several ways of creating keywords, and it is likely that it already has a mechanism that suites your needs.
Dynamic libraries tell what keywords they implement with the get_keyword_names method. The method also has the alias getKeywordNames that is recommended when writing Java. This method cannot take any arguments, and it must return a list of strings (in Python) or a string array (in Java) containing the names of the keywords that the library implements.
If the returned keyword names contain several words, they can be returned separated with spaces or underscores, or in the camelCase format. For example, ['first keyword', 'second keyword'], ['first_keyword', 'second_keyword'], and ['firstKeyword', 'secondKeyword'] would all result in the keywords First Keyword and Second Keyword.
Dynamic libraries must always have this method. If it is missing, or if calling it fails for some reason, the library is considered a static library, instead.
Dynamic libraries have a special run_keyword (alias runKeyword) method for executing their keywords. When a keyword from a dynamic library is used in the test data, Robot Framework uses the library's run_keyword method to get it executed. This method takes two arguments. The first argument is a string containing the name of the keyword to be executed in the same format as returned by get_keyword_names. The second argument is a list of arguments (an object array in Java) given to the keyword in the test data.
After the library has got the keyword name and arguments, it can execute the keyword freely, but it must use the same mechanism to communicate with the framework as static libraries. This means using exceptions for reporting keyword status, logging by writing to the standard output and using the return statement in run_keyword for returning something.
Every dynamic library must have both the get_keyword_names and run_keyword methods. The rest of the methods in the dynamic API are optional, so the example below shows a working (albeit trivial) dynamic library.
class DynamicExample:
def get_keyword_names(self):
return ['first keyword', 'second keyword']
def run_keyword(self, name, args):
print "Running keyword %s with arguments %s" % (name, args)
If a dynamic library only implements the get_keyword_names and run_keyword methods, Robot Framework does not have any information about the arguments that the implemented keywords need. For example, both First Keyword and Second Keyword in the example above could be used with any number of arguments. This is problematic, because most real keywords expect a certain number of keywords, and under these circumstances they would need to check the argument counts themselves.
Dynamic libraries can tell Robot Framework what arguments the keywords that it implements actually expect using get_keyword_arguments (alias getKeywordArguments) method. This method takes the name of a keyword as an argument and returns a list of strings (a string array in Java) containing the arguments accepted by that keyword.
Similarly as static keywords, dynamic keywords can require any number of arguments, have default values and accept a variable number of arguments. The syntax for how to represent all these different situations is explained in the following table. Note that the examples use Python lists of strings, but Java developers should be able to translate them to string arrays.
|Expected arguments
|How to represent
|Min / Max
|No arguments
|Empty list.
|One or more argument
|List of strings containing argument names.
|['one_argument'], ['a1', 'a2', 'a3']
|1/1, 3/3
|Default values for arguments
|Default values separated from names with =. Default values are always considered to be strings.
|['arg=default value'], ['a', 'b=1', 'c=2']
|0/1, 1/3
|Variable number of arguments
|Last argument has * before its name.
|['*arguments'], ['a', 'b=42', '*rest']
|0/any, 1/any
When the get_keyword_arguments is used, Robot Framework automatically calculates how many arguments the keywords require. If a keyword is used with an invalid number of arguments, an error occurs and run_keyword is not even called. The last column of the table above shows the minimum and maximum argument counts calculated from the presented examples.
The actual argument names do not matter when tests are executed, because only argument counts are of concern to Robot Framework. On the other hand, if the libdoc.py tool is used for documenting the library, arguments are shown in the documentation, in which case they need to have meaningful names.
The final special method that dynamic libraries can implement is get_keyword_documentation (alias getKeywordDocumentation). It takes a keyword name as an argument and, as the method name implies, returns its documentation as a string.
The returned documentation is used similarly as the keyword documentation string with static libraries implemented with Python. The main use case is getting keywords' documentations into a library documentation generated with libdoc.py. Additionally, the first line of the documentation (until the first \n) is shown in test logs.
All special methods in the dynamic API are listed in the table below. Method names are listed in the underscore format, but their camelCase aliases work exactly the same way.
|To return names of implemented keywords.
|name, arguments
|To execute the specified keyword with given arguments.
|To return keyword's argument specification. Optional.
|To return keyword's documentation. Optional.
It is possible to write a formal interface specification in Java, as below. However, remember that libraries do not need to implement any explicit interface, because Robot Framework directly checks with reflection if the library has the required get_keyword_names and run_keyword methods. Additionally, get_keyword_arguments and get_keyword_documentation are completely optional.
public interface RobotFrameworkDynamicAPI {
String[] getKeywordNames();
Object runKeyword(String name, Object[] arguments);
String[] getKeywordArguments(String name);
String getKeywordDocumentation(String name);
A good example of using the dynamic API is Robot Framework's own Remote library.
The hybrid library API is, as its name implies, a hybrid between the static API and the dynamic API. Just as with the dynamic API, it is possible to implement a library using the hybrid API only as a class.
Keyword names are got in the exactly same way as with the dynamic API. In practice, the library needs to have the get_keyword_names or getKeywordNames method returning a list of keyword names that the library implements.
In the hybrid API, there is no run_keyword method for executing keywords. Instead, Robot Framework uses reflection to find methods implementing keywords, similarly as with the static API. A library using the hybrid API can either have those methods implemented directly or, more importantly, it can handle them dynamically.
In Python, it is easy to handle missing methods dynamically with the __getattr__ method. This special method is probably familiar to most Python programmers and they can immediately understand the following example. Others may find it easier to consult Python Reference Manual first.
from somewhere import external_keyword
class HybridExample:
def get_keyword_names(self):
return ['my_keyword', 'external_keyword']
def my_keyword(self, arg):
print "My Keyword called with '%s'" % arg
def __getattr__(self, name):
if name == 'external_keyword':
return external_keyword
raise AttributeError("Non-existing attribute '%s'" % name)
Note that __getattr__ does not execute the actual keyword like run_keyword does with the dynamic API. Instead, it only returns a callable object that is then executed by Robot Framework.
Another point to be noted is that Robot Framework uses the same names that are returned from get_keyword_names for finding the methods implementing them. Thus the names of the methods that are implemented in the class itself must be returned in the same format as they are defined. For example, the library above would not work correctly, if get_keyword_names returned My Keyword instead of my_keyword.
The hybrid API is not very useful with Java, because it is not possible to handle missing methods with it. Of course, it is possible to implement all the methods in the library class, but that brings few benefits compared to the static API.
When this API is used, Robot Framework uses reflection to find the methods implementing keywords, similarly as with the static API. After getting a reference to the method, it searches for arguments and documentation from it, in the same way as when using the static API. Thus there is no need for special methods for getting arguments and documentation like there is with the dynamic API.
When implementing a test library in Python, the hybrid API has the same dynamic capabilities as the actual dynamic API. A great benefit with it is that there is no need to have special methods for getting keyword arguments and documentation. It is also often practical that the only real dynamic keywords need to be handled in __getattr__ and others can be implemented directly in the main library class.
Because of the clear benefits and equal capabilities, the hybrid API is in most cases a better alternative than the dynamic API when using Python. One notable exception is implementing a library as a proxy for an actual library implementation elsewhere, because then the actual keyword must be executed elsewhere and the proxy can only pass forward the keyword name and arguments.
A good example of using the hybrid API is Robot Framework's own Telnet library.
Test libraries implemented with Python can use Robot Framework's internal modules, for example, to get information about the executed tests and the settings that are used. This powerful mechanism to communicate with the framework should be used with care, though, because all Robot Framework's APIs are not meant to be used by externally and they might change radically between different framework versions.
The safest API to use are methods implementing keywords in the BuiltIn library. Changes to keywords are rare and they are always done so that old usage is first deprecated. One of the most useful methods is replace_variables which allows accessing currently available variables. The following example demonstrates how to get ${OUTPUT_DIR} which is one of the many handy automatic variables. It is also possible to set new variables from libraries using set_test_variable, set_suite_variable and set_global_variable.
import os.path
from robot.libraries.BuiltIn import BuiltIn
def do_something(argument):
output = do_something_that_creates_a_lot_of_output(argument)
outputdir = BuiltIn().replace_variables('${OUTPUTDIR}')
path = os.path.join(outputdir, 'results.txt')
f = open(path, 'w')
print '*HTML* Output written to <a href="results.txt">results.txt</a>'
The only catch with using methods from BuiltIn is that all run_keyword method variants must be handled specially. Methods that use run_keyword methods have to be registered as run keywords themselves using register_run_keyword method in BuiltIn module. This method's documentation explains why this needs to be done and obviously also how to do it.
The plan is to document all the internal modules better so that it is easier to decide which can be used and how they should be used. If you are unsure is using some API safe, please send a question to either user or developer mailing list.
This section explains different approaches how to add new functionality to existing test libraries and how to use them in your own libraries otherwise.
If you have access to the source code of the library you want to extend, you can naturally modify the source code directly. The biggest problem of this approach is that it can be hard for you to update the original library without affecting your changes. For users it may also be confusing to use a library that has different functionality than the original one. Repackaging the library may also be a big extra task.
This approach works extremely well if the enhancements are generic and you plan to submit them back to the original developers. If your changes are applied to the original library, they are included in the future releases and all the problems discussed above are mitigated. If changes are non-generic, or you for some other reason cannot submit them back, the approaches explained in the subsequent sections probably work better.
Another straightforward way to extend an existing library is using inheritance. This is illustrated by the example below that adds new Title Should Start With keyword to the SeleniumLibrary. This example uses Python, but you can obviously extend an existing Java library in Java code the same way.
from SeleniumLibrary import SeleniumLibrary
class ExtendedSeleniumLibrary(SeleniumLibrary):
def title_should_start_with(self, expected):
title = self.get_title()
if not title.startswith(expected):
raise AssertionError("Title '%s' did not start with '%s'"
% (title, expected))
A big difference with this approach compared to modifying the original library is that the new library has a different name than the original. A benefit is that you can easily tell that you are using a custom library, but a big problem is that you cannot easily use the new library with the original. First of all your new library will have same keywords as the original meaning that there is always conflict. Another problem is that the libraries do not share their state.
This approach works well when you start to use a new library and want to add custom enhancements to it from the beginning. Otherwise other mechanisms explained in this section are probably better.
Because test libraries are technically just classes or modules, a simple way to use another library is importing it and using its methods. This approach works great when the methods are static and do not depend on the library state. This is illustrated by the earlier example that uses Robot Framework's BuiltIn library.
If the library has state, however, things may not work as you would hope. The library instance you use in your library will not be the same as the framework uses, and thus changes done by executed keywords are not visible to your library. The next section explains how to get an access to the same library instance that the framework uses.
Robot Framework 2.5.2 added new BuiltIn keyword Get Library Instance that can be used to get the currently active library instance from the framework itself. The library instance returned by this keyword is the same as the framework itself uses, and thus there is no problem seeing the correct library state. Although this functionality is available as a keyword, it is typically used in test libraries directly by importing the BuiltIn library class as discussed earlier. The following example illustrates how to implement the same Title Should Start With keyword as in the earlier example about using inheritance.
from robot.libraries.BuiltIn import BuiltIn
def title_should_start_with(expected):
seleniumlib = BuiltIn().get_library_instance('SeleniumLibrary')
title = seleniumlib.get_title()
if not title.startswith(expected):
raise AssertionError("Title '%s' did not start with '%s'"
% (title, expected))
This approach is clearly better than importing the library directly and using it when the library has a state. The biggest benefit over inheritance is that you can use the original library normally and use the new library in addition to it when needed. That is demonstrated in the example below where the code from the previous examples is expected to be available in a new library SeLibExtensions.
|Test Case
|Open Browser
|# SeleniumLibrary
|Title Should Start With
|# SeLibExtensions
Test libraries that use the dynamic or hybrid library API often have their own systems how to extend them. With these libraries you need to ask guidance from the library developers or consult the library documentation or source code.
The remote library interface provides means for having test libraries on different machines than where Robot Framework itself is running, and also for implementing libraries using other languages than the natively supported Python and Java. For a test library user remote libraries look pretty much the same as any other test library, and developing test libraries using the remote library interface is also very close to creating normal test libraries.
There are two main reasons for using the remote library API:
The remote library interface is provided by the Remote library that is one of the standard libraries starting from Robot Framework 2.1. This library does not have any keywords of its own, but it works as a proxy between the core framework and keywords implemented elsewhere. The Remote library interacts with actual library implementations through remote servers, and the Remote library and servers communicate using a simple remote protocol on top of an XML-RPC channel. The high level architecture of all this is illustrated in the picture below:
The Remote library needs to know the address of the remote server but otherwise importing it and using keywords that it provides is no different to how other libraries are used. If you need to use the Remote library multiple times in a test suite, or just want to give it a more descriptive name, you can import it using the WITH NAME syntax.
The URL used by the first example above is also the default address that the Remote library uses if no address is given. Similarly port 8270 is the default port the provided remote servers use. (82 and 70 are the ASCII codes of letters R and F, respectively.)
Before the Remote library can be imported, the remote server providing the actual keywords must be started. If the server is started before launching the test execution, it is possible to use the normal Library setting like in the above example. Alternatively other keywords, for example from OperatingSystem or SSH libraries, can start the server up, but then you may need to use Import Library keyword because the library is not available when the test execution starts.
How a remote server can be stopped depends on how it is implemented. Following methods work with the servers distributed with Robot Framework:
Because the XML-RPC protocol does not support all possible object types, the values transferred between the Remote library and remote servers must be converted to compatible types. This applies to the keyword arguments the Remote library passes to remote servers and to the return values servers give back to the Remote library.
The conversions are done using following rules:
Robot Framework 2.1 includes remote server implementations written both in Python and Ruby. These servers, as well as the example libraries shown below and an example test case file, are included in source distributions under tools/remoteserver directory and available also at http://code.google.com/p/robotframework/wiki/RemoteLibrary.
The provided servers are designed so that it is easy to create test libraries using them. With both of the servers the basic procedure is as follows:
Both these steps can be done in the same module as illustrated by the examples below. Executing these modules as scripts from the command line will start the remote server so that it serves the keywords implemented in the library.
This example demonstrates how to use the Python version of the remote server. The example library implements keywords Count Items In Directory and Strings Should Be Equal.
#!/usr/bin/env python
import os
import sys
class ExampleRemoteLibrary:
def count_items_in_directory(self, path):
return len([ i for i in os.listdir(path) if not i.startswith('.') ])
def strings_should_be_equal(self, str1, str2):
print "Comparing '%s' to '%s'" % (str1, str2)
if str1 != str2:
raise AssertionError("Given strings are not equal")
if __name__ == '__main__':
from robotremoteserver import RobotRemoteServer
RobotRemoteServer(ExampleRemoteLibrary(), *sys.argv[1:])
This example uses the Ruby remote server and provides exactly same keywords as the previous Python example:
#!/usr/bin/env ruby
class ExampleRemoteLibrary
def count_items_in_directory(path)
Dir.entries(path).find_all{|i| not i.match('^\.')}.length
def strings_should_be_equal(str1, str2)
puts "Comparing '#{str1}' to '#{str2}'"
if str1 != str2
raise RuntimeError, "Given strings are not equal"
if __FILE__ == $0
require "robotremoteserver"
RobotRemoteServer.new(ExampleRemoteLibrary.new, *ARGV)
This section explains the protocol that is used between the Remote library and remote servers. This information is mainly targeted for people who want to create new remote servers. The provided Python and Ruby servers can also be used as examples.
The remote protocol is implemented on top of XML-RPC, which is a simple remote procedure call protocol using XML over HTTP. Most mainstream languages (Python, Java, C, Ruby, Perl, Javascript, PHP, ...) have a support for XML-RPC either built-in or as extensions.
A remote server is an XML-RPC server that must have the same methods in its public interface as the dynamic library API has. Only get_keyword_names and run_keyword are actually required, but get_keyword_arguments and get_keyword_documentation are also recommended. Notice that using camelCase format in method names is not possible currently. How the actual keywords are implemented is not relevant for the Remote library. A remote server can either act as a wrapper for real test libraries, like the provided Python and Ruby servers do, or it can implement keywords itself.
Remote servers should additionally have stop_remote_server method in their public interface to ease stopping them. They should also expose this method as Stop Remote Server keyword automatically so that it can be used in the test data regardless of the test library.
The Remote library gets a list of keywords that the remote server provides using get_keyword_names method. This method must return the keyword names as a list of strings.
Remote servers can, and should, also implement get_keyword_arguments and get_keyword_documentation methods to provide more information about the keywords. Both of these keywords get the name of the keyword as an argument. Arguments must be returned as a list of strings in the same format as with dynamic libraries, and documentation must be returned as a string.
When the Remote library wants the server to execute some keyword, it calls remote server's run_keyword method and passes it the keyword name and a list of arguments. Base types can be used as arguments directly but more complex types are converted to supported types. The server must return results of the execution in a result dictionary (or map, depending on terminology) containing items explained in the following table.
|Mandatory execution status. Either PASS or FAIL.
|Possible output to write into the log file. Must be given as a single string but can contain multiple messages and different log levels in format *INFO* First message\n*INFO* Second\n*WARN* Another message.
|Possible return value. Must be one of the supported types.
|Possible error message. Used only when the execution fails.
|Possible stack trace to write into the log file using DEBUG level when the execution fails.
Robot Framework has a listener interface that can be used to receive notifications about test execution. Listeners are classes with certain special methods, and they can be implemented both with Python and Java. Starting from version 2.0.2, it is also possible to implement listeners as Python modules. Example uses of the listener interface include external test monitors, sending a mail message when a test fails, and communicating with other systems.
Listeners are taken into use from the command line with the --listener option, so that the name of the listener is given to it as an argument. The listener name is got from the name of the class or module implementing the listener interface, similarly as test library names are got from classes implementing them. The specified listeners must be in the same module search path where test libraries are searched from when they are imported. Other option is to give an absolute or a relative path to the listener file similarly as with test libraries. It is possible to take multiple listeners into use by using this option several times.
Starting from version 2.0.2, it is also possible to give arguments to listener classes from the command line. Arguments are specified after the listener name (or path) using a colon as a separator. This approach provides only string type arguments and arguments obviously cannot contain colons. However, it should be pretty easy to listeners to go around these limitations.
pybot --listener MyListener tests.html jybot --listener com.company.package.Listener tests.html pybot --listener path/to/MyListener.py tests.html pybot --listener module.Listener --listener AnotherListener tests.html pybot --listener ListenerWithArgs:arg1:arg2 pybot --listener path/to/MyListener.java:argument tests.html
Robot Framework creates an instance of the listener class with given arguments when test execution starts. During the test execution, Robot Framework calls listeners' methods when test suites, test cases and keywords start and end. It also calls the appropriate methods when output files are ready, and finally at the end it calls the close method. A listener is not required to implement any official interface, and it only needs to have the methods it actually needs.
The signatures of methods related to test execution progress were changed in Robot Framework 2.1. This change was made so that new information can be added to listener interface without breaking existing listeners. The old signatures will continue to work, but they will be deprecated in some future version, so all new listeners should be implemented with signatures described in the table below. The most recent detailed description of the old listener interface can be found in User Guide of Robot Framework 2.0.4.
A listener must have attribute ROBOT_LISTENER_API_VERSION defined in order to be recognized as a new style listener. Value of the ROBOT_LISTENER_API_VERSION attribute must be 2, either as a string or as an integer. The examples below are implemented as new style listeners.
Starting from Robot Framework 2.1, all listener methods related to test execution progress have the same signature method(name, attributes), where attributes is a dictionary containing details of the event. The following table lists all the available methods in the listener interface and the contents of the attributes dictionary, where applicable. Keys of the dictionary are strings. All of these methods have also camelCase aliases. Thus, for example, startSuite is a synonym to start_suite.
|Attributes / Explanation
|name, attributes
Keys in the attributes dictionary:
The last four were added in Robot Framework 2.5
|name, attributes
Keys in the attributes dictionary:
|name, attributes
Keys in the attributes dictionary:
|name, attributes
Keys in the attributes dictionary:
|name, attributes
Keys in the attributes dictionary:
|name, attributes
Keys in the attributes dictionary:
Called when an executed keyword writes a log message. message is a dictionary with following keys:
New in Robot Framework 2.1.3.
Called when the framework itself writes a syslog message. message is a dictionary with same keys as with log_message method.
New in Robot Framework 2.1.3.
|Called when writing to an output file is finished. The path is an absolute path to the file. When outputs are split, called for each finished file.
|Called when writing to a log file is finished. The path is an absolute path to the file. When outputs are split, called for each finished file.
|Called when writing to a report file is finished. The path is an absolute path to the file.
|Called when writing to a summary file is finished. The path is an absolute path to the file.
|Called when writing to a debug file is finished. The path is an absolute path to the file.
|Called after all test suites, and test cases in them, have been executed.
The available methods and their arguments are also shown in a formal Java interface specification below. Contents of the java.util.Map attributes are as in the table above. It should be remembered that a listener does not need to implement any explicit interface or have all these methods.
public interface RobotListenerInterface {
public static final int ROBOT_LISTENER_API_VERSION = 2;
void startSuite(String name, java.util.Map attributes);
void endSuite(String name, java.util.Map attributes);
void startTest(String name, java.util.Map attributes);
void endTest(String name, java.util.Map attributes);
void startKeyword(String name, java.util.Map attributes);
void endKeyword(String name, java.util.Map attributes);
void logMessage(java.util.Map message);
void message(java.util.Map message);
void outputFile(String path);
void logFile(String path);
void reportFile(String path);
void summaryFile(String path);
void debugFile(String path);
void close();
The first simple example is implemented in a Python module. It mainly illustrates that using the listener interface is not very complicated.
def start_test(name, attrs):
print 'Executing test %s' % name
def start_keyword(name, attrs):
print 'Executing keyword %s with arguments %s' % (name, attrs['args'])
def log_file(path):
print 'Test log available at %s' % path
def close():
print 'All tests executed'
The second example, which still uses Python, is slightly more complicated. It writes all the information it gets into a text file in a temporary directory without much formatting. The filename may be given from the command line, but also has a default value. Note that in real usage, the debug file functionality available through the command line option --debugfile is probably more useful than this example.
import os.path
import tempfile
class PythonListener:
def __init__(self, filename='listen.txt'):
outpath = os.path.join(tempfile.gettempdir(), filename)
self.outfile = open(outpath, 'w')
def start_suite(self, name, attrs):
self.outfile.write("%s '%s'\n" % (name, attrs['doc']))
def start_test(self, name, attrs):
tags = ' '.join(attrs['tags'])
self.outfile.write("- %s '%s' [ %s ] :: " % (name, attrs['doc'], tags))
def end_test(self, name, attrs):
if attrs['status'] == 'PASS':
self.outfile.write('FAIL: %s\n' % attrs['message'])
def end_suite(self, name, attrs):
self.outfile.write('%s\n%s\n' % (attrs['status'], attrs['message']))
def close(self):
The third example implements the same functionality as the previous one, but uses Java instead of Python.
import java.io.*;
import java.util.Map;
import java.util.List;
public class JavaListener {
public static final int ROBOT_LISTENER_API_VERSION = 2;
public static final String DEFAULT_FILENAME = "listen_java.txt";
private BufferedWriter outfile = null;
public JavaListener() throws IOException {
public JavaListener(String filename) throws IOException {
String tmpdir = System.getProperty("java.io.tmpdir");
String sep = System.getProperty("file.separator");
String outpath = tmpdir + sep + filename;
outfile = new BufferedWriter(new FileWriter(outpath));
public void startSuite(String name, Map attrs) throws IOException {
outfile.write(name + " '" + attrs.get("doc") + "'\n");
public void startTest(String name, Map attrs) throws IOException {
outfile.write("- " + name + " '" + attrs.get("doc") + "' [ ");
List tags = (List)attrs.get("tags");
for (int i=0; i < tags.size(); i++) {
outfile.write(tags.get(i) + " ");
outfile.write(" ] :: ");
public void endTest(String name, Map attrs) throws IOException {
String status = attrs.get("status").toString();
if (status.equals("PASS")) {
else {
outfile.write("FAIL: " + attrs.get("message") + "\n");
public void endSuite(String name, Map attrs) throws IOException {
outfile.write(attrs.get("status") + "\n" + attrs.get("message") + "\n");
public void close() throws IOException {
Robot Framework has some public APIs which are intended to help in developing supporting tools or extending the processing of input or output data. These APIs are implemented as Python modules, and as such can only be used from Python and Jython scripts and programs.
Unfortunately, these APIs are not particularly well documented, and are subject to change and refinement in the future. The plan is to enhance the documentation in the future, but before that the options for getting more information are asking help from Robot Framework developers, investigating existing supporting tools that use these APIs, or just taking a look at the source code of Robot Framework.
This API consists of a factory method for reading a Robot Framework output file into a TestSuite object that contains all the relevant information about the results of the test execution. Signature of method is TestSuite(outpath), where outpath is a path to an existing output file. The returned TestSuite object can be used to process the results of the test run.
Here is an example that reads a given output file and marks each test case whose execution time is longer than three minutes failed. The TestSuite object is then serialized and normal log and report files could be generated with rebot.
#!/usr/bin/env python
"""Usage: check_test_times.py inpath [outpath]
Reads result of a test run from Robot output file and checks that no test
took longer than 3 minutest to execute. If outpath is not given, the
result is written over the original file.
import sys
from robot.output import TestSuite
def check_tests(inpath, outpath=None):
if not outpath:
outpath = inpath
suite = TestSuite(inpath)
def _check_execution_times(suite):
for test in suite.tests:
if test.status == 'PASS' and test.elapsedtime > 1000 * 60 * 3:
test.status = 'FAIL'
test.message = 'Test execution time was too long: %s' % test.elapsedtime
for suite in suite.suites:
if __name__ == '__main__':
except TypeError:
print __doc__
This API consists of run method, which can be used for starting the test execution. Signature of the method is run(*datasources, **options), where datasources are paths to files and directories to be executed and options are same as normal command line options without hyphens.
from robot import run
run('tests.html', log='mylog.html', include=['tag1', 'tag2'])
Equivalent command line usage would be:
pybot --log mylog.html --include tag1 --include tag2 tests.html
This method can be used only once in a given context. This problem will be fixed in future releases.
Package robot.parsing contains tools for parsing and handling test data. TestCaseFile and TestDataDirectory classes can be instantiated with named argument source to start parsing existing test data. Example below shows how to parse names of tests from a test file. For more details please see the source code of Robot Framework directly.
from robot.parsing import TestCaseFile
suite = TestCaseFile(source='path/to/tests.html')
print 'Suite: ', suite.name
for test in suite.testcase_table:
print test.name
This API consists of a factory method for parsing given input files into a runnable TestSuite object. The signature of this robot.running.TestSuite method is TestSuite(datasources, settings), where data sources are paths to files and directories similarly as when executing tests from the command line.
Robot Framework has a global logger that is responsible for error reporting and logging in general. This LOGGER instance is a proxy and it is possible to register new loggers to it. Registered loggers get notifications when something happens and they can report events however they want. A console logger writing warnings and errors into the standard error stream is registered automatically but it can be disabled. For more information about how to register loggers and what methods loggers can implement, see the source code and documentation of robot.output.LOGGER.
Starting from Robot Framework 2.5.2 Robot Framework is also distributed as a standalone jar file that contains both Jython and Robot Framework. This allows command line execution with only Java installed, but the jar file also provides an API for Java usage. The current API documentation is available online.
The simple code below demonstrates how Robot Framework test execution can be started from a Java program:
import org.robotframework.RobotFramework;
public class Test {
public void runTests() {
int rc = RobotFramework.run(new String[] { "--outputdir", "/tmp", "mytests" });
if (rc == 0)
System.out.println("All tests passed");
else if (rc <= 250)
System.out.println(rc + " tests failed.");
System.out.println("Error occurred");
Return value of RobotFramework.run has same meaning as return code of Robot Framework execution.
The Setting table is used to import test libraries, resource files and variable files and to define metadata for test suites and test cases. It can be included in test case files and resource files. Note that in a resource file, a Setting table can only include settings for importing libraries, resources, and variables.
|Used for taking test libraries into use.
|Used for taking resource files into use.
|Used for taking variable files into use.
|Used for specifying a test suite or resource file documentation.
|Used for setting free test suite metadata.
|Suite Setup
|Used for specifying the suite setup.
|Suite Teardown
|Used for specifying the suite teardown.
|Suite Precondition
|A synonym for Suite Setup.
|Suite Postcondition
|A synonym for Suite Teardown.
|Force Tags
|Used for specifying forced values for tags when tagging test cases.
|Default Tags
|Used for specifying default values for tags when tagging test cases.
|Test Setup
|Used for specifying a default test setup.
|Test Teardown
|Used for specifying a default test teardown.
|Test Precondition
|A synonym for Test Setup.
|Test Postcondition
|A synonym for Test Teardown.
|Test Template
|Used for specifying a default template keyword for test cases.
|Test Timeout
|Used for specifying a default test case timeout.
The settings in the Test Case table are always specific to the test case for which they are defined. Some of these settings override the default values defined in the Settings table.
|Used for specifying a test case documentation.
|Used for tagging test cases.
|Used for specifying a test setup.
|Used for specifying a test teardown.
|A synonym for [Setup].
|A synonym for [Teardown].
|Used for specifying a template keyword.
|Used for specifying a test case timeout.
Settings in the Keyword table are specific to the user keyword for which they are defined.
|Used for specifying a user keyword documentation.
|Used for specifying user keyword arguments.
|Used for specifying user keyword return values.
|Used for specifying a user keyword timeout.
This appendix lists all the command line options that are available when executing test cases with pybot or jybot, and when post-processing outputs with rebot.
-N, --name <name> Sets the name of the top-level test suite. -D, --doc <document> Sets the documentation of the top-level test suite. -M, --metadata <name:value> Sets free metadata for the top level test suite. -G, --settag <tag> Sets the tag(s) to all executed test cases. -t, --test <name> Selects the test cases by name. -s, --suite <name> Selects the test suites by name. -i, --include <tag> Selects the test cases by tag. -e, --exclude <tag> Selects the test cases by tag. -c, --critical <tag> Tests that have the given tag are considered critical. -n, --noncritical <tag> Tests that have the given tag are not critical. --runmode <mode> Sets the execution mode for this test run. Valid modes are ContinueOnFailure, ExitOnFailure, SkipTeardownOnExit, DryRun, and Random:<what>. -v, --variable <name:value> Sets individual variables. -V, --variablefile <path:args> Sets variables using variable files. -d, --outputdir <dir> Defines where to create output files. -o, --output <file> Sets the path to the generated output file. -l, --log <file> Sets the path to the generated log file. -r, --report <file> Sets the path to the generated report file. -S, --summary <file> Sets the path to the generated summary file. -b, --debugfile <file> The debug file that is written during execution. -T, --timestampoutputs Adds a timestamp to all output files. --splitoutputs <level> Splits output and log files. --logtitle <title> Sets a title for the generated test log. --reporttitle <title> Sets a title for the generated test report. --reportbackground <colors> Sets background colors for the generated report and summary. --summarytitle <title> Sets a title for the generated summary report. -L, --loglevel <level> Sets the threshold level for logging. --suitestatlevel <level> Defines how many levels to show in the Statistics by Suite table in outputs. --tagstatinclude <tag> Includes only these tags in the Statistics by Tag and Test Details by Tag tables in outputs. --tagstatexclude <tag> Excludes these tags from the Statistics by Tag and Test Details by Tag tables in outputs. --tagstatcombine <tags:title> Creates combined statistics based on tags. --tagdoc <pattern:doc> Adds documentation to the specified tags. --tagstatlink <pattern:link:title> Adds external links to the Statistics by Tag table in outputs. --listener <name:args> Sets a listener for monitoring test execution. -W, --monitorwidth <chars> Sets the width of the monitor output. -C, --monitorcolors <on|off|force> Specifies are colors used in the console. -P, --pythonpath <path> Additional locations where to search test libraries from when they are imported. -E, --escape <what:with> Escapes characters that are problematic in the console. -A, --argumentfile <path> A text file to read more arguments from. -h, --help Prints usage instructions. --version Prints the version information.
-N, --name <name> Sets the name of the top level test suite. -D, --doc <document> Sets the documentation of the top-level test suite. -M, --metadata <name:value> Sets free metadata for the top-level test suite. -G, --settag <tag> Sets the tag(s) to all processed test cases. -t, --test <name> Selects the test cases by name. -s, --suite <name> Selects the test suites by name. -i, --include <tag> Selects the test cases by tag. -e, --exclude <tag> Selects the test cases by tag. -c, --critical <tag> Tests that have the given tag are considered critical. -n, --noncritical <tag> Tests that have the given tag are not critical. -d, --outputdir <dir> Defines where to create output files. -o, --output <file> Sets the path to the generated output file. -l, --log <file> Sets the path to the generated log file. -r, --report <file> Sets the path to the generated report file. -S, --summary <file> Sets the path to the generated summary file. -T, --timestampoutputs Adds a timestamp to all output files. --splitoutputs <level> Splits output and log files. --logtitle <title> Sets a title for the generated test log. --reporttitle <title> Sets a title for the generated test report. --reportbackground <colors> Sets background colors for the generated report and summary. --summarytitle <title> Sets a title for the generated summary report. -L, --loglevel <level> Sets the threshold level to select log messages. New in Robot Framework 2.5.2. --suitestatlevel <level> Defines how many levels to show in the Statistics by Suite table in outputs. --tagstatinclude <tag> Includes only these tags in the Statistics by Tag and Test Details by Tag tables in outputs. --tagstatexclude <tag> Excludes these tags from the Statistics by Tag and Test Details by Tag tables in outputs. --tagstatcombine <tags:title> Creates combined statistics based on tags. --tagdoc <pattern:doc> Adds documentation to the specified tags. --tagstatlink <pattern:link:title> Adds external links into the Statistics by Tag table in outputs. --removekeywords <all|passed> Removes keyword data from the generated outputs. --starttime <timestamp> Sets the starting time of test execution when creating combined reports. --endtime <timestamp> Sets the ending time of test execution when creating combined reports. -E, --escape <what:with> Escapes characters that are problematic in the console. -A, --argumentfile <path> A text file to read more arguments from. -h, --help Prints usage instructions. --version Prints the version information.
These templates can be used when creating test data for Robot Framework. There are templates both for test case and resource files, and resource templates can also be used to create test suite initialization files. Templates are available both in HTML and TSV format and they can be customized freely.
Templates are available through this user guide, they are included in the source distribution, and they can also be downloaded from http://code.google.com/p/robotframework/wiki/Templates.
The available supporting tools for Robot Framework are described in this appendix.
These tools are distributed with Robot Framework. They are included in the source distribution and also available through http://code.google.com/p/robotframework/wiki/SupportingTools.
libdoc.py is tool for generating HTML or XML documentation from keywords of a test library or a resource file.
testdoc.py is tool for generating high level documentation of a given test suite, including the names of suites and tests as well as top-level keywords.
risto.py is a tool for generating graphs about historical statistics of test executions.
robotdiff.py is a tool for generating diff reports from Robot Framework output files.
times2csv.py is a tool for generating start, end and elapsed time information about suites, tests and keywords in CSV format.
fileviewer.py is a graphical tool implementing UNIX tail -like functionality. It is especially designed to view debug files.
One click installer is an AutoIT script that installs Robot Framework and its dependencies.
statuschecker.py is a tool for verifying that test case statuses and messages and also keyword log messages are as expected.
These tools are developed as separate projects.
RIDE is a standalone tool for editing test data. It helps in creating, editing and maintaining of Robot Framework test data. The project pages are at http://code.google.com/p/robotframework-ride/.
mabot is a standalone tool for reporting manual test execution results. It enables storing and reporting manual test cases along with automated Robot Framework test cases. The project pages are at http://code.google.com/p/robotframework-mabot/.
JavaTools is an external collection of tools that simplify creation of larger Java test libraries by offering several dynamic ways of resolving available keywords at runtime. For more information, see http://code.google.com/p/robotframework-javatools/.
It is possible to use simple HTML formatting with test suite, test case and user keyword documentation in the test data, as well as when documenting test libraries. The formatting is similar to the style used in most wikis, and it is designed to be understandable both as plain text and after the HTML transformation.
The documentation used for test suites, test cases and keywords is subject to general parsing rules of the test data. This means that normal newlines are not preserved, and dividing documentation into lines and paragraphs requires using a literal newline character sequence (\n), as illustrated in the example below.
First line.\n
Second paragraph, this time\n
with multiple lines.
With library documentations normal newlines are enough, and for example the following keyword documentation would create same end result as the above test suite documentation.
def example_keyword():
"""First line.
Second paragraph, this time
with multiple lines.
Bold text can be created by having an asterisk before and after the selected word or words, for example *this is bold*. Italic style works similarly, but the special character to use is an underscore, for example _italic_. It is also possible to have bold italic with the syntax _*bold italic*_.
An asterisk or an underscore alone, or in the middle of a word, does not start formatting, but punctuation characters before or after them are allowed. Both bold and italic are limited for formatting text on one line, and formatting spanning several lines must be explicitly started and stopped on every line.
|*bold* and then _italic_
|bold and then italic
|_*bold italic*_, _italic_, nothing
|bold italic, italic, nothing
|This is *bold*\n
*on multiple*\n
|This is bold
on multiple
All strings that look like URLs are automatically converted into clickable links. Additionally, URLs that end with extension .jpg, .jpeg, .png, .gif or .bmp (case-insensitive) will automatically create images. For example URLs like http://some.url are turned into links, and http:///server/image.jpg and file:///path/chart.png into images.
The automatic conversion of URLs to links is applied to all the data in logs and reports, but creating images is done only for test suite, test case and keyword documentation. Creating images works starting from Robot Framework 2.0.2.
Tables are created using the pipe character with whitespace around it as a cell boundary and the newline as a row separator. In library documentations normal newlines are enough, but in test suite, test case and keyword documentations the explicit newline character sequence (\n) is needed:
| *A* | *B* | *C* |\n | _1_ | Hello | world |\n | _2_ | Hi | |\n
The created table always has a thin border and the text is left-aligned. Formatting using bold and italic works also in table cells, so it is possible to create headers. For example the above documentation would be formatted like this:
Horizontal rulers (the <hr> tag) make it possible to separate larger sections from each others, and they can be created by having three hyphens alone in a line. With documentations in the test data literal newlines are, again, required:
Some text here.\n \n ---\n \n More text...
Robot Framework has its own time format that is used by several keywords (for example Sleep and Wait Until Keyword Succeeds) as well as test case and user keyword timeouts. This format is meant to be both flexible to use and easy to understand.
The time can always be given as a plain number, in which case it is interpreted to be seconds. Both integers and floating point numbers work, and it is possible to use either real numbers or strings containing numerical values. This format is useful, for example, when the actual time value is calculated.
Representing the time as text means using a format such as 2 minutes 42 seconds, which is normally easier to understand than just having the value as seconds. It is, for example, not so easy to understand how long a time 4200 is in seconds, but 1 hour 10 minutes is clear immediately.
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 the available specifier texts are:
1 min 30 secs 1.5 minutes 90 s 1 day 2 hours 3 minutes 4 seconds 5 milliseconds 1d 2h 3m 4s 5ms