You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python调用RobotFramework测试时传入字典参数为空的问题排查

解决Robot测试中Python传入字典为空的问题

我明白你现在的困扰——在Robot Framework测试里定义了字典,想让调用它的Python程序填充,结果跑起来字典始终是空的。咱们先理清楚问题出在哪,再一步步解决。

你的代码片段

robotstarter.py

import robot
test_dict = {'dict.a': '2', 'dict.b': '2', 'dict.c': '2', 'dict.d': '2', 'dict.e': '2', 'dict.f': '2'}
print(test_dict)
robot.run("printdictionary.robot",  # 这里你未写完run方法的完整参数

printdictionary.robot(推测你的写法)

*** Variables ***
${my_dict}    {}

*** Test Cases ***
Check Dictionary
    Log    ${my_dict}

问题根源

Python脚本里的test_dict只是当前Python文件的局部变量,Robot Framework没办法自动“感知”到它。要让变量从Python传递到Robot测试套件,必须用Robot官方提供的变量传递机制,也就是通过robot.run()的variables参数明确传入。

两种解决方案

方案1:直接传递完整字典作为单个Robot变量

修改robotstarter.py,把整个字典包装成一个变量传递:

import robot

# 把字典作为一个整体,用一个键名传递给Robot
test_dict = {'my_dict': {'a': '2', 'b': '2', 'c': '2', 'd': '2', 'e': '2', 'f': '2'}}
print(test_dict)
# 通过variables参数把变量传给Robot
robot.run("printdictionary.robot", variables=test_dict)

然后在printdictionary.robot里直接使用这个字典变量:

*** Test Cases ***
Print Full Dictionary
    Log    ${my_dict}    # 直接打印整个字典
    Log Many    ${my_dict}    # 逐行打印字典的键值对

方案2:传递单个键值对,再在Robot里组装成字典

如果你还是想保留dict.a、dict.b这种单个变量的形式,可以这样做:

修改robotstarter.py,确保run方法传入variables参数:

import robot

test_dict = {'dict.a': '2', 'dict.b': '2', 'dict.c': '2', 'dict.d': '2', 'dict.e': '2', 'dict.f': '2'}
print(test_dict)
# 把这些单个变量传给Robot
robot.run("printdictionary.robot", variables=test_dict)

然后在printdictionary.robot里把这些变量组装成字典:

*** Variables ***
${my_dict}    {}

*** Test Cases ***
Build and Print Dictionary
    # 把单个变量逐一加入字典
    Set To Dictionary    ${my_dict}    a=${dict.a}    b=${dict.b}    c=${dict.c}
    Set To Dictionary    ${my_dict}    d=${dict.d}    e=${dict.e}    f=${dict.f}
    Log    ${my_dict}    # 打印组装好的字典

验证方法

运行robotstarter.py后,查看Robot生成的日志文件(log.html),就能看到字典已经被正确填充了。

内容的提问来源于stack exchange,提问作者Heneer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:43:21