[英]How to validate data from json response (Python)?
我正在使用機器人框架創建 API 測試。 我使用請求庫,執行 GET 請求,並希望驗證響應。 但它向我顯示了一個錯誤:
AttributeError: 'dict' object 沒有屬性 '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'
簡單的解決方案正如 Pavel 所暗示的那樣
@keyword
def validate_json_response(self, response):
assert response['count'] == '82
如果您想重復使用 thi,那么您可以做的是在 paht 中找到元素並評估該元素。 在您的 python 庫中添加關鍵字,如下所示。
@keyword
def pathGet(self, dictionary , path):
for item in path:
dictionary = dictionary[item]
return dictionary
測試中的用法如下
*** Variables ***
@{DIR_COUNT} count
在測試中,您將添加此塊
${count}= pathGet ${response} ${DIR_COUNT}
Should Be Equal ${count} ${82}
這樣,您可以重用關鍵字,而不管元素路徑如何。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.