如何使用 python 在运行时验证两个 JSON API 响应键值对匹配?

How to Validate two JSON API Response key-value pair matches on runtime using python?

我正在尝试验证相同键值的两个 API JSON 响应键值对,如果 JSON 响应不匹配则抛出错误。

例如:1. www.oldurl.com 给出=>

   { "firstName":"alex", "age":31, "dob":"10-12-1988" }

2. www.newurl.com gives =>

   { "firstName":"**alx**", "**ag**":31, "dob":"10-12-1988" }

此处 oldurl 和 newurl 给出相同的 JSON 响应,但在 newurl 中我们看到键和值错误。

现在,我需要捕获此错误并向用户显示 newurl.com 中的键 firstname 和 age 不匹配。

Python代码:

import unittest
import requests, json,settings
from requests.auth import HTTPBasicAuth
from jsonschema import validate
class TestOne(unittest.TestCase):
    def setUp(self):

    def test_oldurl(self):
    resp=requests.get('www.oldurl.com',auth=HTTPBasicAuth(settings.USER_NAME,settings.PASSWORD))
    data = resp.text
    print (data)  #Prints json 

    def test_newurl(self):
    resp=requests.get('www.newurl.com',auth=HTTPBasicAuth(settings.USER_NAME,settings.PASSWORD))
    data = resp.text
    print (data)  #Prints json 

现在我收到了两个 JSON 响应,我该如何验证这两个响应。 是否有任何 python 库可以验证并显示键和值中的任何错误。

注意:两个 JSON 响应应该相同我这样做是为了验证的一部分,以避免将来响应中出现任何错误。

我还单独使用模式进行一个 JSON 响应密钥验证。 使用:

    def setUp(self):
    with open('Blueprint_schema.json', 'r') as f:
        self.schema = f.read()
        self.file = f
     validate(json.loads(data), json.loads(self.schema))
     self.assertNotEqual(data,'[]')

但这仅对一个 JSON 响应键有帮助。因此,我需要在执行时比较两个 API 的 JSON 响应,或者将其存储在两个文件中并打开并验证。我认为这些文件验证但它会更多编码所以考虑通过在运行时本身验证来减少代码长度。

请提出您的想法。

# newurl_resp should also give back same key:value pairs as oldurl was giving

#load JSON Data into Dictionary 
import json
f = open("response_oldurl.json")
oldurl_resp= json.load(f)
f.close()
#type(oldurl_resp) --> <class dict>

oldurl_resp = { "firstName":"alex", "age":31, "dob":"10-12-1988" }
newurl_resp = { "firstName":"**alx**", "**ag**":31, "dob":"10-12-1988"}

方法 1 即时报告错误

def validate_resp(old_resp,new_resp):
    for old_k,old_v in oldurl_resp.items():

        try:
            if old_k in new_resp:
                new_val = new_resp[old_k]
            else:
                raise KeyError('newurl_response doesn\'t have key: '+old_k)

            try:
                if old_v != new_val:
                    raise ValueError('new value = '+str(new_val)+' doesn\'t match with orignal value = '+str(old_v)+' of key: '+str(old_k))

                    #raise ValueError('new value = {} doesn\'t match with orignal value = {} of key: {}'.format(new_val,old_v,old_k))

            except ValueError as v_err:
                print(v_err.args)

        except KeyError as k_err:
            print(k_err.args)


validate_resp(oldurl_resp,newurl_resp)

#("new value = **alx** doesn't match with orignal value = alex of key: firstName",)
#("newurl_response doesn't have key: age",)

方法 2 保存它们以备后用

items_with_value_err = []
missing_keys = []

def validate_resp(old_resp,new_resp):
    for old_k,old_v in oldurl_resp.items():
        if old_k in new_resp:
            if new_resp[old_k] != old_v:
                # key is same but new_resp contains different value
                items_with_value_err.append((old_k,old_v,new_resp[old_k]))
        else:
            missing_keys.append(old_k)

    if len(items_with_value_err) == 0 and len(missing_keys) == 0:
        return True
    else:
        return False

print(validate_resp(oldurl_resp, newurl_resp)) #prints False