zoukankan      html  css  js  c++  java
  • python+unittest+xlrd+request搭建API测试框架

    实现功能

    1.可在表格中进行编写用例

    2.自动执行表格中测试用例

    3.对响应结果进行深度断言,可定位预期结果与测试结果的不同值与位置

    4.形成HTML格式的测试报告

    源码可在githube中下载 https://github.com/wcnszbd/Mytest

    先附上效果图:

     
    再上代码:
    结构图
     
     
     1 #!/usr/bin/env python
     2 # -*- coding: utf-8 -*-
     3 # @Time    : 2017-07-28 18:07
     4 import xlrd
     5 import requests
     6 class APiTool:
     7 
     8     # 调取表格中用例方法
     9     def xlsee(self, xlsFile):
    10         sheetlist = []  # 用来保存表格所有数据
    11         rqapi = xlrd.open_workbook(xlsFile)   # 获得文件对象
    12         sheet_name = rqapi.sheet_names()[0]  # 获取第一个sheet名称
    13         sheet = rqapi.sheet_by_name(sheet_name)  # 获取第一个sheet对象
    14         nrow = sheet.nrows   # 获取行总数
    15         for i in range(1,nrow):
    16             sheetlist.append(sheet.row_values(i))
    17         return sheetlist
    18 
    19     # 请求方法
    20     def request(self, rqtype, rqurl, paramete, headers):
    21         if rqtype == "get":
    22             apiresult = requests.get(url=rqurl, params=paramete, headers=headers)  # 发送请求
    23             return apiresult
    24         if rqtype == "post":
    25             apiresult = requests.post(url=rqurl, data=paramete, headers=headers)
    26             return apiresult
    27         else:
    28             print("请求参数错误,请求类型只支持get+post,请求地址支持string,参数支持dict")
    29 
    30 
    31     # 对返回的json值进行深度断言
    32 
    33     def compare_json_data(self,A, B, L = [], xpath = '.'):
    34         if isinstance(A, list) and isinstance(B, list):
    35             for i in range(len(A)):
    36                 try:
    37                     self.compare_json_data(A[i], B[i], L, xpath + '[%s]' % str(i))
    38                 except:
    39                     L.append('▇▇▇ A中的key %s[%s]未在B中找到
    ' % (xpath, i))
    40         if isinstance(A, dict) and isinstance(B, dict):
    41             for i in A:
    42                 try:
    43                     B[i]
    44                 except:
    45                     L.append('▇▇▇ A中的key %s/%s 未在B中找到
    ' % (xpath, i))
    46                     continue
    47                 if not (isinstance(A.get(i), (list, dict)) or isinstance(B.get(i), (list, dict))):
    48                     if type(A.get(i)) != type(B.get(i)):
    49                         L.append('▇▇▇ 类型不同参数在[A]中的绝对路径:  %s/%s  ►►► A is %s, B is %s 
    ' % (xpath, i, type(A.get(i)), type(B.get(i))))
    50                     elif A.get(i) != B.get(i):
    51                         L.append('▇▇▇ 仅内容不同参数在[A]中的绝对路径:  %s/%s  ►►► A is %s, B is %s 
    ' % (xpath, i, A.get(i), B.get(i)))
    52                     continue
    53                 self.compare_json_data(A.get(i), B.get(i), L, xpath + '/' + str(i))
    54             return
    55         if type(A) != type(B):
    56             L.append('▇▇▇ 类型不同参数在[A]中的绝对路径:  %s  ►►► A is %s, B is %s 
    ' % (xpath, type(A), type(B)))
    57         elif A != B and type(A) is not list:
    58             L.append('▇▇▇ 仅内容不同参数在[A]中的绝对路径:  %s  ►►► A is %s, B is %s 
    ' % (xpath, A, B))
    59         return L
    60 
    61     def Assert(self,A,B):
    62         C = []
    63         self.compare_json_data(A, B, C)
    64         assert len(C) == 0, "
    "+"".join(C)
     1 #!/usr/bin/env python
     2 # -*- coding: utf-8 -*-
     3 # @Time    : 2017-07-28 18:07
     4 import unittest
     5 import HTMLTestRunner
     6 import time
     7 import tool
     8 import json
     9 
    10 class Test(unittest.TestCase):
    11     heixiongjing = 666
    12     # 获取测试数据
    13 
    14 # 闭包函数用于生成用例
    15 
    16 def demo(i):
    17     def case(self):
    18         CaseUrl = i[2]+i[3]
    19         RequestType = i[4]
    20         Paramete = i[5]
    21         Result = json.loads(i[6])
    22         apiresult = apitest.request(RequestType, CaseUrl, Paramete, '')
    23         code = apiresult.status_code
    24         assert code == 200, '▇▇▇请求失败!'+'  '+'code:'+str(code)+'  '+'url='+CaseUrl
    25         pam = json.loads(apiresult.text)
    26         apitest.Assert(pam, Result)
    27 
    28     setattr(case, '__doc__', str(i[1]))
    29     return case
    30 
    31 # 根据用例条数循环生成用例
    32 def testall(num):
    33     for i in num:
    34         setattr(Test, 'test_'+str(int(i[0])), demo(i))
    35 
    36 
    37 if __name__ == "__main__":
    38     apitest = tool.APiTool()
    39     xlsFile = r"D:myapi_test2apicase.xls"  # 文件路径
    40     sheetlist1 = apitest.xlsee(xlsFile)
    41     testall(sheetlist1)
    42     suit = unittest.makeSuite(Test)
    43     now = time.strftime("%Y-%m-%d %H_%M_%S", time.localtime(time.time()))
    44     filename = "D:\myapi_test2\report\"+now+'result.html' #定义个报告存放路径,支持相对路径。
    45     fp = open(filename, 'wb')
    46     runner = HTMLTestRunner.HTMLTestRunner(stream=fp, title='自动化测试报告', description='XX平台V1.0')
    47     runner.run(suit)
    48     # unittest.main()

    期间感谢@大师兄@三师兄@饭哥@无敌哥的指导

     

    为什么选择?

    有的人喜欢创造世界,他们做了程序员

    有的人喜欢拯救世界,他们做了测试员

  • 相关阅读:
    推荐一款快得令地发指本地搜索软件:Everything,绝对改变对NTFS的看法
    “/”应用程序中的服务器错误 WebParts开发时出现的错误
    《让人无法说 NO的攻心说话术》摘要
    UXWEEK
    2012中国交互设计体验日演讲实录
    彩色铅笔入门
    ClickOnce证书签名
    DevExpress控件使用小结
    解决ClickOnce签名过期问题
    属于自己的小小空间
  • 原文地址:https://www.cnblogs.com/hxjxb/p/7255432.html
Copyright © 2011-2022 走看看