Pass arguments to Robot Framework keyword

Содержание
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

Banner image

Пример

***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

Article author: Andrei Olegovich

Похожие статьи
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
Banner image

Search this site

Subscribe to Telegram channel @aofeed to follow new articles and updates to old ones

Go to channel

@aofeed

Ask a question in the Telegram group

@aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su, info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: