【问题标题】:How to pass arguments directly from json file to keyword in robot framework?如何将参数直接从json文件传递到机器人框架中的关键字?
【发布时间】:2019-06-26 21:19:46
【问题描述】:

我有一个这样的 Json 文件。PFB 代码:

"properties " : {
    "xyz" : {
        "username" : "abc@gmail.com",
        "password" : "abc@123",
        "phonenumber" : "1235",
    },
      "ABC" : {
        "username" : "abc@gmail.com",
        "password" : "abc@123",
        "phonenumber" : "1345",
    },

关键字如下:

Do operation for properties
  [Arguments]  ${username}  ${password}  ${phonenumber}
  Log  ${username}
  Log  ${password} 
  Log  ${phonenumber}

我的问题是:

1) json 文件包含很多东西,但我只能从文件中获取属性。我将如何从整个 json 文件中获取属性部分,并将用户名、密码、电话号码等参数直接传递到上面提到的关键字中。

2)如何为此逻辑编写关键字,以便我们仅更改 json 文件以添加更多属性,例如除了 xyz、abc,我们将添加我们想要的任意数量的属性,它会自动获取和关键字为我们提供所需的结果我们在 json 文件中修改的所有属性。

【问题讨论】:

    标签: json python-2.7 robotframework


    【解决方案1】:

    如果我理解正确,您的问题总结是:a)如何以这种形式在 Robotframework 中读取和解析 json 文件,以及 b)将每条记录的属性传递给该关键字。

    可以使用Get File从文件系统中读取文件。

    可以使用 python 的 json 模块读取 json 文件,更具体地说是 loads() 方法 - 它接受一个字符串,并返回一个 python 对象。

    您的“json”示例是非常无效的 json,因此让我们假设“属性”位于文件内的某个位置(3 级深)。

    ${the file as string}=    Get File    c:\\the\\path\\to\\the\\file.json
    ${parsed}=    Evaluate    json.loads("""${the file as string}""")    json
    ${properties}=    Set Variable    ${parsed["top"]["child"]["properties"]}
    

    现在变量properties 是一个字典,有这两个键——“ABC”和“xyz”;您只需对其进行迭代,并将每个子字典的子键传递给关键字。

    FOR    ${key}    IN    @{properties}
      ${sub dict}=    Get From Dictionary    ${properties}    ${key}
      Do operation for properties    ${sub dict}[username]    ${sub dict}[password]    ${sub dict}[phonenumber]
    END
    

    【讨论】:

    • @Todor-感谢您的回复!!!它确实有帮助,但是当我运行时出现此错误:字典'$ {sub dict}'没有键'“用户名”'。为什么会出现这个错误?
    • 因为您使用的子词典不是您期望的结构。在循环中,在“从字典中获取”关键字之后,添加一个Log ${sub dict},您将看到实际的内容是什么。
    • 我运行了脚本,得到了以下日志 ${sub dict} 的输出:{u'username': u'abc@gmail.com', u'password': u'abc@123 ', u'phonenumber': u'1235'} 。看来问题是由于你而来的。删除 u' 以便检测关键“用户名”的方法是什么?
    • 不是“u”符号;看起来我在答案中犯了一个错误,在字典访问中,键不应该用引号引起来。更新了,换新版本试试。
    猜你喜欢
    • 2018-07-03
    • 1970-01-01
    • 2020-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-17
    • 2019-04-09
    • 2015-09-02
    相关资源
    最近更新 更多