python - 如何验证来自 json 响应(Python)的数据?
问题描述
我正在使用机器人框架创建 API 测试。我使用请求库,执行 GET 请求,并希望验证响应。但它向我显示了一个错误:
AttributeError:“dict”对象没有属性“count”。
还有其他方法可以验证响应吗?
图书馆代码
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
关键字文件
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'
测试文件*
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
解决方案
这也应该说明问题和解决方案:
my_dict = {
"count": 5
}
print(my_dict["count"]) # 5
print(my_dict.count) # AttributeError: 'dict' object has no attribute 'count'
推荐阅读
- python - 检查字符串的特定字符是数字还是字母(python)
- c - 一般保护/核心转储“边界”
- swift - 如何在快速在 textFieldDidBeginEditing 委托上呈现另一个视图控制器时隐藏键盘?
- android-studio - Gradle 同步失败:com.android.tools.idea.gradle.project.sync.idea.issues.SdkPlatformNotFoundException:模块:找不到“app”平台“android-29”
- python - 用于匹配各种形式的字符串的正则表达式
- flutter - 如何开始 WhatsApp 对话?[扑]
- r - 着色 DT 列
- asp.net-core - 使用多个参数调用 Web API
- xamarin - 无法在 xamarin 表单中保持标签栏可访问时导航页面
- java - 哪些 KeyStore 实现可用于存储对称密钥?