Search code examples
robotframework

Robot not overriding variable passed in from command line


I have the following test:

*** Test Cases ***

My Test
    ${MY_VAR}     Set Variable    %{MY_VAR=mydefault}

If I export MY_VAR before running the test it picks that up.

If I don't have the env var set it uses the value mydefault.

So far so good, but I was expected to also explicitly override via the command line.

When I pass --variable MY_VAR=fromcmd it does not use that value.

Does %{} not support overriding with --variable?

Edit

Per answer to this question it looks like environment variable interpolation ignores cli injected variables.

If that's the case then it seems to me like the most readable way to handle this is in a variables.py with regular Python code like this (I think it's preferable to handling it with the robot syntax in the test case itself):

if not BuiltIn().get_variable_value("${MY_VAR}"):
    MY_VAR = os.environ.get("MY_VAR", "default value")

It would be awesome though if there was some way to override this behavior. Does robot provide a way to hook into its %{} function and modify it with custom behavior?


Solution

  • It's true the variable setting in the command line has the highest priority, but this is not what happens here - in this line you are effectively re-setting the value.

    You passed some value from the CLI, but when the execution got to that line, it actually did "the variable MY_VAR will now be set to the value of the env variable MY_VAR, or if there isn't such - to mydefault".
    E.g. you're effectively overriding the value from the CLI args, present or not.


    You can solve for this by first checking is the var already defined (from CLI, or some place else), and fall back to env and default only if not. The Get Variable Value returns by default None (the py type) if a variable is not defined, so using that:

    ${MY_VAR}=    Get Variable Value    ${MY_VAR}
    IF    $MY_VAR is None      # not set yet? 
        ${MY_VAR}=   Set Variable    %{MY_VAR=mydefault} 
    END