Pass arguments to Robot Framework keyword

Contents
Introduction
Example
Default values
Related articles

Introduction

In Robot Framework, you can write keywords that can accept arguments when called.

If you have read the article about RFBrowser then you have already encountered such keywords.

In previous articles there were some keywords that take multiple arguments. In this article we can study this important functionality in more detail.

How to actually implement custom keywords and library keywords with multiple arguments is discussed in separate sections.

Keywords can take zero or more arguments, and some arguments can have default values.

What arguments a keyword takes depends on its implementation. For keywords from official libraries, the documentation is usually the best place to find information about a keyword. The documentation for the BuiltIn library can be found here

Official documentation

Add two numbers

Напишем RobotFramework Keyword, который будет принимать два числа и складывать их.

Проверим результат

***Settings *** Documentation Tests passing int and float as arguments ***Variables *** ***Keywords *** Add [Arguments] ${addend1} ${addend2} ${result}= Evaluate ${addend1} + ${addend2} [Return] ${result} ***Test Cases *** Test Add Integers ${sum1}= Add 1 2 Should Be Equal As Integers ${sum1} 3 Test Add Floats ${sum2}= Add 3.5 6.2 Should Be Equal As Numbers ${sum2} 9.7 Test Add Negative Integers ${sum3}= Add -2 -3 Should Be Equal As Integers ${sum3} -5

robot args_add.robot

============================================================================== Args Add :: Tests passing int and float as arguments ============================================================================== Test Add Integers | PASS | ------------------------------------------------------------------------------ Test Add Floats | PASS | ------------------------------------------------------------------------------ Test Add Negative Integers | PASS | ------------------------------------------------------------------------------ Args Add :: Tests passing int and float as arguments | PASS | 3 tests, 3 passed, 0 failed ============================================================================== Output: /home/andrei/tests/output.xml Log: /home/andrei/tests/log.html Report: /home/andrei/tests/report.html

Про использование Evaluate читайте здесь

Обратите внимание на проверку равенства. Для целых чисел я применил Should Be Equal As Integers а для чисел с плавающей точкой Should Be Equal As Numbers

Значения по умолчанию

Напишем кейворд, который будет добавлять к доменному имени протокол. По умолчанию будет http:// но можно передать свой аргумент.

***Settings *** Documentation Tests Url Creation ***Variables *** ***Keywords *** Write Url [Arguments] ${domain} ${protocol}=http:// ${result}= Catenate SEPARATOR= ${protocol} ${domain} [Return] ${result} ***Test Cases *** # Передаём https:// Test HeiHei ${heihei}= Write Url heihei.ru https:// Log To Console ${heihei} Should Be Equal ${heihei} https://heihei.ru # Ничего не передаём, рассчитываем получить # дефолтный http:// Test TopBicycle ${tb}= Write Url topbicycle.ru Log To Console ${tb} Should Be Equal ${tb} http://topbicycle.ru

robot args_def_values.robot

============================================================================== Args Def Values :: Tests Url Createion ============================================================================== Test HeiHei .https://heihei.ru Test HeiHei | PASS | ------------------------------------------------------------------------------ Test TopBicycle .http://topbicycle.ru Test TopBicycle | PASS | ------------------------------------------------------------------------------ Args Def Values :: Tests Url Createion | PASS | 2 tests, 2 passed, 0 failed ============================================================================== Output: /home/andrei/tests/output.xml Log: /home/andrei/tests/log.html Report: /home/andrei/tests/report.html

Пример

***Settings *** Documentation Example that opens single page Library Browser ... enable_playwright_debug=${True} ... auto_closing_level=TEST ... retry_assertions_for=0:00:03 ***Variables *** ***Keywords *** Open Url [Arguments] ${url} ${headless}=False New Browser browser=chromium headless=${headless} New Context viewport={'width': 1920, 'height': 1080} ignoreHTTPSErrors=True New Page ${url} ***Test Cases *** Verify Title Open Url url=https://aredel.com headless=False Get Title == AREDEL.COM Close Browser

robot args.robot

robot args.robot ============================================================================== Args :: Example that opens single page ============================================================================== Verify Title | PASS | ------------------------------------------------------------------------------ Args :: Example that opens single page | PASS | 1 test, 1 passed, 0 failed ============================================================================== Output: /home/andrei/tests/output.xml Log: /home/andrei/tests/log.html Report: /home/andrei/tests/report.html

Сперва нужно указывать аргументы без значений по умолчанию.

Если первым указать аргумент у которого есть значение по умолчанию а за ним тот, у которого нет - будет ошибка

Invalid argument specification: Non-default argument after default arguments.

***Settings *** Documentation Tests Url Creation ***Variables *** ***Keywords *** Write Url [Arguments] ${protocol}=http:// ${domain} ${result}= Catenate SEPARATOR= ${protocol} ${domain} [Return] ${result} ***Test Cases *** Test HeiHei ${heihei}= Write Url https:// heihei.ru Log To Console ${heihei} Should Be Equal ${heihei} https://heihei.ru Test TopBicycle ${tb}= Write Url topbicycle.ru Log To Console ${tb} Should Be Equal ${tb} http://topbicycle.ru

robot args_def_values_err.robot

[ ERROR ] Error in file '/home/andrei/tests/args_def_values_err.robot' on line 8: Creating keyword 'Write Url' failed: Invalid argument specification: Non-default argument after default arguments. ============================================================================== Args Def Values Err :: Tests Url Creation ============================================================================== Test HeiHei | FAIL | Invalid argument specification: Non-default argument after default arguments. ------------------------------------------------------------------------------ Test TopBicycle | FAIL | Invalid argument specification: Non-default argument after default arguments. ------------------------------------------------------------------------------ Args Def Values Err :: Tests Url Creation | FAIL | 2 tests, 0 passed, 2 failed ============================================================================== Output: /home/andrei/tests/output.xml Log: /home/andrei/tests/log.html Report: /home/andrei/tests/report.html

Related Articles
Robot Framework
Basics
RFBrowser
Set Variable
if else: conditionals
in: check if smth belongs to list
Loops
Change Variable Value
New Line
[Tags]
Collections: lists, dicts
JSON
Pass Argument to a Keyword
Evaluate
Robot in PyCharm

Search on this site

Subscribe to @aofeed channel for updates

Visit Channel

@aofeed

Feedback and Questions in Telegram

@aofeedchat