How to pass a boolean variable to a python function from robot framework

Viewed 3462

I am new to robot framework, and inherited some .robot files which call some python functions.

Within the .robot file we have some variables defined as:

| *** Variables ***  |
| ${file}            | 2021
| ${useV2}           | False

However when the python function is called and this code runs:

log.info(f"{useV2} , type: {type(useV2)}")

the output is

False , type: <class 'str'>

So short of checking for "False" and "True" in this function, and subsequent functions where needed, how do I setup a robot framework variable as a boolean and have python derive true/false accurately?

2 Answers

Two options - either use the syntax to declare it as the actual boolean type:

${useV2}           ${False} 

(this works for declaring ints or floats too), or use the keyword Convert To Boolean, that handles the strings "True" and "False":

${useV2}=    Convert To Boolean    ${useV2}

The section in the user guide talking about this variable syntax - http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#boolean-and-none-null-variables ; the integers/floats are described in the section above it.


And here's a sample; with this RobotFramework code:

*** Variables ***
${booly}      ${True}
${stringy}    True

*** Test Cases ***
A test
    Do It       ${booly}
    Do It       ${stringy}
    ${cast to booly}=       Convert To Boolean      ${stringy}
    Do It       ${cast to booly}

, and this python function:

from robot.libraries.BuiltIn import BuiltIn

def do_it(useV2):
    BuiltIn().log_to_console(f"{useV2} , type: {type(useV2)}")

, the output in the console is:

True , type: <class 'bool'>
True , type: <class 'str'>
True , type: <class 'bool'>

E.g. the variable defined as ${True} is <class 'bool'>, the one defined as True is <class 'str'>, and the later after going through Convert To Boolean becomes bool itself.

Older RF versions always passed parameters to python land as strings. So, python code was supposed to always do a typecast to a proper type. Here's a issue about the topic: https://github.com/robotframework/robotframework/issues/2890

Newer versions when that landed do a type conversion if your python code has type annotation for the parameter (with few caveats).

So, I'd assume that your python function that is a keyword in RF, does not have type annotation ..

Related