Search code examples
robotframework

How to use mathematical expressions in a keyword argument's default value in robot framework?


I'd like to define a keyword with a parameter whose default argument is computed on the fly based off of one or more global constants, but I'm struggling to find the right syntax for inserting mathematical expressions into an argument's default value assignment.

I tried this in a few different ways already, each throwing a different error.

*** Variables ***
${A_CONSTANT} =  10

*** Test Cases ***
A Test Case
    A Keyword

*** Keywords ***
A Keyword
    [Arguments]  ${optionalArgument}= ${A_CONSTANT / 10}
    Log    Optional Argument is ${optionalArgument}

This way produces the error Suspended due to logged failure: Resolving argument default values failed: Resolving variable '${A_CONSTANT / 10}' failed: TypeError: unsupported operand type(s) for /: 'str' and 'int', indicating that A_CONSTANT is read as a string instead of an integer.

If I explicitly set A_CONSTANT to an integer by changing line two to ${A_CONSTANT} = Evaluate int(10), the error message stays the same, inicating that robot framework converts it back into a string at some point.

Using the builtin Evaluate keyword inside the optionalArgument's default assignment doesn't work either since the expression to evaluate is interpreted as a second argument for A Keyword instead.

*** Variables ***
${A_CONSTANT} =  Evaluate  int(10)

*** Test Cases ***
A Test Case
    A Keyword

*** Keywords ***
A Keyword
    [Arguments]  ${optionalArgument}= Evaluate  ${A_CONSTANT / 10}
    Log    Optional Argument is ${optionalArgument}

This produces the error Suspended due to logged error: Error in file '/work/Downloads/something.robot' on line 9: Creating keyword 'A Keyword' failed: Invalid argument specification: Non-default argument after default arguments.


Solution

  • You must define the variable as a number:

    *** Variables ***
    ${A_CONSTANT}  ${10}
    

    Then the error may be gone.

    I prefer to do a more complex calculation, by defining the default as None, and then compute at the start:

    *** Keywords ***
    A Keyword
        [Arguments]  ${optionalArgument}=${NONE}
        IF    not ${optionalArgument}
            ${optionalArgument}=    Evaluate  ${A_CONSTANT}/10
        END
        Log    Optional Argument is ${optionalArgument}