如何将json数据文件加载到robot框架中的变量中



我正试图将json数据文件直接加载到Robot Framework中的变量中。有人能用一个例子详细说明一下如何做吗?提前感谢:(

一种方法是使用OperatingSystem库中的Get-File关键字,然后使用内置的Evaluate关键字将其转换为python对象。

例如,考虑一个名为example.json的文件,其中包含以下内容:

{
    "firstname": "Inigo",
    "lastname": "Montoya"
}

你可以用这样的东西来记录这个名字:

*** Settings ***
| Library | OperatingSystem
*** Test Cases ***
| Example of how to load JSON
| | # read the raw data
| | ${json}= | Get file | example.json
| | 
| | # convert the data to a python object
| | ${object}= | Evaluate | json.loads('''${json}''') | json
| | 
| | # log the data
| | log | Hello, my name is ${object["firstname"]} ${object["lastname"]} | WARN

当然,您也可以用python编写自己的库来创建一个做同样事情的关键字。

有一个库可用于此:HttpLibrary.HTTP

${json}= | Get file | example.json
${port}  | HttpLibrary.HTTP.Get Json Value | ${json} | /port
log      | ${port}

API文件可在此处获取:http://peritus.github.io/robotframework-httplibrary/HttpLibrary.html

一个常见的用法是将json数据传递到另一个库,如Http库请求。你可以做:

*** Settings ***
Library        OperatingSystem
Library        RequestsLibrary
*** Test Cases ****
Create User
         #...
   ${file_data}= 
    ...  Get Binary File    ${RESOURCES}${/}normal_user.json
         Post Request       example_session    /user    data=${file_data} 
         #...

没有直接涉及python,也没有中间json对象。

Thanks Vinay .. that helped now we can retrieve data from json file in robot framework as well
*** Settings ***
Library           HttpLibrary.HTTP
Library           OperatingSystem
*** Test Cases ***
Login_to_SalesForce_Json
    ${jsonfile}    Get File    c:/pathtojason/Data/testsuite.json
    ${username}    Get Json Value    ${jsonfile}    /test_case1/username
    log    ${username}
Below is the json file structure
{
    "test_case1": 
        {
            "username":"User1",
            "password":"Pass1"
        }
    ,
    "test_case2":
        {
            "username1":"User2",
            "password1":"Pass2"
        }

}

前提条件是:pip-install-可信主机pypi.python.org robotframework httplibrary

我遇到了类似的问题,这对我来说很好:
${json}获取二进制文件${json_path}nameOfJsonFile.json

它适用于我的API测试,读取.json和POST,如这里的

*** Settings ***
Library    Collections
Library    ExtendedRequestsLibrary 
Library    OperatingSystem
*** Variables ***  
${uri}    https://blabla.com/service/
${json_path}    C:/home/user/project/src/json/
*** Test Cases ***
Name of Robot Test Case  
    Create Session    alias    ${uri}    
    &{headers}  Create Dictionary  Content-Type=application/json; charset=utf-8
    ${json}  Get Binary File  ${json_path}nameOfJsonFile.json
    ${resp}    Post Request    alias    data=${shiftB}    headers=${headers}
    Should Be Equal As Strings    ${resp.status_code}    200

也有一些情况下,您需要将读取的二进制文件(在我的例子中是${json}(转换为字典,但首先尝试这个简单的解决方案。

最新更新