对python自动生成接口测试的示例讲解
在python中Template可以将字符串的格式固定下来,重复利用。同一套测试框架为了可以复用,所以我们可以将用例部分做参数化,然后运用到各个项目中。
代码如下:
coding=utf-8 ''' 作者:大石 功能:自动生成pyunit框架下的接口测试用例 环境:python2.7.6 用法:将用户给的参数处理成对应格式,然后调用模块类生成函数,并将参数传入即可 ''' fromstringimportTemplate #动态生成单个测试用例函数字符串 defsingleMethodCreate(MethodList,interfaceNamePara): code=Template('''\ndeftest_${testcase}(self): u"""${testcaseName}""" headers=$headers data=$data re=requests.$method(url='$url',headers=headers,data=data) status_code=re.status_code s=str(status_code) json=re.text logging.info('-'*5+'返回状态码是'+s+'-'*5) logging.info('-'*5+'返回结果集是'+json+'-'*5) assertstatus_code==200 assertjson['status']=='ok' ''') string=code.substitute(testcase=MethodList["testcase"],testcaseName=MethodList["TestcaseName"], method=MethodList['method'],url=MethodList['url'],headers=MethodList['headers'],data=MethodList['data'], ) returnstring #拼接单个的测试用例函数字符串为完整字符串并传回主函数 #MethodParaList获取测试用例部分list defmethodCreate(MethodParaList,interfaceNamePara): string="" forMethodParainMethodParaList: string2=singleMethodCreate(MethodPara,interfaceNamePara) string=string+string2 returnstring #构造单个测试集 defsingleTestsuitCreate(MethodList,parameters): code=Template('''suite.addTest(${className}("test_${testcase}"))''') string=code.substitute(testcase=MethodList["testcase"],className=parameters[0]) returnstring #添加测试集 defaddtestsuit(MethodParaList,interfaceNamePara): string="" forMethodParainMethodParaList: string2=singleTestsuitCreate(MethodPara,interfaceNamePara) string=string+string2 returnstring #生成测试用例类函数字符串 defmodelClassCreate(parameters): modelCode=methodCreate(parameters[2],parameters[1]) adtestsuit=addtestsuit(parameters[2],parameters) code=Template('''#coding:utf-8 """ 作者:大石 功能:待执行的接口测试用例 环境:python2.7.6 用法:通过框架自动触发调用 """ importunittest,requests,datetime,sys,logging,BSTestRunner,time,os fromLogimportLog class${className}(unittest.TestCase): u"""待测试接口:${interfaceName}""" defsetUp(self): logging.info('-'*5+"begintest"+"-"*5) deftearDown(self): logging.info('-'*5+"endtest"+'-'*5) ${model} if__name__=="__main__": #解决UnicodeDecodeError:'ascii'codeccan'tdecodebyte0xe5inposition97:ordinalnotinrange(128) reload(sys) sys.setdefaultencoding('utf8') #构造测试集 suite=unittest.TestSuite() ${testsuite} #定义date为日期,time为时间 date=time.strftime("%Y%m%d") time1=time.strftime("%H%M%S") now=time.strftime("%Y-%m-%d-%H_%M_%S",time.localtime(time.time())) #创建路径 path='F:/test/study/yaml/test_log/'+now+"/" #解决多次执行时报路径已存在的错误 try: os.makedirs(path) except: ifpath!=None: logging.error(u'当前路径已经存在') filename=path+'Report.html' fp=file(filename,'wb') #日志记录 Log.log() #执行测试 runner=BSTestRunner.BSTestRunner(stream=fp,title=u'下单平台接口测试用例',description=u'接口用例列表:') runner.run(suite) fp.close() ''') fileStr=code.substitute(className=parameters[0],interfaceName=parameters[1],testsuite=adtestsuit,model=modelCode) f=open(parameters[0]+".py",'w') f.write(fileStr) f.close()
然后测试用例部分如下:
parameters=["Testcase_Orders", "/login", [ {"TestcaseName":"测试登录","method":"post","url":"http://www.senbaba.cn/login","headers":{'content-type':'application/json', 'User-Agent':'Mozilla/5.0(WindowsNT6.1;WOW64;Trident/7.0;rv:11.0)likeGecko', 'Accept':'application/x-ms-application,image/jpeg,application/xaml+xml,image/gif,image/pjpeg,application/x-ms-xbap,*/*', 'Accept-Language':'zh-CN'},"data":{"uname":"187071484771","pwd":"123456"}, "testcase":"login"}, {"TestcaseName":"测试登录","method":"post","url":"http://www.senbaba.cn/login1","headers":{'content-type':'application/json', 'User-Agent':'Mozilla/5.0(WindowsNT6.1;WOW64;Trident/7.0;rv:11.0)likeGecko', 'Accept':'application/x-ms-application,image/jpeg,application/xaml+xml,image/gif,image/pjpeg,application/x-ms-xbap,*/*', 'Accept-Language':'zh-CN'},"data":{"uname":"187071484771","pwd":"123457"}, "testcase":"login_failed"} ] ]
自动生成的测试用例如下:
#coding:utf-8 """ 作者:大石 功能:待执行的接口测试用例 环境:python2.7.6 用法:通过框架自动触发调用 """ importunittest,requests,datetime,sys,logging,BSTestRunner,time,os fromLogimportLog classTestcase_Orders(unittest.TestCase): u"""待测试接口:/login""" defsetUp(self): logging.info('-'*5+"begintest"+"-"*5) deftearDown(self): logging.info('-'*5+"endtest"+'-'*5) deftest_login(self): u"""测试登录""" headers={'Accept-Language':'zh-CN','content-type':'application/json','Accept':'application/x-ms-application,image/jpeg,application/xaml+xml,image/gif,image/pjpeg,application/x-ms-xbap,*/*','User-Agent':'Mozilla/5.0(WindowsNT6.1;WOW64;Trident/7.0;rv:11.0)likeGecko'} data={'uname':'187071484771','pwd':'123456'} re=requests.post(url='http://www.senbaba.cn/login',headers=headers,data=data) status_code=re.status_code s=str(status_code) json=re.text logging.info('-'*5+'返回状态码是'+s+'-'*5) logging.info('-'*5+'返回结果集是'+json+'-'*5) assertstatus_code==200 assertjson['status']=='ok' deftest_login_failed(self): u"""测试登录""" headers={'Accept-Language':'zh-CN','content-type':'application/json','Accept':'application/x-ms-application,image/jpeg,application/xaml+xml,image/gif,image/pjpeg,application/x-ms-xbap,*/*','User-Agent':'Mozilla/5.0(WindowsNT6.1;WOW64;Trident/7.0;rv:11.0)likeGecko'} data={'uname':'187071484771','pwd':'123457'} re=requests.post(url='http://www.senbaba.cn/login1',headers=headers,data=data) status_code=re.status_code s=str(status_code) json=re.text logging.info('-'*5+'返回状态码是'+s+'-'*5) logging.info('-'*5+'返回结果集是'+json+'-'*5) assertstatus_code==200 assertjson['status']=='ok' if__name__=="__main__": #解决UnicodeDecodeError:'ascii'codeccan'tdecodebyte0xe5inposition97:ordinalnotinrange(128) reload(sys) sys.setdefaultencoding('utf8') #构造测试集 suite=unittest.TestSuite() suite.addTest(Testcase_Orders("test_login")) suite.addTest(Testcase_Orders("test_login_failed")) #定义date为日期,time为时间 date=time.strftime("%Y%m%d") time1=time.strftime("%H%M%S") now=time.strftime("%Y-%m-%d-%H_%M_%S",time.localtime(time.time())) #创建路径 path='F:/test/study/yaml/test_log/'+now+"/" #解决多次执行时报路径已存在的错误 try: os.makedirs(path) except: ifpath!=None: logging.error(u'当前路径已经存在') filename=path+'Report.html' fp=file(filename,'wb') #日志记录 Log.log() #执行测试 runner=BSTestRunner.BSTestRunner(stream=fp,title=u'下单平台接口测试用例',description=u'接口用例列表:') runner.run(suite) fp.close()
20171019添加测试集的一个简单方法:
#添加测试集 defaddtestsuit(parameters): string="" temp=Template('''\nsuite.addTest(${className}("test_${testcase}")) ''') l=len(parameters[2]) foriinrange(0,l): testcase1=parameters[2][i]['testcase'] string2=temp.substitute(className=parameters[0],testcase=testcase1) string=string+string2 printstring returnstring
以上这篇对python自动生成接口测试的示例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。