一、用Excel编写用例(xlsx格式)
截图仅供参考,实际用例编写需要根据实际情况来。
二、用例加载、验证
1、数据的加载
import xlrd,xlwt #python操作excel主要用到xlrd和xlwt这两个库,即xlrd是读excel,xlwt是写excel的库def datacel():try:filepath='.\\test_case\\jenkins_case.xlsx'file=xlrd.open_workbook(filepath)#打开excel文件工作簿me=file.sheets()[3]#指定到具体sheet4表nrows=me.nrows#读行数#用例IDlistid=[]# 用例名称listname = []# keylistkey = []#参数listcontent=[]#urllisturl=[]#请求方式listfangshi=[]#断言 期望值listqiwang=[]for i in range(1,nrows):listid.append(me.cell(i,0).value)listname.append(me.cell(i, 1).value)listkey.append(me.cell(i,2).value)listcontent.append(me.cell(i,3).value)listurl.append(me.cell(i,4).value)listfangshi.append(me.cell(i,5).value)listqiwang.append(me.cell(i,6).value)return listid,listname,listkey,listcontent,listurl,listfangshi,listqiwangexcept:print("数据错误,请检查表格")def makedata():listid, listname, listkey, listcontent, listurl, listfangshi, listqiwang=datacel()make_data=[]for i in range(len(listid)):make_data.append({'url':listurl[i],'key':listkey[i],'content':listcontent[i],'fangshi':listfangshi[i],'qiwang':listqiwang[i]})return make_dataif __name__ == '__main__':data_test = makedata()for i in range(len(data_test)):print(data_test[i])
2、数据使用
import unittest, requests from ddt import ddt,data #数据驱动 from unittest_excel.get_excel import makedata #引用数据加载模块 data_exce=makedata() #变量=makedata()返回值 list,每个元素是字典、用例 @ddt class TestStringMethods(unittest.TestCase):def setUp(self):print('+++')def tearDown(self):print('---')@data(*data_exce)def test_url(self,data_exce):print(data_exce['url'])print(data_exce['key'])print(data_exce['content'])print(data_exce['fangshi'])print(data_exce['qiwang'])@data(*data_exce)def test_request(self,data_exce):r=requests.post(url=data_exce['url'],json=data_exce['key'])print(data_exce['url'],r.status_code)if __name__ == '__main__':unittest.main()
3、单个目标验证
''' 这里暂时只比较了返回的value是否和预期一致的情况,没有比较目标的键值都相同以及目标的层级 dict:待测目标 objkey:目标key objvalue:目标value ''' def dict_get(dict, objvalue, default):tmp = dictfor k,v in tmp.items():# 如果dict中的value和目标value相同,则返回value,这里也可以改成键值都相等if v == objvalue:return velse:if (type(v).__name__ == 'list'):#如果类型是list,且不为空if len(v)>=1:for i in range(0,(len(v))) :ret= dict_get(v[i], objvalue, default)#递归调用,如果不是返回default,则跳出递归if ret is not default:return retif (type(v).__name__ == 'dict'):#如果类型是dict,且不为空if len(v)>=1:for i in range(0,(len(v))) :ret = dict_get(v, objvalue, default)#递归调用,如果不是返回default,则跳出递归if ret is not default:return retreturn default#找不到时返回的默认值if __name__ == '__main__':test={"sites": [{ "name":"test" , "url":"www.test.com" },{ "name":"google" , "url":"www.google.com" },{ "name":"weibo" , "url":"www.weibo.com" }]}a=dict_get(test,"www.weibo.co",'未找到')print(a)
4、整个response验证,这里是以单个目标验证为基础的方法
from Template_Log.log import LOG,logger from unittest_t3.check_kv import dict_get@logger('断言测试结果,通过返回pass,失败返回fail') def assert_in(assert_hope,response):if len(assert_hope.split('=')) > 1:#目标示例: assert_hope:name=google&url=www.google.comdata = assert_hope.split('&')#分割后示例:[name=google,url=www.google.com]result = dict([(item.split('=')) for item in data])#分割后示例: {name:google,url:www.google.com} value1=[]for value in result.values():s=dict_get(response, value, None)#期望的value和响应response对比,如果有相同就返回valueif (s != None):value1.append(s)else:return 'fail'print('断言通过,断言的实际值是:',value1)return 'pass'else:LOG.info('填写测试预期值')raise ('请填写期望值')
三、实例
import json,ddt import unittest,requests from Template_Log.log import LOG,logger#数据驱动 from unittest_t2.get_excel import makedata from unittest_t3.check_all import assert_in from unittest_t3.xmltojson import Xml2Json data_exce=makedata()@ddt.ddt class TestStringMethods(unittest.TestCase):def setUp(self):LOG.info("start_here")def tearDown(self):LOG.info("end_here")@logger('进入用例test_insert')@ddt.data(*data_exce)def test_insert(self,data_exce):r=requests.post(data_exce['url'],data=data_exce['key'])try:apijson = json.loads(r.text)except Exception:apijson = Xml2Json(r.text).resultprint('返回结果:', r.json())print('期望值:',data_exce['qiwang'])LOG.info('返回结果:%s'%apijson)qingwang=assert_in(data_exce['qiwang'],apijson)LOG.info('断言结果:%s'%qingwang)self.assertEqual(qingwang,'pass',msg='预期和返回一致')if __name__ == '__main__':unittest.main()