Search code examples
pythonrobotframework

RobotFramework - How to Return Value from Keyword and Stop?


I want to return a value from a keyword and exit keyword, just like you would do it in a programming language when you return values from functions. The keyword selects a random item from the list on the page, but if the page contains only 1 item then the whole thing crashes. I can't come to a solution and this is what i've done atm:

Get Random Item From Page
    # Pass the general list items xpath to the argument
    [Arguments]  ${element_path}
    ${elements}=  Get Element Count  ${element_path}
    Run Keyword If  ${elements} == 1  [Return]  ${element_path}[1]
    ${random}=  FakerLibrary.Random Int  1  ${elements}
    [Return]  ${element_path}[${random}]

The problem is that it continues to execute the keywords after the first return tag. What am i doing wrong?


Solution

  • You can use Return from keyword or Return from keyword if to return from the middle of a keyword.

    Example

    *** Keywords ***
    Is number even or odd?
        [Arguments]  ${number}
        log  number is ${number}
        Return from keyword if  int('${number}')%2 == 0  even
        Return from keyword  odd
    
    *** Test cases ***
    Test even number
        ${result}=  Is number even or odd?  4
        should be equal  ${result}  even
    
    Test odd number
        ${result}=  Is number even or odd?  5
        should be equal  ${result}  odd