Jenkins:
robot -i tp2 -i t2 -v ExecutionType:headless -d .//JenkinsLogs//Logs_%JOB_NAME%-%BUILD_NUMBER% -s suiteName TestSuite/ModuleFolderName
Run Locally
@echo off
FOR /f %%a IN ('WMIC OS GET LocalDateTime ^| FIND "."') DO SET DTS=%%a
SET DateTime=%DTS:~0,4%-%DTS:~4,2%-%DTS:~6,2%_%DTS:~8,2%-%DTS:~10,2%-%DTS:~12,2%
cd ..
call robot -d ./Report/%DateTime%_ServiceReq -v ExecutionType:headless -s VesselCall_ServiceRequest Testsuite/pcs_marsa/VesselCall
Get Dropdown list values
@{poclist}= Get List Items ${PassTypeComboBox} values=False
['--Select--', ' Pass1 ', ' Pass2 ', ' Pass3 ']
Read Dictionary in .dot notation
&{dict}= read_values_from_cell_with_scenario ${testDataExcelPath} ${worksheet} ${scenario}
Input Text ${TradeLicenseNoTextBox} ${dict.TradeLicenseNo}
set root=C:\Project\Project-rootfolder
pushd %root%
robot --variable ExecutionType:headless -t "testcase_name" -d .//report_temp1 -s margo_fr -o output.xml .
pause
robot --variable ExecutionType:headless -d .//JenkinsLogs//Logs_%JOB_NAME%-%BUILD_NUMBER% -s TS_Vessel_Registration TestSuite/PCS_MARSA
@RD /S /Q "%WORKSPACE%@tmp"
Increment
${date} Get Current Date time_zone=local increment=0 days result_format=%d-%b-%Y exclude_millis=False
Get Day and month from Date
Strip date Zero
${monthlistdate}= convert date ${eventTime} result_format=%m
${monthlistdate}= Strip String ${monthlistdate} mode=left characters=0
${select_month}= convert date ${eventTime} result_format=%B
${select_day}= convert date ${eventTime} result_format=%d
${select_day}= Strip String ${select_day} mode=left characters=0
# ${select_date}= catenate ${select_month} ${select_day}
${select_hour}= convert date ${eventTime} result_format=%H
${select_minute}= convert date ${eventTime} result_format=%M
Contains
Run Keyword If 'pradeep' in 'pradeepkumar' Log To Console True
... ELSE Log To Console False
Run Keyword And Continue On Failure Should Be Equal As Strings ${ExpectedResults}[loadingOps] ${ActualResults}[loadingOps] ignore_case=True
white space ${space}
Log To Console Daily Pass${space}a stream=STDOUT no_newline=False
Explicit locator strategy
Strategy | Match based on | Example |
---|---|---|
id | Element id . | id:example |
name | name attribute. | name:example |
identifier | Either id or name . | identifier:example |
class | Element class . | class:example |
tag | Tag name. | tag:div |
xpath | XPath expression. | xpath://div[@id="example"] |
css | CSS selector. | css:div#example |
dom | DOM expression. | dom:document.images[5] |
link | Exact text a link has. | link:The example |
partial link | Partial link text. | partial link:he ex |
sizzle | Sizzle selector deprecated. | sizzle:div.example |
jquery | jQuery expression. | jquery:div.example |
default | Keyword specific default behavior. | default:example |
Run keyword if string contians substring
Run Keyword If 'pradeep1' in 'pradeepkumar' Log To Console True
... ELSE Log To Console False
Press Keys None RIGHT Arrow
FOR ${index} IN RANGE 1 ${count}+1
Press Keys None RIGHT
Sleep 1 reason=None
END
Creating objects in robot framwork
https://stackoverflow.com/questions/47765335/in-robot-framework-how-do-you-to-create-object-of-class-and-call-the-methods-in
Faker Library
https://seleniummaster.com/sitecontent/index.php/selenium-robot-framework-menu/selenium-robot-framework-python-menu/270-generate-test-data-in-robot-framework-example-one
https://guykisel.github.io/robotframework-faker/
https://guykisel.github.io/robotframework-faker/#Address
pip install robotframework-faker
*** Settings ***
Library FakerLibrary
***Test Cases***
testcase1
${address}= Address
Log To Console ${address}
dry run / dryrun
robot --dryrun -v ExecutionType:headless -d ./Report -s ts_billing_manual Testsuite/pcs_marsa/billing
declaring variables
*** Variables ***
${PdfTestFilePath} ${EXECDIR}/VariableFiles/OTHERS/upload.pdf
${BROWSER_CHROME} Chrome
Replace Variables template file
https://robotframework.org/robotframework/latest/libraries/BuiltIn.html#Replace%20Variables
${tesT} set variable pradeep
${template} = Get File C:/test/fileName.xml
${message} = Replace Variables ${template}
Log To Console ${message} stream=STDOUT no_newline=False
iframes
Select Frame msg_body
*** Settings ***
Library DateTime
Library String
Library XML
Library OperatingSystem
*** Variables ***
${XmlFile} Unified_Registartion.xml
*** Test Cases ***
test1
${root}= Parse XML ${XmlFile} strip_namespaces=True
#Parse Xml source keep_clark_notation=False strip_namespaces=False
${text}= Get Element Text ${root} Profiles//ProfileStatus
parse XML
${xml}= Parse XML ${EXECDIR}/VariableFiles/XML/${xmlfile}
${book} = Get Element Text ${xml} Bookstore/book
Library String
Random Number:
${random2}= Generate Random String length=7 chars=[NUMBERS]
importing Python library:
Library ${EXECDIR}/Library/ExcelReadAndWrite/libReadWrite.py
"""
Writing value into xlsx of a specified column name of given scenario name.
"""
def write_value_into_cell_By_Scenario(file_path, worksheet, column_name, scenario, enter_value):
with closing(load_workbook(filename=file_path)) as wb:
enter_value = str(enter_value)
ws = wb[worksheet]
no_of_columns = ws.max_column
no_of_rows = ws.max_row
column_no = 0
scenario_row_no=0
# Loop will print all columns name in the first row
for i in range(1, no_of_columns + 1):
cell_obj = ws.cell(row=1, column=i)
# print(cell_obj.value)
if(column_name == cell_obj.value):
column_no = i
print("column no:", i)
break
######## Identifying the scenario row no
for j in range(2, no_of_rows + 1):
cell_obj = ws.cell(row=j, column=1)
print(cell_obj.value)
if(cell_obj.value==scenario):
print("found")
scenario_row_no=j
break
################## raise exception if scenario not found
if(scenario_row_no==0):
raise Exception('scenario not found in the worksheet....!')
else:
pass
ws.cell(row=scenario_row_no, column=column_no, value=enter_value)
wb.save(file_path)
Get time :
${sys_date_time}= get time
Types in Robot Framework:
https://stackoverflow.com/questions/54534602/how-to-check-datatype-of-variable-in-robot-framework
https://stackoverflow.com/questions/42617970/get-type-in-robot-framework
${XYZ} Set Variable True
${XYZ1}= Convert To Boolean ${XYZ}
${type string}= Evaluate type($XYZ)
Log To Console ${type string}
Comment Issue Date 10 days before & Expiry 10 days after current date
${IssueDate}= Get Current Date time_zone=local increment=240:00:00 result_format=%d/%m/%Y exclude_millis=True
${ExpiryDate}= Get Current Date time_zone=local increment=240:00:00 result_format=%d/%m/%Y exclude_millis=True
Program to open url in Robot Framework
*** Settings ***
Library SeleniumLibrary
Library OperatingSystem
**Test Cases***
test
Log To Console hi stream=STDOUT no_newline=False
Open Browser https://google.com browser=ie alias=None remote_url=False desired_capabilities=None ff_profile_dir=None
*** Settings ***
Library SeleniumLibrary
Library OperatingSystem
Library String
Library Dialogs
Library Collections
Library Process
Library DateTime
Library DatabaseLibrary
Library FtpLibrary
Library RequestsLibrary
Library keyboard
# Library pcs_robot_v2
Library json
Library requests
Library DependencyLibrary
Upload file in robot framework:
https://stackoverflow.com/questions/44583374/upload-a-file-in-browser-using-robot-framework-test
click_locator_and_attach
[Arguments] ${locator} ${filepath}
BuiltIn.sleep 3.0
Press Keys ${locator} ${filepath}
Choose File ${locator} ${filepath}
BuiltIn.sleep 3.0
# press_esc_keyboard_key
keyboard.press_and_release ${KEYBOARD_KEY_ESC}
Capture Page Screenshot
log To Console hi stream=STDOUT no_newline=False
Overlay:
${present}= Run Keyword And Return Status wait until Element Is Visible //div[@class="ngx-overlay foreground-closing"] timeout=30 error=None
log To Console OverlayPresentRefresh=${present} stream=STDOUT no_newline=False
Run Keyword If '${ETB}' == '${EMPTY}'
... No_Operation
... ELSE
... Run Keywords Wait_And_Input_Text //input[@id="dtETB"] ${ETB}
... AND Press Keys None ESC
strip()
wait until Element Is Visible //h2[@class="service-title"][contains(text(),"${service_name.strip()}")]
Response time:
Open_Page_Url url=${MARGO_STAGING} alias=${alias} browser=${BROWSER_CHROME}
${date_start}= Get Current Date
Maximize Browser Window
VPN_Login_Verify
Wait For Condition return window.document.readyState === "complete"
#### Wait Until Element Is Visible ${MARGO_FREIGHT} timeout=45
${date_end}= Get Current Date
Capture Page Screenshot
${time}= Subtract Date From Date ${date_end} ${date_start}
Run Keyword And Continue On Failure Run Keyword If ${time}>3.0 Page_load_time_error
Delete Breakpoints in Visual Studio Code, VSCode
Create a bat file with the WorkSpaceStorage location of the visual studio
RD /S /Q "C:\Users\pradeep.rajappa\AppData\Roaming\Code\User\workspaceStorage"
--dryrun
set root=C:\Project\ProjectFolder
pushd %root%
robot --dryrun -t "TestCase_Name" -d .//report_temp3 -s testsuiteName -o output.xml .
pause
https://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#dry-run
compare date time in between
GetCurrentWorkingHoursType
[Arguments] ${WorkingHoursStartTime} ${WorkingHoursEndTime}
${currentDateTime}= Get Current Date time_zone=local increment=0 result_format=%d-%b-%Y %H:%M exclude_millis=True
${currentDate}= Get Current Date time_zone=local increment=0 result_format=%d-%b-%Y exclude_millis=False
${StartTime}= convert date ${currentDate} ${WorkingHoursStartTime} date_format=%d-%b-%Y %H:%M result_format=%d-%b-%Y %H:%M exclude_millis=True
${EndTime}= convert date ${currentDate} ${WorkingHoursEndTime} date_format=%d-%b-%Y %H:%M result_format=%d-%b-%Y %H:%M exclude_millis=True
${WorkingHoursType}= Run Keyword If '${currentDateTime}' > '${StartTime}' and '${currentDateTime}' < '${EndTime}'
... Set Variable Regular
... ELSE
... Set Variable Overtime
[Return] ${WorkingHoursType}
Assign value from html read
${PortValue}= Run Keyword If '${voyagePort}'=='${EMPTY}'
... Get Element Attribute //label[contains(text(),"${Port}")]/following-sibling::div/p innerText
... ELSE IF '${voyagePort}'=='PORT'
... Get Selected List Label //label[contains(text(),"${Port}")]/parent::div/select
GetTimeDuration
[Arguments] ${eventNameTimeDict} ${StartTimeEventName} ${EndTimeEventName}
${duration}= Subtract Date From Date ${eventNameTimeDict["${EndTimeEventName}"]} ${eventNameTimeDict["${StartTimeEventName}"]}
... exclude_millis=True date1_format=%d-%b-%Y %H:%M date2_format=%d-%b-%Y %H:%M
${duration} Convert To Integer ${duration} base=None
${duration} = Convert Time ${duration} timer exclude_millis=yes
${duration}= convert date ${duration} date_format=%H:%M:%S result_format=%H:%M
${duration} Catenate ${duration} hours
[Return] ${duration}
Convert Seconds to hours minutes , time format
Library DateTime
${time} = Convert Time 661 timer exclude_millis=yes
Log To Console ${time} stream=STDOUT no_newline=False
${eventTime}= convert date ${time} date_format=%H:%M:%S result_format=%H:%M
Log To Console ${eventTime} stream=STDOUT no_newline=False
00:11
seconds to HH:MM convertor
time to date format convertor
https://stackoverflow.com/questions/60491006/convert-seconds-to-hoursminutes-using-convert-date-and-robotframework
${time} evaluate f"{${seconds//3600}:02d}:{${seconds%3600}:02d}"
Loop dictionary
https://stackoverflow.com/questions/42228908/for-loop-over-dictionary-in-robot-framework
https://seleniummaster.com/sitecontent/index.php/selenium-robot-framework-menu/selenium-robot-framework-python-menu/259-manipulate-dictionary-in-robot-framework
${MyDictionary}= Create Dictionary
Set To Dictionary ${MyDictionary} Foo1 Value1
${MyDictionary2}= Copy Dictionary ${MyDictionary}
${Keys}= Get Dictionary Keys ${MyDictionary}
${keyValue}= Get From Dictionary ${MyDictionary} Foo2
Log Dictionary ${MyDictionary}
Remove From Dictionary ${MyDictionary} Foo1
Comment Keeps the given keys in the dictionary and removes all other.
Keep In Dictionary ${MyDictionary} Foo4
${unsorted} = Get Dictionary Values ${D3} sort_keys=False
dictionary Usage:
${Dict}[Working Hours]
conditional equals
Run Keyword If '${UserType}' == 'SA' Log To Console True stream=STDOUT no_newline=False
and condition
Run Keyword If '${billingRecordExists}' != 'True' and '${billingRecordExists}' != 'True'
... Log to console True
... ELSE
... Log to console False
if dictionary contains key then run the keyword
Run keyword if 'key1' in ${dictonaryValues} Log To Console
Date format only changes to the format , result format will print in the required format. we can use the same timstamp for both dateformat and result format
${eventDateTime} = Convert Date ${eventDateTime}
result_format=%d-%b-%Y %H:%M date_format=%d-%b-%Y %H:%M exclude_millis=True
${IncrementTime}= Run Keyword If '${IncrementTime}' == '${empty}'
Set Variable 2 minutes
Set Variable 2 minutes
... ELSE Set Variable ${IncrementTime}
Sending two / multiple dictionary as parameters
&{a}= Create Dictionary
... gla=2
&{b}= Create Dictionary
... bla=67
DictTest ${a} ${b}
DictTest
[Arguments] ${a} ${b}
Log To Console ${a.gla} stream=STDOUT no_newline=False
Log To Console ${b.bla} stream=STDOUT no_newline=False
adding minutes in for loop for date time
FOR ${eventName} IN @{eventsList}
${eventDateTime} = Add Time To Date ${eventDateTime} 5 minutes
Log To Console ${eventDateTime} stream=STDOUT no_newline=False
# VoyageEventsFillData ${ServiceRequestMarsa} ${eventName} ${MovementType}
# ... ${ResourceName} ${event_time}
# Set To Dictionary ${eventName} ${minutes}
END
Convert Date
${date} = Convert Date 6-Jul-2020 10:12 date_format=%d-%b-%Y %H:%M
Unary Operator
Increment or decrement operator
https://stackoverflow.com/questions/35056327/decrement-or-increment-a-variable-in-the-robot-framework
${N_groups-1}
${N_groups}= ${N_groups-1}
@{Hero}= Create List a b c
${N_groups} Set Variable 10
FOR ${value} IN @{Hero}
${N_groups}= Evaluate ${N_groups} + 1
Log To Console ${N_groups} stream=STDOUT no_newline=False
END
run keyword if list is non empty list
test
@{SpecialConditionsList}= create list 9
SA_Sent_VesselCall_Approve @{SpecialConditionsList}
SA_Sent_VesselCall_Approve
[Arguments] ${SpecialConditionsList}=@{EMPTY}
${count}= Get Length ${SpecialConditionsList}
Run keyword if ${count} > 0 log to console Greater than zero
return list , and set list
@{list}= Run Keyword If '${type}' == 'public' Set Variable @{PublicHolidaysList}
... ELSE IF '${type}' == 'iftar' Set Variable @{IftarList}
... ELSE IF '${type}' == 'weekend' Set Variable @{WeekendDaysList}
... ELSE IF '${type}' == 'regular' Set Variable @{regularDaysList}
[Return] @{list}
Return Multiple values
https://stackoverflow.com/questions/38440154/return-two-values-in-robot-framework
${regulardays} ${weekenddays} GetDaysList
GetDaysList
[Return] ${regularDaysList} ${WeekendDaysList}
Get weekday, sunday , monday , tuesday
https://stackoverflow.com/questions/52254674/robotframework-get-current-date/52255317
${DATE_MESSAGE} get current date result_format=%A
For Loop Recursion Method:
Recursion: Function calling itself.
FOR ${rowIndex} IN RANGE 1 ${TotalRowsCount}+1
${row}= Set Variable (//table)[2]/tbody/tr[${rowIndex}]
${rowDate}= Get Element Attribute ${row}/td[2] innerText
${MonthContains}= Run Keyword And Return Status Should Contain ${rowDate} ${Month}
Log To Console ${rowIndex}:${${MonthContains}} stream=STDOUT no_newline=False
Run Keyword If ${MonthContains}
... Run Keywords
... Execute JavaScript document.evaluate('${row}', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.scrollIntoView()
... AND Wait_And_Click_Element ${row}/td[5]/a[@ngbtooltip="Delete"]
... AND Wait_And_Click_Element //button[text()="Yes"]
... AND Wait_For_Page_Load
... AND DeleteHolidaysRows ${Month}
END
The
Run Keywords
does not allow assignmentshttps://stackoverflow.com/questions/53781034/assign-a-variable-within-the-keyword-run-keywords-possible
Class Object Oriented Concept in Python and Robot Framework
https://stackoverflow.com/questions/42340299/how-can-i-access-the-object-variable-in-robot-framework
https://stackoverflow.com/questions/42340299/how-can-i-access-the-object-variable-in-robot-framework
FileName: class_test.py
class jpg(object):
def __init__(self, *args, **kwargs):
self.TAG = 'Pradeep'
self.args = args
self.PARAMS = {}
def test_jpg(*args, **kwargs):
return jpg(*args, **kwargs)
*** Settings ***
Library class_test.py
*** Test Cases ***
python class test
[Tags] class
#[Documentation] python class test
${ret}= test_jpg class_tag
Log To Console ${ret.TAG} stream=STDOUT no_newline=False
Log To Console ${ret.args} stream=STDOUT no_newline=False
Python Class Object used in Robot Framework
Advanced variable features
https://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.htmlSearch : "2.6.6 Advanced variable features"
lass MyObject:
def __init__(self, name):
self.name = name
def eat(self, what):
return '%s eats %s' % (self.name, what)
def __str__(self):
return self.name
OBJECT = MyObject('Robot')
DICTIONARY = {1: 'one', 2: 'two', 3: 'three'}
*** Test Cases ***
Example
KW 1 ${OBJECT.name}
KW 2 ${OBJECT.eat('Cucumber')}
KW 3 ${DICTIONARY[2]}
Run Keyword If key exists in dictionary (Robot Framework)
https://stackoverflow.com/questions/59775094/run-keyword-if-key-exists-in-dictionary-robot-framework
*** Test Cases ***Example&{TestCase1}= Create Dictionary key1=a key2=b key3=c key4=d&{TestCase2}= Create Dictionary key2=x key3=yRun keyword if 'key5' in $TestCase1 Log To Console Message
Run keyword if 'key3' in ${TestCase2} Log To Console Message
Run keyword if 'Tariff' in ${ExpectedDict}
... Run Keyword And Continue On Failure
... Should Be Equal As Strings
... ${ExpectedDict.Tariff} ${ActualDict.Tariff}
[Arguments] ${resourceType}=${EMPTY} ${Equipment}=${EMPTY}
${RowLocator} //table
${resourceTypeLocator}= Run Keyword If '${resourceType}' != "${empty}" Set Variable ${RowLocator}/../td[2][contains(.,'Mooring gang supervisor')] ELSE Set Variable ${RowLocator}
${EquipmentLocator}= Run Keyword If '${Equipment}' != "${empty}" Catenate ${resourceTypeLocator}/../td[3][contains(.,'TUGBOat1')] ELSE Set Variable ${resourceTypeLocator}
Robot Framework does not have while loop
https://stackoverflow.com/questions/36328595/how-to-write-a-loop-while-in-robot-framework
is not empty
${new_datetime}= Run Keyword If '${add_time}'is not'${EMPTY}' and '${subtract_time}'=='${EMPTY}'
... Add time To Date ${todays_datetime} ${add_time}
... ELSE IF '${add_time}'=='${EMPTY}' and '${subtract_time}'is not'${EMPTY}'
... Subtract Time From Date ${todays_datetime} ${subtract_time}
... ELSE
... Fail Wrong parameters
if else condition
Run Keyword If '${count}' == '0'
... log to console 0
... ELSE
... Run Keywords keyword1 keyword2 argument1 argument2
or condition
https://stackoverflow.com/questions/23863264/how-to-write-multiple-conditions-of-if-statement-in-robot-framework
Run Keyword If '${color}' == 'Red' or '${color}' == 'Blue' or '${color}' == 'Pink'
... No Operation
... ELSE
... abcd
Run Keyword If '${PreviousMonthDay}' == 'Friday' or '${PreviousMonthDay}' == 'Saturday' or '${dayNumberPreviousMonth}' == '05'
... No Operation
... ELSE
... Append To List ${regularDaysList} ${PreviousMonthDate}
Wait_For_Page_Load
Wait For Condition return document.readyState === "complete"
Sleep 3 reason=None
dic
${Count1} Get Element Count ${xpath}
def click_locator_and_attach_by_sendkeys(locator, pathname):
se3lib = BuiltIn().get_library_instance('SeleniumLibrary')
print(pathname)
se3lib.driver.find_element_by_xpath(locator).send_keys(pathname)
attach document
click_locator_and_attach
[Arguments] ${locator} ${filepath}
BuiltIn.sleep 3.0
Press Keys ${locator} ${filepath}
Choose File ${locator} ${filepath}
BuiltIn.sleep 3.0
# press_esc_keyboard_key
keyboard.press_and_release ${KEYBOARD_KEY_ESC}
Capture Page Screenshot
Dictonary arguments
&{SerReqDataDict}= Create Dictionary
... Place=mysore
... name=${RequestedStartTime}
not equal to
${SearchAllRows} Set Variable ${empty}
Run Keyword If "${SearchAllRows}" != "${empty}" Log To Console 1
... ELSE Log To Console 2
Run Keyword And Return Status
\ ${present}= Run Keyword And Return Status Element Should Be Visible ${y}
\ Run Keyword If ${present} Run Keywords Click Element ${y} AND Exit For Loop
set text if condition
abcdmethod
[Arguments] ${status}
${abcd}= Run Keyword If '${status}' == 'APPROVED' Set Variable Approved
... ELSE IF '${status}' == 'PENDING' Set Variable Pending
[Return] ${abcd}
Variable Dictionary
&{VoyageDetailsDict}= Create Dictionary file=abc
${ab} = Set Variable file
#${xyx}= ${VoyageDetailsDict[""${ab}""]}
Log To Console ${VoyageDetailsDict["${ab}"]} stream=STDOUT no_newline=False
List count
@{bookingtype}= create list a b
${count}= Get Length ${bookingtype}
Log To Console ${count} stream=STDOUT no_newline=False
:For ${i} IN RANGE 6
\ ${statusTitle}= SeleniumLibrary.Get Element Attribute ${status_loc} title
\ Exit For Loop IF "${statusTitle}" == "${status}"
Wait Until Element Is Visible ${locator} timeout=45
named argument or default argument
https://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html
One Argument With Default Value [Arguments] ${arg}=default value
Writing keyword in multi line multiline
https://stackoverflow.com/questions/16551786/is-it-possible-to-have-a-variable-span-multiple-lines-in-robot-framework
&{dict}= Create Dictionary FreshWaterSamplingValue=Yes
... AnyOnboardillnessValue=No
... LastCertificateIssuingPort=No
Wait Retry
https://stackoverflow.com/questions/53545785/too-many-arguments-to-wait-for-condition-in-robot-framework
Wait Until Keyword Succeeds 2 min 5 sec Element Should Be Visible ${CompletedTasksPane}
Passing List as an Argument:
***Test Cases***
ABCDDDDDDDDD
@{list}= Create List one two
Keyword1 @{list} type=mt address=jj pin=ase
***Keywords***
Keyword1
[Arguments] @{name} ${type} ${address} ${pin}
Log To Console ${EventName} stream=STDOUT no_newline=False
Create list and return
@{list}= Create List
Append To List ${list} ${value}
[return] ${list}
javascript Click
JS_Click
[Documentation] Clicks element when XPATH is given using JavaScript
[Arguments] ${element_xpath}
${element_xpath}= Replace String ${element_xpath} \" \\\"
Execute JavaScript document.evaluate("${element_xpath}", document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0).click();
scrollIntoView
Scroll to view
document.evaluate('//*[@id="getQuote"]/div[3]/div[1]/div', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.scrollIntoView()
in Yaml use single quotes twice to bypass single quote
TimeTextBox: '//label[contains(text(), ''start'')]/following-sibling::div//input'
Add 10 min time to Current Date and time
https://robotframework.org/robotframework/latest/libraries/DateTime.html#Add%20Time%20To%20Time
${date}= Get Current Date time_zone=local increment=00:10:00 result_format=%d/%m/%Y %H:%M exclude_millis=True
output:
20/06/2020 18:17
${date}= Get Current Date time_zone=local increment=00:10:00 result_format=%d-%b-%Y %H:%M exclude_millis=True
or
ca
${currentDAte} Get Current Date
Log To Console ${currentDAte} stream=STDOUT no_newline=False
${date} = Add Time To Date ${currentDAte} 10 min
Log To Console ${date} stream=STDOUT no_newline=False
Set date through Xpath:
document.evaluate("//*[@id='actual-end']/div/input", document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0).value = "23-Jun-2020 22:55"
Date input from javascript
Execute Javascript document.getElementById("fromDateInput").value = "${fromDate}"
Javascript Click
JS_Click
[Documentation] Clicks element when XPATH is given using JavaScript
[Arguments] ${element_xpath}
${element_xpath}= Replace String ${element_xpath} \" \\\"
Execute JavaScript document.evaluate("${element_xpath}", document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0).click();
Create Object Oriented Class python class file.
https://stackoverflow.com/questions/47765335/in-robot-framework-how-do-you-to-create-object-of-class-and-call-the-methods-in
Dictionary in Method Arguments
methodName ${argument1} ${argument2} qty=2 starttime=10/03/2020 10_25 place=Bangalore
methodName
[Arguments] ${argument1} ${argument2} &{dictonaryValues}
Date in Format
Library String
${pcsDate}= Set Variable 6/6/2020 22:00
@{splittedDate} = Split String ${pcsDate} ${empty} #${empty} means space
${onlyDate} = Convert Date ${splittedDate}[0] date_format=%d/%m/%Y
${datePart} = Convert Date ${onlyDate} result_format=%d-%b-%y
${finalDate} Catenate ${datePart} ${splittedDate}[1]
Log To Console ${finalDate} stream=STDOUT no_newline=False
Log To Console ${finalDate} stream=STDOUT no_newline=False
output: 06-Jun-20 22:00
${date}= Get Current Date time_zone=local increment=0 result_format=%d-%b-%Y %H:%M exclude_millis=True
16-Jun-2020 18:12
Split string
Library String
${pcsDate}= Set Variable 6/6/2020 22:00
@{splittedDate} = Split String ${pcsDate} ${empty}
@{poclist} = Split String ${calllist.purposeOfcall} ,
append to list
@{list} Create List
Append To List ${list} ${text}
For each
@{list} = Create List mango apple
#MultiSelectDropdown @{portList}
FOR ${ELEMENT} IN @{list}
Log To Console ${ELEMENT} stream=STDOUT no_newline=False
END
MultiSelectDropdown
[Arguments] @{list}
Log To Console ${list} stream=STDOUT no_newline=False
or Condition
https://stackoverflow.com/questions/23863264/how-to-write-multiple-conditions-of-if-statement-in-robot-framework
Run Keyword If '${color}' == 'Red' or '${color}' == 'Blue' or '${color}' == 'Pink' log to console \nexecuted with multiple or
Indexing Problem
is string, not list or dictionary, and thus accessing item
${locator} = Replace String ${locator}$[${row}] $ ${EMPTY} count=1
Read dictionary values
&{data1}= Create Dictionary
Set To Dictionary ${data1} Key Data Value 16
Log To Console ${data1["Key Data Value"]} stream=STDOUT no_newline=False
${value}= Execute JavaScript return document.evaluate('//h5[contains(text(),"abc")]/following-sibling::h4', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.innerHTML
Javascript innerHTML by xpath\
document.evaluate('//h5[contains(text(),"Shipment Ref. No.")]/following-sibling::h4', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.innerHTML
Execute Javascript document.evaluate('${fast}', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.scrollIntoView()
Dictionary Index
Access dictionary first item by index
&{Data}= Create Dictionary
Set To Dictionary ${Data} Name 1
Set To Dictionary ${Data} Number 2
Log To Console @{Data}[0] stream=STDOUT no_newline=False
${Expected}= Set Variable 49999
${Charges}= Set Variable 1
${Charges}= Run Keyword If ${Charges} <= 1000 Set Variable 12
... ELSE IF ${Expected} <= 5000 Set Variable 22
... ELSE IF ${Expected} <= 50000 Set Variable 52
... ELSE IF ${Expected} > 50000 Set Variable 72
Log To Console ${Charges} stream=STDOUT no_newline=False
Add days , Add hours and Add minutes in the same method with the time format
${incrementDays} set Variable 1
${incrementHours} set Variable 1
${incrementMinutes} set Variable 1
${date2}= Get Current Date time_zone=local increment=${incrementHours}:${incrementMinutes}:00
${date3} = Add Time To Date ${date2} ${incrementDays} days result_format=%d/%m/%Y %H:%M exclude_millis=True
Log To Console ${date3} stream=STDOUT no_newline=False
21/06/2020 20:08
add hours
add mins
add time
subtract hours
subtract
${date}= ${newDate} time_zone=local increment=00:10:00 result_format=%d/%m/%Y %H:%M exclude_millis=True
Days minus
subtract days
add days
${ssab}= Get Current Date result_format=datetime
${date} = Add Time To Date ${ssab} -7 days result_format=%d/%m/%Y %H:%M exclude_millis=True
13/06/2020 18:26
${date}= Get Current Date result_format=datetime
${ssab}= Convert To String ${date}
${date} = Add Time To Date ${ssab} -7 days
Log To Console ${date} stream=STDOUT no_newline=False
List Comparision:
https://stackoverflow.com/questions/45512858/robot-framework-collections-list-comparison-issue
Lists Should Be Equal ${List_Of_States_USA} ${List_Of_States_USA-Temp}
${L1} Create List @{List_Of_States_USA}
${L2} Create List @{List_Of_States_USA-Temp}
Lists Should Be Equal ${L1} ${L2}
${value1}= Set Variable Last
${tag}= Run Keyword If '${value1}' == 'Current' Set Variable /following-sibling::div
... ELSE IF '${value1}' == 'Last' Set Variable /following-sibling::div[2]
Log To Console ${tag}
${value1}= Set Variable Current
${tag}= Run Keyword If '${Flag}' == 'Current' Set Variable /following-sibling::div
... ELSE Set Variable /following-sibling::div[2]
${up}= Evaluate math.ceil(${c}) math
@{words} = Split String 4.1234 AED
Log To Console @{words}[0] stream=STDOUT no_newline=False
@{feesValue} = Split String ${fees}
[Return] @{feesValue}[0]
return list
testing
${data}= keyword1
Log To Console ${data.name} stream=STDOUT no_newline=False
Log To Console ${data.name} stream=STDOUT no_newline=False
***Keywords***
keyword1
&{Data}= Create Dictionary
Set To Dictionary ${Data} ShipmentName cloth
Set To Dictionary ${Data} BlNumber pen
[Return] &{Data}
if else set variable
https://stackoverflow.com/questions/28229676/if-else-if-in-robot-framework
tent
${txt} Set Variable
${foo}= Set variable True
${total}= Set variable 100
${txt}= Run Keyword If True Evaluate ${total} / 2
... ELSE Evaluate ${total} / 4
Log To Console ${txt}
Log To Console ${txt}
Return Dictionary : inner Text
Keyword3
[Arguments] ${data1}
&{dict}= Keyword4
Dictionary Should Contain Item ${dict} ${keyName} ${valueName} msg=None
For loop
Append to dictionary
Keyword4
&{dictn}= Create Dictionary
FOR ${i} IN RANGE 1 10+1
${key1}= Get Element Attribute xpath innerText
${value1}= Get Element Attribute xpath innerText
Set To Dictionary ${dictn} ${key1} ${value1}
END
[return] &{dictn}
Return the value from one method to other:
Keyword1
${data}= Keyword2
Keyword2
[Return] ${data}
if else if
Run Keyword If "${id}"=="1" Method1
... ELSE IF "${id}"=="2" Method2
... ELSE IF "${id}"=="3" Method3
Tabs: send keys
https://robotframework.org/SeleniumLibrary/SeleniumLibrary.html#Press%20Keys
Press Keys None CTRL+ARROW_RIGHT
Press Keys None ENTER
https://medium.com/@joonasvenlinen/ui-regression-testing-with-robot-framework-part-1-578f2f50b721
and condition
Run Keyword If '${Status1}'==first and '${Status2}'==second Wait_And_Click_Element ${elementXPath}
... ELSE
... FAIL Failure Message
Robot Framework Debugger
https://marketplace.visualstudio.com/items?itemName=JacobPhilip.danfoss-robotframework-debug
D:\test\.vscode\launch.json
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "robot",
"request": "launch",
"name": "Robotframework Debugger",
"program": "${workspaceFolder}/${relativeFile}",
"stopOnEntry": true,
"arguments": "",
"libraries": ["${workspaceFolder}\\Libraries"],
"variables": [
{
"Name": "RobotVariable",
"Value": "data"
}
],
"PythonPath": "python"
}
]
}
else if
https://stackoverflow.com/questions/28229676/if-else-if-in-robot-framework
1) Intellisense / Auto completion in RobotFramework
Install : Robot Framework Intellisense by Tomi Turtiainen
https://marketplace.visualstudio.com/items?itemName=TomiTurtiainen.rf-intellisense
File --> Preferences --> Settings --> Workspace --> Robot Framework Language Server Configuration --> Rf Language Server: Libraries
Edit in Settings.json
"rfLanguageServer.libraries": [
"BuiltIn-3.0.4",
"DateTime-3.0.4",
"SeleniumLibrary-3.2.0"
]
https://github.com/tomi/vscode-rf-language-server/tree/master/client#supported-standard-libraries
https://dzone.com/articles/robot-framework-the-ultimate-guide-to-running-your
https://www.tutorialspoint.com/robot_framework/index.htm
https://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html
https://www.slideshare.net/EllaSun2/robotframework-newlogo
https://pypi.org/project/robotframework-pageobjectlibrary/
https://pypi.org/project/robotframework-pageobjectlibrary/
https://github.com/boakley/robotframework-pageobjectlibrary/wiki/Tutorial
https://www.tutorialspoint.com/What-is-PYTHONPATH-environment-variable-in-Python
https://stackoverflow.com/questions/56461983/how-to-exit-from-for-loop-in-robot-framework
foreach loop
for each loop
FOR ${value} IN @{Hero}
Do your stuff
Exit For Loop IF "${value}" == "${Batman}"
Do your stuff
END
https://stackoverflow.com/questions/23863264/
how-to-write-multiple-conditions-of-if-statement-in-robot-framework
No comments:
Post a Comment