简体   繁体   English

如何验证来自 json 响应(Python)的数据?

[英]How to validate data from json response (Python)?

I am creating API tests using Robot Framework.我正在使用机器人框架创建 API 测试。 I use requests library, do GET requests, and want to validate responses.我使用请求库,执行 GET 请求,并希望验证响应。 But it shows me an error:但它向我显示了一个错误:

AttributeError: 'dict' object has no attribute 'count'. AttributeError: 'dict' object 没有属性 'count'。

Are there any other ways to validate the response?还有其他方法可以验证响应吗?

library code图书馆代码

import requests

def get_method(URL):
    try:
        response = requests.get(URL,timeout=3)
        response.raise_for_status()
    except requests.exceptions.HTTPError as error1:
        raise TypeError("Http Error:", error1)
    except requests.exceptions.Timeout as error2:
        raise TimeoutError("Timeout Error:", error2)
    except requests.exceptions.ConnectionError as error3:
        raise ConnectionError("Error Connecting:", error3)
    return response 

keywords file关键字文件

from robot.api.deco import keyword
import jsonschema
import json


class keywords:
    ROBOT_LIBRARY_SCOPE = 'TESTS'
    schemaAllUsers = {
        "type": "array",
        "count": {"type": "number"},
        "results": [{
            "name": {"type": "string"},
            "height": {"type": "number"},
            "mass": {"type": "number"}
        }]
    }

    @keyword
    def get_request(self, URL):
        return restAPI_library.get_method(URL)

    @keyword
    def assert_users_response(self, response):
        assert response.status_code == 200

    @keyword
    def get_json_response(self, URL):
        return restAPI_library.get_method(URL).json()

    @keyword
    def validate_json_response(self, response):
        assert response.count == '82'

tests file *测试文件*

Library  keywords.py

*** Test Cases ***
TC - Verify GET request for all users
    ${Users}  Get Request  ${people_endpoint}
    Assert Users Response  ${Users}
    ${response}  Get Json Response  ${people_endpoint}
    VALIDATE JSON RESPONSE  ${response}

*** Variables ***
${people_endpoint}  https://swapi.dev/api/people 

在此处输入图像描述

This should demonstrate the problem and solution as well:这也应该说明问题和解决方案:

my_dict = {
    "count": 5
}

print(my_dict["count"]) # 5
print(my_dict.count) # AttributeError: 'dict' object has no attribute 'count'

Simple solution is as Pavel hinted简单的解决方案正如 Pavel 所暗示的那样

@keyword
def validate_json_response(self, response):
    assert response['count'] == '82

If you want to use thi repeatedly, than what you can do is find element in paht and evaluate that element.如果您想重复使用 thi,那么您可以做的是在 paht 中找到元素并评估该元素。 To your python library add keyword, something like this.在您的 python 库中添加关键字,如下所示。

@keyword
def pathGet(self, dictionary , path):

    for item in path:
        dictionary = dictionary[item]
    return dictionary

usage in test will be as follows测试中的用法如下

*** Variables ***
@{DIR_COUNT}    count 

in the test you will add this block在测试中,您将添加此块

${count}=    pathGet    ${response}    ${DIR_COUNT}
Should Be Equal    ${count}    ${82}

this way you can reuse the keyword, regardles of the elements path.这样,您可以重用关键字,而不管元素路径如何。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM