EMI RobotFrameworkAdvancedGuide
EMI RobotFrameworkAdvancedGuide
Introduction.......................................................................................................................................................1
High-level architecture.....................................................................................................................................3
Installation.........................................................................................................................................................6
Precondition...........................................................................................................................................6
Installation.............................................................................................................................................6
Where files are installed.........................................................................................................................6
Verifying installation........................................................................................................................................7
Uninstallation....................................................................................................................................................8
Variables..........................................................................................................................................................18
Introduction..........................................................................................................................................18
Variable Types.....................................................................................................................................18
Scalar Variables.............................................................................................................................18
List Variables................................................................................................................................19
Environment Variables..................................................................................................................19
Creating Variables...............................................................................................................................19
Variable Table...............................................................................................................................19
Variable File..................................................................................................................................20
Command Line..............................................................................................................................20
Return Values from Keywords......................................................................................................20
Using built-in Set Test/Suite/Global Variable keywords..............................................................21
i
Table of Contents
Variables
Built-in Variables.................................................................................................................................21
Operating System Variables..........................................................................................................21
Number Variables..........................................................................................................................21
Boolean and None Variables.........................................................................................................22
Space and Empty Variables...........................................................................................................22
Automatic Variables......................................................................................................................22
Variable Priorities and Scopes.............................................................................................................23
Variable Priorities..........................................................................................................................23
Variable Scopes.............................................................................................................................24
Advanced Variable Features................................................................................................................24
Extended variable syntax...............................................................................................................24
Variables inside variables..............................................................................................................26
Advanced Features..........................................................................................................................................34
Handling keywords with same names..................................................................................................34
Keyword scopes............................................................................................................................34
Specifying a keyword explicitly....................................................................................................34
Specifying library search order.....................................................................................................34
Timeouts..............................................................................................................................................35
Test Case Timeout.........................................................................................................................35
User Keyword Timeout.................................................................................................................36
For loops..............................................................................................................................................36
Normal for loop.............................................................................................................................36
Using several loop variables..........................................................................................................37
For in range...................................................................................................................................37
Exiting for loop.............................................................................................................................38
Repeating single keyword.............................................................................................................38
Conditional execution..........................................................................................................................39
ii
Table of Contents
Executing Test Cases
Synopsis..................................................................................................................................40
Runner Scripts.........................................................................................................................40
Specifying Test Data...............................................................................................................40
Using Command Line Options......................................................................................................41
Using Options.........................................................................................................................41
Option Values Patterns...........................................................................................................41
Test Results...................................................................................................................................41
Command Line Output...........................................................................................................41
Generated Output Files...........................................................................................................41
Return Codes...........................................................................................................................42
Help and Version Info...................................................................................................................42
Debugging Execution Problems....................................................................................................42
Test Execution.....................................................................................................................................42
Execution Flow..............................................................................................................................42
Execution Suites and Tests.....................................................................................................43
Setups and Teardowns............................................................................................................43
Execution Order......................................................................................................................43
Continue on Failure.......................................................................................................................44
Stopping Test Execution Gracefully.............................................................................................44
Handling Teardowns...............................................................................................................44
Post-processing Outputs......................................................................................................................44
Using the rebot Tool......................................................................................................................45
Creating Different Reports and Logs............................................................................................45
Combining Outputs.......................................................................................................................45
Configuring Execution.........................................................................................................................45
Selecting Test Cases......................................................................................................................45
By Test Suite and Test Case Name.........................................................................................45
By Tag Names........................................................................................................................46
When no tests match selection................................................................................................46
Setting Criticality..........................................................................................................................47
Setting Metadata............................................................................................................................47
Setting the name......................................................................................................................47
Setting the documentation......................................................................................................47
Setting free metadata..............................................................................................................47
Setting tags..............................................................................................................................47
Setting Variables...........................................................................................................................47
Randomizing Execution Order......................................................................................................48
Controlling Console Output..........................................................................................................48
Console Width........................................................................................................................48
Console Colors........................................................................................................................48
Created Outputs...................................................................................................................................48
Different Output Files...................................................................................................................48
Output Directory.....................................................................................................................49
Output File..............................................................................................................................49
Log File...................................................................................................................................49
Report File..............................................................................................................................49
Debug File...............................................................................................................................49
Setting Titles...........................................................................................................................49
Setting Background Colors.....................................................................................................50
Log Levels.....................................................................................................................................50
System Log....................................................................................................................................51
iii
Table of Contents
Extending Robot Framework \ Creating New Libraries.............................................................................52
Appendices.......................................................................................................................................................53
Test Data Settings................................................................................................................................53
Setting Table..................................................................................................................................53
Test Case Table.............................................................................................................................53
Keyword Table..............................................................................................................................53
Command Line Options.......................................................................................................................54
Test Execution Command Line Options.......................................................................................54
Output Post-processing Command Line Options..........................................................................55
Document Licence...........................................................................................................................................58
iv
Introduction
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.
Introduction 1
Why Robot Framework
• Enables easy-to-use tabular syntax for creating test cases in a uniform way.
• Provides ability to create reusable higher-level keywords from the existing keywords.
• Provides easy-to-read result reports and logs in HTML format.
• Is platform and application independent.
• Provides a simple library API for creating customized test libraries which can be implemented
natively with either Python or Java.
• Provides a command line interface and XML based output files for integration into existing build
infrastructure (continuous integration systems).
• Provides support for Selenium for web testing, Java GUI testing, running processes, Telnet, SSH, and
so on.
• Supports creating data-driven test cases.
• Has built-in support for variables, practical particularly for testing in different environments.
• Provides tagging to categorize and select test cases to be executed.
• Enables easy integration with source control: test suites are just files and directories that can be
versioned with the production code.
• Provides test-case and test-suite -level setup and teardown.
• The modular architecture supports creating tests even for applications with several diverse interfaces.
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.
High-level architecture 3
Getting more information
Project Pages Robot Framework http://code.google.com/p/robotframework/ Robot Framework SSH Library
http://code.google.com/p/robotframework-sshlibrary/ Robot Framework RIDE Editor
http://code.google.com/p/robotframework-ride/ Paramiko SSH Python Module
http://www.lag.net/paramiko/ Pycrypto Cryptography Python Toolkit
https://www.dlitz.net/software/pycrypto/ Contact Dimosthenes Fioretos dfiore -at- noc -dot- edunet -dot- gr
Installation
There are two main ways with which you can install robot framework and any relevant usefull software.The
first is by downloading and installing them by hand.The other is by installing the robot_testing repository
residing at yum.gridctb.uoa.gr and using the yum tool.Both ways,should be preceded by the installation of
python26 from the epel repository. The second and most easy way,requires the following steps:
• under /usr/lib/python2.6/site-packages/paramiko/
Pycrypto:
• under /usr/lib64/python2.6/site-packages/Crypto/
• /usr/lib64/python2.6/site-packages/pycrypto-2.3-py2.6.egg-info
Robot Framework:
• /usr/bin/jybot
• /usr/bin/pybot
• /usr/bin/rebot
• /usr/lib/python2.6/site-packages/robotframework-trunk_20110727-py2.6.egg-info
• and under /usr/lib/python2.6/site-packages/robot/
SSHLibrary:
• under /usr/lib/python2.6/site-packages/SSHLibrary/
RIDE:
• under /usr/lib/python2.6/site-packages/robotide/
• /usr/bin/ride.py
Installation 6
Verifying installation
For robot framework,execute:
pybot --version
If everything is ok,it should output the version of robot framework. For the RIDE editor,execute:
ride.py
If everything is ok,the editor environment should appear. For the ssh library,create the following file:
| *Setting* | *Value* |
| Library | SSHLibrary |
pybot test.txt
==============================================================================
Test
==============================================================================
Test1 | PASS |
------------------------------------------------------------------------------
Test | PASS |
1 critical test, 1 passed, 0 failed
1 test total, 1 passed, 0 failed
==============================================================================
Output: /home/dfiore/robot/output.xml
Log: /home/dfiore/robot/log.html
Report: /home/dfiore/robot/report.html
Verifying installation 7
Uninstallation
All the modules presented can be uninstalled by manually deleting the files the installed (the list is available
in a previous section of this document). Other than that,if the installation was done by the tools provided by
the OS,they can by uninstalled by the same means.For example:
Uninstallation 8
Creating Test Data
Structure
The hierarchical structure for arranging test cases is built as follows:
Variable table Defining variables that can be used elsewhere in the test data V
Test case table Creating test cases from available keywords T
Keyword table Creating user keywords from existing lower-level keywords K
• All tables that do not start with a recognized table name in the first cell.
• Everything else on the first row of a table apart from the first cell.
• Data outside tables in HTML and data before the first table in TXT.
• All empty rows, which means these kinds of rows can be used to make the tables more readable.
• All empty cells at the end of rows; you must add a backslash (\) to prevent such cells from being
ignored.
• All single backslashes (\); they are used as an escape character.
• All characters following a hash mark (#), if it is the first character of a cell; this means that hash
marks can be used to enter comments in the test data.
• All formatting in the HTML test data.
Escaping
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 parser is the backslash (\). The escape character can be used as follows:
Note that these escaping rules are applied only to arguments to keywords and values to settings. They are not
used, for example, with keyword and test case names.
Whitespaces
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:
Whitespaces 11
Creating Test Cases
Test Case Syntax
Basic Syntax
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. Example:
Setting Value
Library /path/to/cream/library
Test Case Action Argument Argument Argument
Submit Job Test Create Proxy dteam p4sSw0rD
${job_id}= Submit Job /path/to/jdl cream_endpoint.cern.ch:8443/queue
${final_status}= Get Final Status ${job_id}
Should Be Equal ${final_status} DONE-OK
Destroy Proxy
This test imports a library,and then uses the keywords defined within to submit a job to a cream ce and it
checks its final status.
Setting Value
Library /path/to/cream/library
Test Case Action Argument Argument Argument
Submit Job Test [Documentation] Submit a job to a cream ce
[Tags] job_submit
Create Proxy dteam p4sSw0rD
${job_id}= Submit Job /path/to/jdl cream_endpoint.cern.ch:8443/queue
${final_status}= Get Final Status ${job_id}
Should Be Equal ${final_status} DONE-OK
Destroy Proxy
Using Arguments
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
• Required: An argument must always be passed to the keyword.An example of this could be a logging
keyword.
• Have default value: The argument may or may not be given.In the first case,it has the explicit value
given.In the latter case,it has its default value.An example of this could be a keyword creating a
temporary file name.
• Variable number of arguments: The arguments provided may be from zero (in case of a default value
being used at the same time),to any number.An example of this could be a keyword which deletes
files. Important Note: The variable arguments must always be the last ones!
• Named: Arguments can be given their values,by naming them.In this way,the arguments can be given
in any order.
• Embedded: Arguments may finally be incorporated inside user level keywords,thus being able to call
a user keyword and in this way implicitely assign values to variables.
• Tags are shown in test reports, logs and, of course, in the test data, so they provide metadata to test
cases.
• Statistics about test cases (total, passed, failed are automatically collected based on tags).
• With tags, you can include or exclude test cases to be executed.
• With tags, you can specify which test cases are considered critical.
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.
Using Arguments 13
RobotFrameworkAdvancedGuide < EMI < TWiki
♦ A test case always gets these tags. Additionally, it does not get the possible tags specified
with Default Tags, so it is possible to override the Default Tags by using empty value. It is
also possible to use value NONE to override default tags.
• --settag command line option
♦ All executed test cases get tags set with this option in addition to tags they got elsewhere.
• Set Tags and Remove Tags keywords
These BuiltIn keywords can be used to modify tags during the test execution. 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. Example:
With own tags [Documentation] This test has tags not_ready, owner-mrx, req-42
[Tags] owner-mrx not_ready
No Operation
Own tags with variables [Documentation] This test has tags host-10.0.1.42, req-42
[Tags] host-${HOST}
No Operation
Set Tags and Remove Tags Keywords [Documentation] This test has tags mytag, owner-john
Set Tags mytag
Remove Tags smoke req-*
• There is a need to import the same library several times with different arguments. This is not possible
otherwise.
• The library name is inconveniently long. This can happen, for example, if a Java library has a long
package name.
• You want to use variables to import different libraries in different environments, but refer to them
with the same name.
• The library name is misleading or otherwise poor. In this case, changing the actual name is, of course,
a better solution.
Standard Libraries
Some test libraries are distributed with Robot Framework and these libraries are called standard libraries.
These are the available standard libraries:
• BuiltIn
• OperatingSystem
• Telnet
• Collections
• String
• Dialogs
• Screenshot
• Remote
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, you can contact
Robot Framework developers. In general, a library is a good candidate to be added into standard libraries if it
BuiltIn library 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). For more information, see the BuiltIn library
documentation.
OperatingSystem library 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). For more information, see the OperatingSystem
library documentation.
Telnet library 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.
Collections library 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.
String library 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.
Dialogs library 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.
Screenshot library 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.
Remote library 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.
Standard Libraries 17
Variables
Introduction
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}. 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}.
Variable Types
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.
Scalar Variables
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.It is the well known example we have allready used,which submits a job to a cream ce.
Variables 18
RobotFrameworkAdvancedGuide < EMI < TWiki
syntax like argname=${var}. Note: 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
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 @{LST} is set to the value
['/path/to/jdl','cream_endpoint.cern.ch:8443/queue'], the following two test cases are equivalent:
Environment Variables
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.
Creating Variables
Variables can spring into existence from different sources.Those include variable tables in test case files and
resource files,variable files,return values from keywords and some builtin special purpose keywords.
Variable Table
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.Example:
Scalar Variables 19
RobotFrameworkAdvancedGuide < EMI < TWiki
Variable File
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 a later section.
Command Line
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:
If both variable files and individual variables are given from the command line, the latter have higher priority.
Variable Table 20
RobotFrameworkAdvancedGuide < EMI < TWiki
@{list} = Get 3
Assuming that the keyword Get 3 returns a list [1, 2, 3], the following variables are created: ${scalar} with the
value [1, 2, 3] ${a}, ${b} and ${c} with the values 1, 2, and 3, respectively ${first} with the value 1, and
@{rest} with the value [2, 3] @{list} with the value [1, 2, 3] 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.
Built-in Variables
Robot Framework provides some built-in variables that are available automatically.
Number Variables
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. Example:
Automatic Variables
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. Available automatic variables
Number Variables 22
RobotFrameworkAdvancedGuide < EMI < TWiki
${TEST STATUS} The status of the current test case, either PASS or FAIL. Test teardown
${TEST MESSAGE} The possible error message of the current test case. Test teardown
${PREV TEST The name of the previous test case, or an empty string if no tests have Everywhere
NAME} been executed yet.
${PREV TEST The status of the previous test case: either PASS, FAIL or an empty Everywhere
STATUS} string when no tests have been executed.
${PREV TEST The possible error message of the previous test case. Everywhere
MESSAGE}
${SUITE NAME} The full name of the current test suite. Everywhere
${SUITE SOURCE} An absolute path to the suite file or directory. Everywhere
${SUITE STATUS} The status of the current test case, either PASS or FAIL. Suite
teardown
${SUITE MESSAGE} The full message of the current test suite, including statistics. Suite
teardown
${OUTPUT FILE} An absolute path to the output file. Everywhere
${LOG FILE} An absolute path to the log file or string NONE when no log file is Everywhere
created.
${REPORT FILE} An absolute path to the report file or string NONE when no report is Everywhere
created.
${DEBUG FILE} An absolute path to the debug file or string NONE when no debug file Everywhere
is created.
${OUTPUT DIR} An absolute path to the output directory. Everywhere
Variable Priorities
Variable priorities
Automatic Variables 23
RobotFrameworkAdvancedGuide < EMI < TWiki
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.
Variable Scopes
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.
Variable Priorities 24
RobotFrameworkAdvancedGuide < EMI < TWiki
${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'}
• The variable is searched using the full variable name. The extended variable syntax is evaluated only
if no matching variable is found.
• The real name of the base variable is created. The body of the name consists of all the characters after
${ until the first occurrence of a non-alphanumeric character or a space (for example, OBJECT in
${OBJECT.name} and DICTIONARY in ${DICTIONARY[2]}).
• A variable matching the body is searched. If there is no match, an exception is raised and the test case
fails.
• The expression inside the curly brackets is evaluated as a Python expression, so that the base variable
name is replaced with its value. If the evaluation fails because of an invalid syntax or that the queried
attribute does not exist, an exception is raised and the test fails.
• The whole extended variable is replaced with the value returned from the evaluation.
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. Example:
Variable Value
${JOHN HOME} /home/john
${JANE HOME} /home/jane
Test Case Action Argument
Example ${name} = Get Name
Do X ${${name} HOME}
Positional arguments
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
Return Values
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.
Example:
Positional arguments 28
Resource and Variable Files
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
How to use
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. Example:
Setting Value
Resource myresources.html
Resource ../data/resources.html
Resource ${RESOURCES}/common.tsv
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.
Setting Value
Documentation An example resource file
Library SeleniumLibrary
Resource ${RESOURCES}/common.html
Variable Value
${HOST} localhost:7272
${LOGIN_URL} http://${HOST}/
${WELCOME_URL} http://${HOST}/welcome.html
${BROWSER} Firefox
Keyword Action Argument Argument
Open Login Page [Documentation] Opens browser to login page
Open Browser ${LOGIN_URL} ${BROWSER}
Title Should Be Login Page
Variable Files
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 Python code, and technically they are Python modules.
There are two different possibilities for creating variables: Creating variables directly Variables are specified
as module attributes. In simple cases, the syntax is so simple that no real programming is needed. For
example, MY_VAR = 'my value' creates a variable ${MY_VAR} with the specified text as the value. Getting
variables from a special function Alternatively, variable files can have a special get_variables (or
getVariables) method that returns variables as either a Python dictionary or a Java Map. This method can even
take arguments, which makes this approach quite flexible.
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.
Example:
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 ${TELEPHONES}
is a python dictionary containing two pairs of values: TELEPHONES = {'jack': 4098, 'sape': 4139}
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
else:
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
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:
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)
Note that the all attribute is also, and originally, used by Python to decide which attributes to import when
using the syntax "from modulename import *".
def get_variables():
variables = { "VARIABLE ": "An example string",
"ANOTHER_VARIABLE": "This is pretty easy!",
"INTEGER": 42,
"STRINGS": ["one", "two", "kolme", "four"],
"NUMBERS": [1, 42, 3.14],
"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.
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.
Keyword scopes
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:
• Created as a user keyword in the same file where it is used. These keywords have the highest priority
and they are always used, even if there are other keywords with the same name elsewhere.
• Created in a resource file and imported either directly or indirectly from another resource file. This is
the second-highest priority.
• Created in an external test library. These keywords are used, if there are no user keywords with the
same name. However, if there is a keyword with the same name in the standard library, a warning is
displayed.
• Created in a standard library. These keywords have the lowest priority.
Advanced Features 34
RobotFrameworkAdvancedGuide < EMI < TWiki
Timeouts
Warning: 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. 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.
Timeouts 35
RobotFrameworkAdvancedGuide < EMI < TWiki
No Timeout [Documentation] Empty timeout means no timeout Test Timeout has been
even when used
[Timeout]
Some Keyword argument
For loops
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.
For in range
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. It is also possible to use simple arithmetics such as
addition and subtraction with the range limits. This is especially useful when the limits are specified with
For in range 38
RobotFrameworkAdvancedGuide < EMI < TWiki
Conditional execution
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:
• The name of the keyword used as a setup or a teardown of both test cases and test suites can be
specified using a variable. This facilitates changing them, for example, from the command line.
• The BuiltIn keyword Run Keyword takes a keyword to actually execute as an argument, and it can
thus be a variable. The value of the variable can, for example, be got dynamically from an earlier
keyword or given from the command line.
• The BuiltIn keywords Run Keyword If and Run Keyword Unless execute a named keyword only if a
certain expression is true or false, respectively. They are ideally suited to creating simple if/else
constructs. For an example, see the documentation of the former.
• Another BuiltIn keyword, Set Variable If, can be used to set variables dynamically based on a given
expression.
There are several BuiltIn keywords that allow executing a named keyword only if a test case or test suite has
failed or passed.
Runner Scripts
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. 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:
Using Options
When options are used, they must always be given between the runner script and the data sources. For
example:
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.
Test Results
Command Line Output
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.
RC Explanation
0 All critical tests passed.
1-249 Returned number of critical tests failed.
250 250 or more critical failures.
251 Help or version information printed.
252 Invalid test data or command line options.
253 Test execution stopped by user.
255 Unexpected internal error.
The return code can be set to 0 even if there are critical failures using the --NoStatusRC command line option.
This might be useful, for example, if post-processing of the results is needed before the overall status of test
execution can be determined.
Test Execution
Execution Flow
Return Codes 42
RobotFrameworkAdvancedGuide < EMI < TWiki
Execution Suites and Tests
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.
• Suite Setup
♦ 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.
• Suite Teardown
♦ 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.
• Test Setup
♦ 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.
• Test Teardown
♦ 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.
Execution Order
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:
Continue on Failure
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. One way to handle failures so that test execution is not terminated immediately
is using BuiltIn keywords Run Keyword And Ignore Error and Run Keyword And Expect Error. Using these
keywords for this purpose often adds extra complexity to test cases though.
• Pressing ctrl-c
♦ 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.
• Using Signals
♦ It is possible to terminate test execution using signals INT and TERM. These signals can be
sent from the command line using the 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.
• Using Keywords
♦ 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.
• ExitOnFailure mode
♦ 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.
Handling Teardowns
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.
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.
Post-processing Outputs
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.
Execution Order 44
RobotFrameworkAdvancedGuide < EMI < TWiki
Combining Outputs
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:
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:
Configuring Execution
Selecting Test Cases
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*
--test mysuite.mytest
--test *.suite.mytest
--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*
By Tag Names
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). 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 additio
Selecting test cases by tags is a very flexible mechanism and allows many interesting possibilities:
• A subset of tests to be executed before other tests can be tagged with smoke and executed with
--include smoke.
• Unfinished test can be committed to version control with the tag not_ready and excluded from the test
execution with --exclude not_ready.
• Tests can be tagged with iter-, where specifies the number of the current iteration, and after executing
all test cases, a separate report containing only the tests for a certain iteration can be generated (for
example, rebot --include iter-42 output.xml).
By default when no tests match the selection criteria the execution fails with an error like:
Because no outputs are generated, this behavior can be problematic if tests are executed and results processed
automatically. Luckily a command line option --RunEmptySuite can be used to force the suite to be executed
also in this case. As a result normal outputs are created but show zero executed tests. The same option can be
used also to alter the behavior when an empty directory or a test case file containing no tests is executed.
Setting Criticality
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. Criticality set when the tests are executed is not stored,thus if you want to keep the same criticality
when post-processing the outputs with rebot,you need to use --critical and/or --noncritical also with it.
Setting Metadata
Setting the name
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.
Setting tags
The command line option --settag (-G) can be used to set the given tag to all executed test cases. This option
may be used several times to set multiple tags.
Setting Variables
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 earlier parts of
this guide, but the following examples illustrate how to use these options:
--variable name:value
--variable OS:Linux --variable IP:10.0.0.42
Setting Criticality 47
RobotFrameworkAdvancedGuide < EMI < TWiki
--variablefile path/to/variables.py
--variablefile myvars.py:possible:arguments:here
• random:test
♦ Test cases inside each test suite are executed in random order.
• random:suite
♦ All test suites are executed in a random order, but test cases inside suites are run in the order
they are defined.
• random:all
♦ Both test cases and test suites are executed in a random order.
Example:
The width of the test execution output in the console can be set using the option --monitorwidth (-W). The
default width is 78 characters. The handy $COLUMNS variable can be used like: --monitorwidth
$COLUMNS.
Console Colors
The --monitorcolors (-C) option is used to control whether colors should be used in the console output. This
option has following case-insensitive values:
• auto
♦ Colors are enabled when output is written into the console but not when it is redirected into a
file. This is the default and there is rarely need to change it.
• on
♦ Colors are used also when output is redirected into a file.
• off
♦ Colors are disabled.
Created Outputs
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.
Setting Variables 48
RobotFrameworkAdvancedGuide < EMI < TWiki
Output Directory
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 File
Output files contain all the test execution results in XML format. Log and report 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 the path where the output file is created relative to the output
directory. The default name for the output file, when tests are run, is output.xml. When post-processing
outputs, new output files are not created unless --output (-o) option is explicitly used. It is possible to disable
creation of the output file also when running tests with special value NONE. In this case also other output
files, except for the debug file, are disabled.
Log File
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, reports 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 File
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.
Debug File
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, with the tail -f
command. Debug files are not created unless the command line option --debugfile (-b) is used explicitly.
Setting Titles
The default titles for logs and reports are generated by prefixing the name of the top-level test suite with Test
Log or Test Report. Custom titles can be given from the command line using the options --logtitle and
--reporttitle, respectively. Underscores in the given titles are converted to spaces automatically.Example:
Output Directory 49
RobotFrameworkAdvancedGuide < EMI < TWiki
Setting Background Colors
By default the report file has 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 #FF0000), 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.
Log Levels
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:
• FAIL
♦ Used when a keyword fails. Can be used only by Robot Framework itself.
• WARN
♦ Used to display warnings. They shown also in the console and in the Test Execution Errors
section in log files, but they do not affect the test case status.
• INFO
♦ The default level for normal messages. By default, messages below this level are not shown
in the log file.
• DEBUG
♦ Used for debugging purposes. Useful, for example, for logging what libraries are doing
internally. When a keyword fails, a traceback showing where in the code the failure occurred
is logged using this level automatically.
• TRACE
♦ More detailed debugging level. The keyword arguments and return values are automatically
logged using this level.
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. 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.
System Log
Robot Framework has its own plain-text system log where it writes information about:
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.
#!/bin/bash
export ROBOT_SYSLOG_FILE=/tmp/syslog.txt
export ROBOT_SYSLOG_LEVEL=DEBUG
System Log 51
Extending Robot Framework \ Creating New
Libraries
TODO
Name Description
Library Used for taking test libraries into use.
Resource Used for taking resource files into use.
Variables Used for taking variable files into use.
Documentation Used for specifying a test suite or resource file documentation.
Metadata 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.
Name Description
[Documentation] Used for specifying a test case documentation.
[Tags] Used for tagging test cases.
[Setup] Used for specifying a test setup.
[Teardown] Used for specifying a test teardown.
[Precondition] A synonym for [Setup].
[Postcondition] A synonym for [Teardown].
[Template] Used for specifying a template keyword.
[Timeout] Used for specifying a test case timeout.
Keyword Table
Settings in the Keyword table are specific to the user keyword for which they are defined.
Name Description
[Documentation] Used for specifying a user keyword documentation.
Appendices 53
RobotFrameworkAdvancedGuide < EMI < TWiki
Keyword Table 54
RobotFrameworkAdvancedGuide < EMI < TWiki
• --tagstatlink pattern:link:title
♦ Adds external links to the Statistics by Tag table. table in outputs.
• --removekeywords all|passed
♦ Removes keyword data from the generated outputs.
• --starttime timestamp
♦ Sets the starting time of test execution when creating reports.
• --endtime timestamp
♦ Sets the ending time of test execution when creating reports.
• --nostatusrc
♦ Sets the return code to zero regardless of failures in test cases. Error codes are returned
normally.
• -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.
-- DimosthenesFioretos - 04-Oct-2011
-- DimosthenesFioretos - 17-Oct-2011
Document Licence 58