任务背景是接口请求的response中包含了一个大json,需要完整地去校验整个json是否正确(将第一次接口返回的json保存下来,作为baseline,去比对)
难点: json套数组,数组里又有子json串,子json串中又有数组。
方案如下,仅供参考
def diff_print_conf__res(json_name, response):
file_location = os.path.abspath(__file__)
path = os.path.dirname(file_location)
old_res = json.load(open(path + json_name, 'r', encoding="utf-8"))
flag, diffs = checkDict(old_res, response.json)
logger.log_info('flag 为 {}。(0表示接口返回结果正常,1表示接口返回结果前后不一致)'.format(flag))
response.flag = flag
response.diff_detail = diffs
def checkDict(old_res, new_res):
diff_result = {}
for k, v in old_res.items():
if isinstance(v, dict):
flag, diffs = checkDict(v, new_res[k])
if flag == 1:
return flag, diffs
elif isinstance(v, list):
flag, diffs1 = checkList(v, new_res[k])
if flag == 1:
return flag, diffs1
elif isinstance(v, int):
return 0, ""
else:
if k in filter_field:
continue
if k in new_res:
if v == new_res[k]:
continue
else:
logger.log_info('The key:{} is not same,old value:{} ,new value:{}'.format(k, v, new_res[k]))
# diff_result = 'The key:{} is not same,old value:{} ,new value:{}'.format(k,v,new_res[k])
diff_result[k] = {"old": v, "new": new_res[k]}
# return 1,diff_result
return 0, ""
else:
diff_result[k] = {"msg": "接口返回key不存在:%s" % (k)}
return 1, diff_result
# new_res['diff_result'] = diff_result
return 0, ""
def checkList(old_res, new_res):
print(type(old_res))
for i in range(len(old_res)):
if isinstance(old_res[i], dict):
flag, diffs = checkDict(old_res[i], new_res[i])
if flag == 1:
return flag, diffs
elif isinstance(old_res[i], list):
flag, diffs1 = checkList(old_res[i], new_res[i])
if flag == 1:
return flag, diffs1
else:
if old_res[i] == new_res[i]:
continue
else:
flag, diffs1 = checkList(old_res[i], new_res[i])
if flag == 1:
logger.log_info(
'The key: {} is not same ,the number differ is {},old value:{},new value:{}'.format(old_res, i,
old_res[i],
new_res[i]))
return 0, ""
return 0, ""