Reputation: 228
Here is my Robot File (robot-dictionary-tests.robot)
*** Settings ***
Documentation Passing a dictionary object from Robot to Python and vice versa
Library Utils.py
# To run:
# robot -L debug -d Results/ Tests/robot-dictionary-tests.robot
*** Keywords ***
Call Python To Modify The Dictionary
[arguments] &{named}
modify dictionary ${named}
*** Test Cases ***
Test Modifying Robot Dictionary in Python
&{d} = Create Dictionary key=original
&{expected} = Create Dictionary key=modified
Call Python To Modify The Dictionary &{d}
Should Be Equal ${d} ${expected}
Here is my Utils.py:
from robot.api import logger
@keyword('modify dictionary')
def modify_dictionary(d):
logger.debug(f'before modification, d: {d}')
for key in d:
d[key] = 'modified'
logger.debug(f'after modification, d: {d}')
The Test Case Test Modifying Robot Dictionary in Python fails:
My Question
Why does the robot test fail even though I passed the dictionary d reference to @keyword('modify dictionary')?
Upvotes: 1
Views: 212
Reputation: 6961
As you've suspected, the variables are by reference and thus changed. To my knowledge this has more to do with Python, then Robot Framework.
Passing a dictionary as an object should be done through ${VarName} and not &{VarName}. The documenation on Dictionary Variables explains this like:
...a Python dictionary or a dictionary-like object can be used as a dictionary variable like &{EXAMPLE}. In practice this means that individual items of the dictionary are passed as named arguments to the keyword
In the below code for keyword Call Python To Modify The Dictionary
I change the keyword argument &{named}
to ${named}
and where the keyword is called &{d}
to ${d}
.
*** Keywords ***
Call Python To Modify The Dictionary
[arguments] ${named}
modify dictionary ${named}
*** Test Cases ***
Test Modifying Robot Dictionary in Python
&{d} = Create Dictionary key=original
&{expected} = Create Dictionary key=modified
Call Python To Modify The Dictionary ${d}
Should Be Equal ${d} ${expected}
Resulting in:
Suite Executor: Robot Framework 3.1.2 (Python 3.7.0 on win32)
==============================================================================
SO003
==============================================================================
SO003.Test :: Passing a dictionary object from Robot to Python and vice versa
==============================================================================
Test Modifying Robot Dictionary in Python | PASS |
------------------------------------------------------------------------------
SO003.Test :: Passing a dictionary object from Robot to Python and... | PASS |
1 critical test, 1 passed, 0 failed
1 test total, 1 passed, 0 failed
==============================================================================
SO003 | PASS |
1 critical test, 1 passed, 0 failed
1 test total, 1 passed, 0 failed
==============================================================================
Upvotes: 4