Search code examples
seleniumconditional-statementsrobotframework

How to run if if else condition based on element visibility in selenium robot framework?


I am automating a user registration form flow, where successful registration shows a success message and any validation error throws alert text. For this, I am writing an if-else flow based on the visibility or presence of an element on the page. I will pass the control to a specific keyword with that condition

${SuccessBreadcrumb} is the element which is visible when the registration is successful

Code Snippet

*** Settings ***
Library  SeleniumLibrary

*** Variables ***
${SuccessBreadcrumb} =  xpath=//a[contains(text(),'Success')]
${SuccessMsgLocator} =  xpath=//p[contains(text(), 'successfully created')]
${AlertMsg} =  xpath=//div[@class='text-danger']

*** Keywords ***
Verify Validation Message
    [Arguments]  ${UserDetails}
    sleep  2s
    run keyword if  ${SuccessBreadcrumb}  is visible  Keyword 1
#   ...  else  Keyword 2


Keyword 1
    [Arguments]  ${UserDetails}
    ${AccountCreatedText} =  get text  ${SuccessMsgLocator}
    should contain  ${AccountCreatedText}  ${UserDetails.ValidateMsg}  ignore_case=true

# Keyword 2

Error Log

Run Keyword If ${SuccessBreadcrumb}, is visible, VerifySuccessText
Documentation:  
Runs the given keyword with the given arguments, if condition is true.

Start / End / Elapsed:  20200213 12:27:52.882 / 20200213 12:27:52.882 / 00:00:00.000
12:27:52.882    FAIL    Evaluating expression 'xpath=//a[contains(text(),'Success')]' failed: SyntaxError: invalid syntax (<string>, line 1)

Solution

  • In the documentation for Run Keyword If there does not exist an example with an object. However, using a combination of Run Keyword If with Run Keyword And Return Status will allow you to create a way to handle pass and fail situations within the same test case or keyword.

    *** Settings ***
    Library    SeleniumLibrary
    
    *** Test Cases ***
    Check Element Visible
        Open Browser
        ...    url=https://www.google.com
        ...    browser=chrome
    
        ${passed}    Run Keyword And Return Status  
                     ...    Element Should Be Visible    xpath://*[@id="hplogo"]
        Run Keyword If     ${passed}       Keyword Passed
        ...    ELSE                        Keyword Failed
        [Teardown]    Close Browser
    
    Check Element Not Visible
        Open Browser
        ...    url=https://www.google.com
        ...    browser=chrome
    
        ${passed}    Run Keyword And Return Status  
                     ...    Element Should Be Visible    xpath://*[@id="xxxx"]
        Run Keyword If     ${passed}       Keyword Passed
        ...    ELSE                        Keyword Failed
        [Teardown]    Close Browser
    
    *** Keywords ***
    Keyword Passed
        Log To Console    Passed
    
    Keyword Failed
        Log To Console    Failed