對python自動生成接口測試的示例講解
在python中Template可以將字符串的格式固定下來,重復利用。 同一套測試框架為了可以復用,所以我們可以將用例部分做參數(shù)化,然后運用到各個項目中。
代碼如下:
coding=utf-8
'''
作者:大石
功能:自動生成pyunit框架下的接口測試用例
環(huán)境:python2.7.6
用法:將用戶給的參數(shù)處理成對應格式,然后調(diào)用模塊類生成函數(shù),并將參數(shù)傳入即可
'''
from string import Template
#動態(tài)生成單個測試用例函數(shù)字符串
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+'返回狀態(tài)碼是'+s+'-'*5)
logging.info('-'*5+'返回結(jié)果集是'+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
#拼接單個的測試用例函數(shù)字符串為完整字符串并傳回主函數(shù)
#MethodParaList獲取測試用例部分list
def methodCreate(MethodParaList,interfaceNamePara):
string = ""
for MethodPara in MethodParaList:
string2=singleMethodCreate(MethodPara,interfaceNamePara)
string=string+string2
return string
#構(gòu)造單個測試集
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
#生成測試用例類函數(shù)字符串
def modelClassCreate(parameters):
modelCode = methodCreate(parameters[2],parameters[1])
adtestsuit = addtestsuit(parameters[2],parameters)
code = Template('''#coding: utf-8
"""
作者:大石
功能:待執(zhí)行的接口測試用例
環(huán)境:python2.7.6
用法:通過框架自動觸發(fā)調(diào)用
"""
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')
#構(gòu)造測試集
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()))
#創(chuàng)建路徑
path='F:/test/study/yaml/test_log/'+now+"/"
#解決多次執(zhí)行時報路徑已存在的錯誤
try:
os.makedirs(path)
except:
if path!= None:
logging.error(u'當前路徑已經(jīng)存在')
filename=path+'Report.html'
fp=file(filename,'wb')
#日志記錄
Log.log()
#執(zhí)行測試
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
"""
作者:大石
功能:待執(zhí)行的接口測試用例
環(huán)境:python2.7.6
用法:通過框架自動觸發(fā)調(diào)用
"""
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+'返回狀態(tài)碼是'+s+'-'*5)
logging.info('-'*5+'返回結(jié)果集是'+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+'返回狀態(tài)碼是'+s+'-'*5)
logging.info('-'*5+'返回結(jié)果集是'+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')
#構(gòu)造測試集
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()))
#創(chuàng)建路徑
path='F:/test/study/yaml/test_log/'+now+"/"
#解決多次執(zhí)行時報路徑已存在的錯誤
try:
os.makedirs(path)
except:
if path!= None:
logging.error(u'當前路徑已經(jīng)存在')
filename=path+'Report.html'
fp=file(filename,'wb')
#日志記錄
Log.log()
#執(zhí)行測試
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自動生成接口測試的示例講解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
python爬取之json、pickle與shelve庫的深入講解
這篇文章主要給大家介紹了關(guān)于python爬取之json、pickle與shelve庫的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-03-03
pycharm安裝深度學習pytorch的d2l包失敗問題解決
當新生在學習pytorch時,導入d2l_pytorch包總會遇到問題,下面這篇文章主要給大家介紹了關(guān)于pycharm安裝深度學習pytorch的d2l包失敗問題的解決方法,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2022-03-03
matplotlib多子圖實現(xiàn)共享坐標軸的示例詳解
這篇文章主要為大家詳細介紹了matplotlib繪制多子圖師如何實現(xiàn)共享坐標軸,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下2024-02-02
六個Python編程最受用的內(nèi)置函數(shù)使用詳解
在日常的python編程中使用這幾個函數(shù)來簡化我們的編程工作,經(jīng)常使用能使編程效率大大地提高。本文為大家總結(jié)了六個Python編程最受用的內(nèi)置函數(shù),感興趣的可以了解一下2022-07-07
Python腳本實現(xiàn)監(jiān)聽服務器的思路代碼詳解
這篇文章主要介紹了Python腳本實現(xiàn)監(jiān)聽服務器的思路,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-05-05
使用Python分析文本數(shù)據(jù)的詞頻并詞云圖可視化
這篇文章主要給大家介紹了關(guān)于如何使用Python分析文本數(shù)據(jù)的詞頻并詞云圖可視化,文章中有詳細的圖文介紹和代碼示例,對我們的學習或工作有一定的幫助,需要的朋友可以參考下2023-09-09
Pandas實現(xiàn)復制dataframe中的每一行
這篇文章主要介紹了Pandas實現(xiàn)復制dataframe中的每一行方式,2024-02-02

