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()