首页 > 解决方案 > 如何从 Get Response Body - Robot 框架中获取值

问题描述

响应正文的输出

{"data":[{"id”:122,"name”:”Test 1“,”description”:”TEST 1 Test 2 …..}]},{"id”:123,"name”:”DYNAMO”……}]},{"id”:126,”name”:”T DYNAMO”……

*** Keywords ***    
Capture The Data Ids 
@{ids}=     Create List    122  123  126  167  190   
${header}    Create Dictionary    Authoriztion...   
${resp}      Get Response    httpsbin    /data    

${t_ids}=       Get Json Value    ${resp.content}    /data/0/id

问题

我在测试用例中创建了上述 id 的列表,我需要将创建的数据与响应正文中返回的 id 进行比较。t_ids 返回 122,当 0 被 1 替换时,返回 123

是否可以将它们放入 for 循环中,而不是捕获单个 id?

:FOR    ${i}  IN          ${ids}
\    ${the_id=       Get Json Value    ${resp.content}    /data/${i}/id ?

我试过这个但失败了。

将响应数据中的 id 与创建的列表进行比较的可能解决方案是什么?

谢谢你。

标签: jsonpython-2.7robotframework

解决方案


你想要什么都是可能的,但是知道你的变量包含什么样的数据结构总是好的。在下面的示例中,加载 json 文件会替换${resp.content}. 据我所知,这是一个字符串,它也是Get File返回的。

该示例分为 json 文件和机器人文件。

so_json.json

{
    "data":[
        {
            "id":122,
            "name": "Test 1",
            "description": "TEST 1 Test 2"
        },
        {
            "id": 123,
            "name": "DYNAMO"
        },
        {
            "id": 126,
            "name": "T DYNAMO"
        }
        ]
 }

so_robot.robot

*** Settings ***
Library    HttpLibrary.HTTP
Library    OperatingSystem    
Library    Collections    


*** Test Cases ***
TC
    ${json_string}  Get File    so_json.json
    ${json_object}  Parse Json    ${json_string}
    :FOR  ${item}    IN    @{json_object['data']}
    \    Log To Console    ${item['id']}

这反过来又给出了以下结果:

==============================================================================
Robot - Example                                                             
==============================================================================
Robot - Example.SO JSON                                                     
==============================================================================
TC                                                                    122
123
126
| PASS |
------------------------------------------------------------------------------
Robot - Example.SO JSON                                               | PASS |
1 critical test, 1 passed, 0 failed
1 test total, 1 passed, 0 failed
==============================================================================
Robot - Example                                                       | PASS |
1 critical test, 1 passed, 0 failed
1 test total, 1 passed, 0 failed
==============================================================================

推荐阅读