基于ddt+unittest+Excel做接口测试自动化测试【多测师】
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | 1. 编写读取excelf类 ReadExcel. py # coding=utf-8 import xlrd import sys import inspect class Excel( object ): def __init__( self ,excel_path,sheet_name): self .excel_file = xlrd.open_workbook(excel_path) self .sheet = self .excel_file.sheet_by_name(sheet_name) self .sheet_name = self .sheet.name self .rows = self .sheet.nrows self .cols = self .sheet.ncols """返回单元格,计数(0,0)表示第一行,第一列的单元格""" def get_sheet_data( self ,row,col): test_data = self .sheet.cell(row ,col).value """读取excel,并处理数据返回格式""" def read_excel( self ): list = [] for row in range ( 1 , self .rows): lists = self .sheet.row_values(row)[: self .cols] list1 = [] dict = {} for j in range ( self .cols): list1.append(lists[j].encode( 'utf-8' )) dict [ 'test_name' ] = list1[ 0 ].decode( 'utf-8' ) dict [ 'method' ] = list1[ 1 ].decode( 'utf-8' ) dict [ 'url' ] = list1[ 2 ].decode( 'utf-8' ) dict [ 'data' ] = list1[ 3 ].decode( 'utf-8' ) dict [ 'header' ] = list1[ 4 ].decode( 'utf-8' ) dict [ 'param' ] = list1[ 5 ].decode( 'utf-8' ) dict [ 'type' ] = list1[ 6 ].decode( 'utf-8' ) # print dict list .append( dict ) return list """返回数组""" def get_test_data( self ): array = self .read_excel() return array if __name__ = = "__main__" : path = r "f://myexcel.xlsx" st_name = 'Sheet1' test_data = Excel(path,st_name).read_excel() print (test_data) |
2.封装api,requests库各种请求 testapi.py # coding=utf-8 import json import requests class TestApi(): """ /* @param: @session ,@cookies the request can be divided into session request and cookie request according to user's own choice however,url and header is must ,other parameters are given by user to make it is None or not */ """ def get(self,url,param,header,cookie=None,session=None,**kwargs): if session: return session.request("GET",url,param,headers=header,**kwargs) elif cookie: return requests.get(url,params=param,headers=header,cookies=cookie,**kwargs) """ /* @param: @session ,@cookies 传入的是dict类型 python object 对象 header is form data: application/x-www-urlencoded transfer data to data directly ,finally requests's submit will be like 'aa=dd&bb=ff' formation header is json :application/json due to the data can be 'str','dict'and tuple and so on ,so when we choose data and data is given by dict,we must transfer it to json str,but when is json type str ,we must must transfer python object dict to json str with json.dumps(), finally the request submit data format is str like: 'aa=dd&bb=ff',but when choose json the submit will become like {'a': 'cc' ,'b': 'dd'} , data and json cant not be used in the requests at the same time */ """ def post_data(self,url,type,data,header,cookie=None,session=None,**kwargs): if cookie: if type is "data": return requests.post(url,data=data,header=header,cookies=cookie,**kwargs) elif type is "json": return requests.post(url,data=json.dumps(data),headers=header,cookies=cookie,**kwargs) elif session: if type is "data": return session.request("POST",url,data=data,header=header,cookies=cookie,**kwargs) elif type is "json": return session.request("POST",url,data=json.dumps(data),headers=header,cookies=cookie,**kwargs) """ /* @:param:@json object json的value为传入可序列化的python对象 请求header默认:ContentType: application/json */ """ def post_json(self,url,header,json,cookie=None,session=None,**kwargs): if cookie: return requests.post(url,headers=header,json=json,cookies=cookie,**kwargs) elif session: return session.request("POST",url,headers=header,json=json,**kwargs) """ /* @:param: @url,@data,@**kwargs Tip: header you need to according to your api to be given in **kwargs position */ """ def put(self,url,data,cookie=None,session=None,**kwargs): if cookie: return requests.put(url,data,cookies=cookie,**kwargs) elif session: return session.request("PUT",url,data,**kwargs) """ /* @:param: @url,@data,@**kwargs Tip: header you need to according to your api to given in **kwargs position */ """ def delete(self,url,data,cookie=None,session=None,**kwargs): if cookie: return requests.delete(url,data,cookies=cookie,**kwargs) elif session: return session.request("DELETE",url,data,**kwargs) 3.二次处理请求封装,自动判断请求自动发送参数 from Paramters.apitest import TestApi class TestSend(): def __init__(self,url,method,data,json,header,param,type,cookie1=None, session1=None): self.url=url self.method=method self.data=data self.json=json self.header=header self.param=param self.type=type self.session = session1 self.cookie1 = cookie1 def send(self): if self.method.upper() == "GET": rep = TestApi().get(self.url, self.param, self.header, cookie=self.cookie1, session=self.session) return rep elif self.method.upper() == "POST": rep = TestApi().post_data(self.url, self.type, self.data, self.header, cookie=self.cookie1, session=self.session1) return rep elif self.method.upper() == "PUT": rep = TestApi().put(self.url, self.data, cookie=self.cookie1, session=self.session1) return rep elif self.method.upper() == "DELETE": rep = TestApi().delete(self.url, self.data, cookie=self.cookie1, session=self.session1) return rep
4.ddt+unitest框架编写以及excel读取数据传参+htnl生成方法编写 # coding=utf-8 import ddt import json import requests import unittest import time from HTMLTestRunner import HTMLTestRunner from Paramters.ReadExcel import Excel from Paramters.send import TestSend path=r"f://myexcel.xlsx" st_name='Sheet1' test_data= Excel(path,st_name).read_excel() def run(): suites=unittest.defaultTestLoader.discover('./',pattern='test*.py',top_level_dir=None) report_path='./report.html' with open(report_path, 'wb') as f: runner = HTMLTestRunner(stream=f, title="interface report", description="results like following:",verbosity=1) runner.run(suites) f.close() @ddt.ddt class OverRide(unittest.TestCase): @classmethod def setUpClass(cls): global session s = requests.session() requests.get("http://www.baidu.com") session =s print("---------------开始加载--------------") @classmethod def tearDownClass(cls): """清除cookie""" session.cookies.clear() #也可以这样写 session.cookies=None print("----------------释放完成-------------") @ddt.data(*test_data) def test_data(self,dict): print(dict) defaults = {"url": None, "test_name":None, "header": None, "data": None, "method": None, "param": None, "type": None, "json": None} defaults.update(dict) self.url = defaults["url"] self.header = defaults["header"] self.method = defaults["method"] self.data = defaults["data"] self.param = defaults["param"] self.json = defaults["json"] self.type = defaults["type"] self.test_name=defaults["test_name"] print ("当前执行用例名称:{}".format(self.test_name), time.asctime()) response=TestSend(self.url,self.method,self.data,self.json,self.header,self.param,self.type,session1=session).send() times_out=response.elapsed.total_seconds() headers= response.headers print(response.status_code,times_out,"header内容为:",headers) if __name__ == "__main__": run()
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)