Search code examples
pythonseleniumautomated-testsrobotframework

Run Keyword If key exists in dictionary (Robot Framework)


I am currently using Robot Framework to automate tests for a form. To feed the form data I am using dictionaries like these:

*** Variables ***
&{TestCase1}    key1=a    key2=b    key3=c    key4=d
&{TestCase2}    key2=x    key3=y

What I am trying to do is condition the filling of certain fields on if the matching key exists in the dictionary for that test case, so that optional fields can be left blank. I tried running the the following keyword:

*** Keywords ***
Fill Form
    [Arguments]    &{TestCase}
    Run Keyword If    &{TestCase}[key1]    Input Text    id=field1    &{TestCase}[key1]
    Run Keyword If    &{TestCase}[key2]    Input Text    id=field2    &{TestCase}[key2]
    Run Keyword If    &{TestCase}[key3]    Input Text    id=field3    &{TestCase}[key3]
    Run Keyword If    &{TestCase}[key4]    Input Text    id=field4    &{TestCase}[key4]

...but to no avail. I'm getting this error:

FAIL: Dictionary &{TestCase} has no key 'key1'.

...which makes sense to some extent, because it doesn't, but that was the point. I expected this to make the condition evaluate to False and make RF skip the keyword.

Can anyone explain why it doesn't work that way and if there is another way to make this happen? Any help is greatly appreciated!


Solution

  • You need to check for the existence of the key, not the value. In python this would look like if 'key1' in TestCase, so in robot syntax it would look like this:

    Run keyword if  'key1' in $TestCase  Input Text  ...
    

    Here is a complete example. When run, it should add "key1 is in the log as expected" but not "bogus is unexpectedly in the log"

    *** Variables ***
    &{TestCase1}    key1=a    key2=b    key3=c    key4=d
    &{TestCase2}    key2=x    key3=y
    
    *** Test Cases ***
    Example
        Run keyword if  'key1' in $TestCase1  log  key1 is in the log as expected
        Run keyword if  'bogus' in $TestCase1  log  bogus is unexpectedly in the log