对python自动生成接口测试的示例讲解
程序员文章站
2022-07-01 13:20:23
在python中template可以将字符串的格式固定下来,重复利用。 同一套测试框架为了可以复用,所以我们可以将用例部分做参数化,然后运用到各个项目中。
代码如下:...
在python中template可以将字符串的格式固定下来,重复利用。 同一套测试框架为了可以复用,所以我们可以将用例部分做参数化,然后运用到各个项目中。
代码如下:
coding=utf-8 ''' 作者:大石 功能:自动生成pyunit框架下的接口测试用例 环境:python2.7.6 用法:将用户给的参数处理成对应格式,然后调用模块类生成函数,并将参数传入即可 ''' from string import template #动态生成单个测试用例函数字符串 def singlemethodcreate(methodlist,interfacenamepara): code=template('''\n def test_${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) assert status_code == 200 assert json['status'] == 'ok' ''') string = code.substitute(testcase=methodlist["testcase"],testcasename=methodlist["testcasename"], method=methodlist['method'],url=methodlist['url'],headers=methodlist['headers'],data=methodlist['data'], ) return string #拼接单个的测试用例函数字符串为完整字符串并传回主函数 #methodparalist获取测试用例部分list def methodcreate(methodparalist,interfacenamepara): string = "" for methodpara in methodparalist: string2=singlemethodcreate(methodpara,interfacenamepara) string=string+string2 return string #构造单个测试集 def singletestsuitcreate(methodlist,parameters): code = template('''suite.addtest(${classname}("test_${testcase}"))''') string = code.substitute(testcase = methodlist["testcase"],classname = parameters[0]) return string #添加测试集 def addtestsuit(methodparalist,interfacenamepara): string = "" for methodpara in methodparalist: string2 = singletestsuitcreate(methodpara,interfacenamepara) string=string+string2 return string #生成测试用例类函数字符串 def modelclasscreate(parameters): modelcode = methodcreate(parameters[2],parameters[1]) adtestsuit = addtestsuit(parameters[2],parameters) code = template('''#coding: utf-8 """ 作者:大石 功能:待执行的接口测试用例 环境:python2.7.6 用法:通过框架自动触发调用 """ import unittest,requests,datetime,sys,logging,bstestrunner,time,os from log import log class ${classname}(unittest.testcase): u"""待测试接口:${interfacename}""" def setup(self): logging.info('-'*5+"begin test"+"-"*5) def teardown(self): logging.info('-'*5+"end test"+'-'*5) ${model} if __name__ == "__main__": #解决unicodedecodeerror: 'ascii' codec can't decode byte 0xe5 in position 97: ordinal not in range(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: if path!= 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 (windows nt 6.1; wow64; trident/7.0; rv:11.0) like gecko', '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 (windows nt 6.1; wow64; trident/7.0; rv:11.0) like gecko', '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 用法:通过框架自动触发调用 """ import unittest,requests,datetime,sys,logging,bstestrunner,time,os from log import log class testcase_orders(unittest.testcase): u"""待测试接口:/login""" def setup(self): logging.info('-'*5+"begin test"+"-"*5) def teardown(self): logging.info('-'*5+"end test"+'-'*5) def test_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 (windows nt 6.1; wow64; trident/7.0; rv:11.0) like gecko'} 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) assert status_code == 200 assert json['status'] == 'ok' def test_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 (windows nt 6.1; wow64; trident/7.0; rv:11.0) like gecko'} 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) assert status_code == 200 assert json['status'] == 'ok' if __name__ == "__main__": #解决unicodedecodeerror: 'ascii' codec can't decode byte 0xe5 in position 97: ordinal not in range(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: if path!= 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添加测试集的一个简单方法:
#添加测试集 def addtestsuit(parameters): string = "" temp = template('''\n suite.addtest(${classname}("test_${testcase}")) ''') l = len(parameters[2]) for i in range(0,l): testcase1 = parameters[2][i]['testcase'] string2 = temp.substitute(classname = parameters[0],testcase = testcase1) string=string+string2 print string return string
以上这篇对python自动生成接口测试的示例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。