Python接口测试中实现无限嵌套Response数据对比的方法

山海之间
山海之间
发布时间:2026-10-13 | 2人浏览过
原创

本文分享了一种支持无限嵌套Key的Python接口测试Response对比方法。通过结合enumerate、isinstance和format等内置函数,递归处理字典、列表及基础类型值,动态验证接口返回数据的结构完整性。该方法已部署于Jenkins,能有效处理ORM动态参数场景下的复杂数据结构校验,提升接口自动化测试的覆盖率与稳定性。

背景说明:此前的接口测试框架尚未支持对无限嵌套结构的Key进行对比。近期在testerhome论坛浏览时,参考了其他开发者分享的框架思路,发现部分逻辑并不完全契合当前需求,因此进行了本地化修改。目前该方案已部署至Jenkins并运行稳定,效果良好,特此分享。此外,通过研究他人代码,也学习到了不少Python内置常用方法的使用技巧。

接下来直接展示核心代码,并详细解析在此过程中新掌握的方法与实现思路。

def check_response_hope_key(self,response={},hope_response={}):
  temp_data={}
  for n1 in hope_response:
   print "n1:",n1
   #如果值是字典类型
   if isinstance(hope_response[n1],dict):
    print "dict"
    if not Check_Response_Hope().check_response_hope_key(response=response.get(n1), hope_response=hope_response[n1]):
     MailFile().checkfail(response=response.get(n1), hope_response=hope_response[n1])
     return False
     raise '{},{}'.format(hope_response[n1],response[n1])
   
   #如果值是列表类型
   elif isinstance(hope_response[n1],list):
    print "list"
    for hope_index,hope_listValue in enumerate(hope_response[n1]):
     #print "hope_index:",hope_index
     #print "hope_listValue:",hope_listValue
     for response_index,response_listValue in enumerate(response[n1]):
      #print "response_index:",response_index
      #print "response_listValue:",response_listValue
      if isinstance(hope_listValue,dict):
       Check_Response_Hope().check_response_hope_key(response=response[n1][response_index],
hope_response=hope_response[n1][response_index])
      elif isinstance(hope_listValue,list):
       if hope_response[n1][hope_index]==response[n1][hope_index]:
        break
       else:
        MailFile().checkfail(response=response_listValue,hope=hope_listValue)
        raise Exception ("hope_response="+str(hope_response[n1][hope_index])+"\n"+
"response="+str(response[n1][response_index]))
      else:
       if hope_response[n1][hope_index]==response[n1][hope_index]:
        break
       else:
        MailFile().checkfail(response=response[n1][hope_index],hope=hope_response[n1][hope_index])
        raise Exception ("hope_response="+str(hope_listValue)+"\n"+"response="+str(response_listValue))
   else:
    print "string"
    if response.has_key(n1):
     continue
    else:
     temp_data['error_data']='{}:{},{}:{}'.format(n1,hope_response[n1],n1,response[n1])
     #发送邮件
     MailFile().checkfail(response=response[n1],hope=hope_response[n1])
     raise Exception ("hope_response="+str(hope_response[n1])+"\n"+"response="+str(response.get(n1)))
    
  return True

首先介绍内置函数enumerate():

当传入列表数据时,该函数会返回列表中每个元素的索引及其对应的值。具体示例如下:

>>> list1=[1,2,3,4]
>>> for list_index,list_value in enumerate(list1):
...  print list_index,list_value
... 

0 1 1 2 2 3 3 4

此外,还可以指定索引的起始值进行迭代,例如:

>>> for list_index,list_value in enumerate(list1,1):
...  print list_index,list_value
... 

1 1 2 2 3 3 4 4

其次介绍内置函数isinstance(object, type):

该函数用于判断传入对象是否属于指定类型,返回布尔值True或False。示例如下:

>>> isinstance(list1,dict)
False

注:此方法非常实用且基础,可根据返回的布尔值灵活选择不同的if分支逻辑。

再次介绍内置函数format():

该函数主要用于字符串格式化。虽然并非必须使用,但使用后发现其结构清晰且便捷。以下列举几种常用用法: 1.通过位置进行映射:

>>> '{},{}'.format('abc',123)
'abc,123'
>>> '{1}{0}{1}'.format('abc',123)
'123abc123'

2.通过下标访问:

>>> list1=['a','b']
>>> '{0[1]},{0[0]}'.format(list1)
'b,a'

当然,该函数还有其他多种用法,由于篇幅限制未全部展开,感兴趣者可自行查阅相关资料,相关教程通常非常详尽。

核心思路:

接口返回的Response数据通常以字典格式存在。由于本接口测试框架通过ORM链接数据库动态传递参数,导致返回的Value值可能动态变化,但Response中的Key结构是固定的。因此,验证重点在于检查所有的Key是否存在及结构是否正确。

具体实现时,首先遍历期望返回的字典hope_response。对于hope_response中的每个元素n,其Value可能是字典、列表或字符串/整数(目前未见过Key为整数的情况)。利用isinstance()判断Value类型:若为字符串,则代表最简单层结构{key:value},此时使用has_key()检查Response中是否存在该Key;若为字典类型,则进行递归调用,直至最终落到字符串或整数类型的分支;若为列表类型,则利用enumerate()获取索引和值,再根据值的类型进行相应判断。整体思路如上,实际调试耗时一天多,看似简单,但自行编写时仍会遇到不少细节坑点。

以上就是本文的全部内容,希望对各位的学习有所帮助,也欢迎大家多多支持本站。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表