3.3 User Keyword Definition & Arguments
User Keywords in Robot Framework allow users to create their own
keywords by combining existing keywords into reusable higher-level actions.
They help improve readability, maintainability, and modularity in
automation by abstracting complex sequences into named actions.
User Keywords are defined syntactically very similarly to tests|tasks
and are defined in the *** Keywords ***
section of a suite file or resource file.
3.3.1 *** Keywords ***
Section
The *** Keywords ***
section of suite and resource files
is indentation-based similar to the *** Test Cases ***
section.
The user keywords defined are unindented, while their body implementation is indented by multiple spaces.
See these sections for more details about 2.2 Basic Suite File Syntax and 2.6 Writing Test|Task and Calling Keywords.
This section can be part of suites or resource files. While keywords defined in suites can solely be used in the suite they are defined in, keywords defined in resource files can be used in any suite that imports these resource files.
Example definition of a user keyword:
*** Keywords ***
Verify Valid Login
[Arguments] ${exp_full_name}
${version}= Get Server Version
Should Not Be Empty ${version}
${name}= Get User Name
Should Be Equal ${name} ${exp_full_name}
As a reference for how defined keywords are documented, see 2.5 Keyword Interface and Documentation.
3.3.2 User Keyword Names
Recall the rules how keyword names are matched.
The names of User Keywords should be descriptive and clear, reflecting the purpose of the keyword. Well-named keywords make tests more readable and easier to understand. Robot Framework supports Unicode and allows the use of special characters and even Emojis in keyword names.
Keyword names are case-insensitive and can include spaces.
Also spaces and underscores will be ignored when matching keyword names.
So the keywords Login To System
, and log_into_system
are considered identical.
To identify keywords that shall be executed, Robot Framework uses a matching algorithm that is case-insensitive and ignores spaces and underscores.
- If then a full match is found, that keyword is used.
- If no full match is found, the prefixes
Given
,When
,Then
,And
, andBut
(case-insensitive), which are used in Behavior-Driven Specification style, are removed from the called keyword name to find a match. - If still no match is found, Robot Framework tries to match the name with keywords that have embedded arguments.
By default, if not explicitly defined by the library developers, all Library Keywords are named in Title Case with capital letters at the beginning of each word, and spaces between words.
Project may choose a different naming convention for User Keywords, but it is recommended to be consistent across the project for User Keyword names.
They are defined without indentation, and the subsequent lines until the next unindented line are considered the body of the keyword. The following topics explain how to structure the body of a keyword.
3.3.3 User Keyword Settings
Recall all available settings and their purpose for User Keywords
User keywords can have similar settings as test cases, and they have the same square bracket syntax separating them from keyword calls. All available settings are listed below and explained in this section or in sections linked below.
[Documentation]
Used for setting user keyword documentation. (see 3.3.4 User Keyword Documentation)[Arguments]
Specifies user keyword arguments to hand over values to the keyword. (see 3.3.5 User Keyword Arguments)[Setup]
,[Teardown]
Specify user keyword setup and teardown. (see 4.2 Teardowns (Suite, Test|Task, Keyword))[Tags]
(*) Sets tags for the keyword, which can be used for filtering in documentation and attribution for post-processing results.[Timeout]
(*) Sets the possible user keyword timeout.[Return]
(*) Deprecated.
(*) The application of these settings are not part of this syllabus.
3.3.4 User Keyword Documentation
Recall the significance of the first logical line and in keyword documentation for the log file.
Each keyword can have a [Documentation]
setting to provide a description of the keyword's purpose and usage.
The first logical line, until the first empty row, is used as the short documentation of the keyword in the log.html
test protocol.
Proper documentation helps maintain clarity, especially in larger projects. It is a good practice to document what the keyword does, any important notes regarding its usage, and additional information about the arguments it accepts if not self-explanatory.
User keywords can be documented in the Robot Framework documentation format.
The syntax of this format has similarities to Markdown, but is more limited and not compatible with Markdown!
This format includes:
*bold*
= bold_italic_
= italic_*bold italic*_
= bold italic`code`
=code
- Tables
- Lists
- Links
- Images
- Heading levels
3.3.5 User Keyword Arguments
Understand the purpose and syntax of the [Arguments] setting in User Keywords.
User Keywords can accept arguments, which make them more dynamic and reusable in various contexts.
The [Arguments]
setting is used to define the arguments a user keyword expects.
See also Chapter 2 2.5.2 Keyword Arguments for an introduction to argument kinds.
Arguments are defined by [Arguments]
followed by the argument names separated by multiple spaces in the syntax of scalar variables.
Unlike Library Keywords, User Keywords cannot define argument types like string
, number
, etc., as described in the 2.5.2.8 Argument Types section.
3.3.5.1 Defining Mandatory Arguments
Recall what makes an argument mandatory in a user keyword.
Define User Keywords with mandatory arguments.
Arguments defined as scalar variable (${arg}
) without a default value are mandatory and must be provided when calling the keyword.
Example that defines a keyword with two arguments:
*** Keywords ***
Verify File Contains
[Documentation] Verifies that a file contains a specific text.
...
... The keyword opens the file specified by the file path and checks if it contains the expected content.
[Arguments] ${file_path} ${expected_content}
${server_log} = Get File ${file_path}
Should Contain ${server_log} ${expected_content}
All variables defined in the [Arguments]
are local to the keyword body and do not exist outside of the keyword.
This keyword may be called in a test case like this:
*** Test Cases ***
Check Server Log
Verify File Contains server.log Successfully started
In that case, the argument ${file_path}
is assigned the value server.log
, and ${expected_content}
is assigned the value Successfully started
.
3.3.5.2 Defining Optional Arguments
Recall how to define optional arguments in a user keyword.
Define User Keywords with optional arguments.
Optional arguments are defined by assigning default values to them in the [Arguments]
setting.
All optional arguments must be defined after all mandatory arguments.
Default values are assigned using an equal sign (=
),
followed by the default value without any spaces, such as ${ignore_case}=True
,
which would set the string True
as default.
The assigned default values can also include previously defined variables,
such as ${ignore_case}=${True}
, where ${True}
represents the boolean value True
.
Example:
*** Keywords ***
Verify File Contains
[Documentation] Verifies that a file contains a specific text.
...
... The keyword opens the file specified by the ``file_path``
... and checks if it contains the ``expected_content``.
...
... By default, the verification is case-insensitive
... but can be changed with the optional argument ``ignore_case``.
[Arguments] ${file_path} ${expected_content} ${encoding}=utf-8 ${ignore_case}=${True}
${server_log} = Get File ${file_path} ${encoding}
Should Contain ${server_log} ${expected_content} ignore_case=${ignore_case}
3.3.5.3 Defining Embedded Arguments
Describe how embedded arguments are replaced by actual values during keyword execution.
Understand the role of embedded arguments in Behavior-Driven Development (BDD) style.
In Robot Framework, embedded arguments allow the inclusion of arguments directly within the keyword name itself. This approach is particularly useful for creating Behavior-Driven Development (BDD)-style test cases or for making keyword names more readable and meaningful.
With embedded arguments, placeholders are used within the keyword name, which are replaced by actual values when the keyword is executed. These arguments are written as scalar variables with dollar signs and curly braces, as shown in the following example:
*** Keywords ***
The file '${file_name}' should contain '${expected_content}'
${file_content} = Get File ${file_name}
Should Contain ${file_content} ${expected_content}
When this keyword is called, the placeholders ${file_name}
and ${expected_content}
are replaced by the actual values provided in the keyword call.
For instance, in the following example,
${file_name}
is replaced with server.log
and ${expected_content}
with Successfully started
:
*** Test Cases ***
Test File Content
Given the server log level is 'INFO'
When the server is started successfully
Then the file 'server.log' should contain 'Successfully started'
Quotes around the embedded arguments are treated as regular characters within the keyword name but can improve readability and help distinguish embedded arguments from the rest of the keyword name.
Embedded arguments can become problematic when the keyword name becomes overly long or complicated. To address this, a mix of embedded arguments and regular arguments can be used. This approach can help manage more complex data structures and enhance readability.
Example of mixed embedded and regular arguments:
*** Test Cases ***
Embedded and normal arguments
Given the user is on the pet selection page
When the user adds 2 cat fish
And the user sets 3 dogs
And the user removes 1 dogs
Then the number of cat fish should be 2
And the number of dogs should be count=2
*** Keywords ***
the number of ${animals} should be
[Arguments] ${count}
${current_count} Get Animal Count ${animals}
Should Be Equal As Numbers ${current_count} ${count}
the user ${action}
[Arguments] ${amount} ${animal}
IF '${action}' == 'adds'
Add Items To List animal_list ${animal} ${amount}
ELSE IF '${action}' == 'removes'
Remove Items From List animal_list ${animal} ${amount}
ELSE IF '${action}' == 'sets'
Set Amount To List animal_list ${animal} ${amount}
ELSE
Skip Test skipped due to invalid action
END
3.3.5.4 Other Argument Kinds
Other argument kinds like Named-Only Arguments, Free Named Arguments, or Variable Number of Positional Arguments should be known, but their definition and usage are not part of this syllabus.
3.3.6 RETURN Statement
Understand how the RETURN
statement passes data between different keywords.
Use the RETURN
statement to return values from a user keyword and assign it to a variable.
The RETURN
statement (case-sensitive) in Robot Framework is used to return values from a User Keyword
to be used in further test steps or stored in variables.
This allows test execution to pass data between different keywords.
It can return one or more values. If more than one value is returned, they can either be assigned to multiple variables or stored as a list in a single variable.
Example:
*** Keywords ***
Get File Name From Path
[Arguments] ${file_path}
${path} ${file} = Split Path ${file_path}
RETURN ${file}
The RETURN
statement is normally used at the end of a keyword definition,
because it will end the keyword execution at that point and return to the caller.
However, this behavior can be used to conditionally end a keyword execution early together with an IF
or TRY-EXCEPT
statement.
The RETURN
statement cannot return a value from a keyword call directly like in other programming languages.
The return value must be stored in a variable first and then be returned by the RETURN
statement.
3.3.7 Keyword Conventions
Recall the naming conventions for user keywords.
When defining User Keywords, it is recommended to follow conventions to ensure consistency and readability across the project. These may be taken from community best practices or defined within the project team.
Keyword Conventions should contain agreements on:
- Naming Case: Which case shall be used? (i.e.
Title Case
,camelCase
,snake_case
,kebab-case
, orsentence case
, etc. ) (from a readability perspective,Title Case
orSentence case
are recommended) - Grammatical Form/Mood: Which form shall be used for actions and verifications/assertions? (i.e.
Imperative
for both likeClick Button
,Verify Text
. Or i.e.Declarative
/Indicative
for assertions likeText Should Be
,Element Should Be Visible
) - Word/Character Count: How man words or characters shall be used in a keyword name? (i.e. less than 7 words)
- Argument Count: How many arguments shall a keyword have? (i.e. less than 5)
- Documentation: How shall the documentation be structured and which information shall be included or is it required at all?