Robot Framework如何运行存储在列表中的关键字及其变量?
问题描述
我尝试把关键字及其参数以列表形式传递给另一个关键字执行,写了如下代码:
Keyword That Runs: [Arguments] @{keyword_to_run_with_parameters} Run Keyword @{keyword_to_run_with_parameters}
测试时创建参数列表:
@{to_analyze}= Create List Should Be Equal ${True} ${True}
执行后报错:
No keyword with name 'keyword_to_run_with_parameters = ['Should Be Equal', True, True]' found.
试过用${keyword_to_run_with_parameters}执行也失败,在StackOverflow上没找到合适的解决办法。
补充需求:做GUI自动化时,想实现一个关键字,在非Selenium关键字失败时自动截图。目前因为无法正确处理包含关键字和参数的列表,功能没法实现。虽然可以在关键字失败后手动调用截图,但想知道更优雅的实现方式,当前写的代码如下:
Capture Screenshot On Failure [Documentation] Captures screenshot on failure of a keyword, then fails the test with custom message if any is given. ... Needed because RobotFramework/Selinium only takes screenshot if a RobotFramework/Selinium command fails. ... param: keywords: @{keywords}= Create List Keyword Arguments [Arguments] ${failmessage}=Basic feedback for failiure. Picture is above. @{keywords} ${good} = Run Keyword And Return Status @{keywords} Run Keyword If not ${good} Run Keywords ... Capture Page Screenshot ... AND Fail ${failmessage}
问题原因
直接用Run Keyword传递列表变量@{keyword_to_run_with_parameters}时,Robot会把整个列表当成单个关键字名称,而不是拆分出关键字和对应参数,这就是报错的核心原因。
解决方案
要让Robot识别出列表里的「关键字+参数」结构,需要在列表变量前加星号*,也就是*@{变量名}。星号的作用是告诉Robot:把列表第一个元素作为关键字,剩下的元素作为该关键字的参数传递。
基础执行关键字修正
把原来的执行关键字改成如下写法:
Keyword That Runs [Arguments] @{keyword_to_run_with_parameters} Run Keyword *@{keyword_to_run_with_parameters}
测试时创建列表的方式不变,执行后就能正常运行Should Be Equal ${True} ${True}。
截图功能关键字修正
针对「非Selenium关键字失败自动截图」的需求,把Run Keyword And Return Status的参数也加上星号,修正后的代码:
Capture Screenshot On Failure [Documentation] 关键字失败时自动截图,随后可自定义失败消息终止测试。 ... 解决RobotFramework/Selenium仅在自身命令失败时才截图的问题。 ... 参数:@{keywords} - 要执行的关键字及参数(格式:关键字名 参数1 参数2 ...) [Arguments] ${failmessage}=执行失败,截图已保存。 @{keywords} ${good} = Run Keyword And Return Status *@{keywords} Run Keyword If not ${good} Run Keywords ... Capture Page Screenshot ... AND Fail ${failmessage}
调用示例
*** Test Cases *** 登录验证测试 Capture Screenshot On Failure 用户名验证失败 Should Be Equal ${actual_username} admin
当Should Be Equal验证失败时,会自动触发截图,然后抛出自定义的失败消息。
内容的提问来源于stack exchange,提问作者alabastor95
相关产品推荐
相关产品推荐

