近期一直在學習python,這兩天正好做rest接口的接口測試,就嘗試着用python寫一個測試rest接口的通用類,省去用工具的繁瑣,也顯得比較高大上一些。
http rest接口最常用的兩種請求方式,POST和GET兩種方法,請求都是類似下面例子的url。
例子:http://127.0.0.1:8080/rest/login?oper_no=marry。
需要用到python的幾個內置模塊,urllib、urllib2、re、os、time。urllib和urllib2是網絡模塊,re是正則表達式模塊,os是系統模塊,用它來執行一些系統命令,time模塊用它來取當前系統時間。
代碼如下,都加了對應的註釋:
import urllib,urllib2
import re,os
import time
class RestTest(object):
def __init__(self):
'''
python的魔術方法,類似java的構造函數,該類在實例化的時候會調用這個函數
'''
self.__ResPath__='/Users/niuhanyang/Desktop/TestRes/'#測試結果路徑
def Rest(self,method,url,restName,**param):
'''
:param method: 請求方法,GET/POST,入參類型是str
:param url: 請求url地址,入參類型是str
:param restName: 接口名稱,入參,類型是str
:param param: 請求參數是一個可選參數,例如oper_id=11,會把傳入的值都放到一個dict中,如{'oper_id':11}
:return:如果是登錄接口的話,會返回jessionid
'''
jsessionStr=r'"jsessionid":"(.*?)"'#正則表達式,抓出jsessionid
new_jsessionStr = re.compile(jsessionStr)#編譯正則
if method=='GET':
data = self.UrlParam(param)
new_url=url+'?'+data#生成新的url
result = urllib.urlopen(new_url).read()#保存返回結果
print restName+'\n'+result
self.WriteRes(result,restName)#保存測試結果和返回報文
return ''.join(new_jsessionStr.findall(result))
if method=='POST':
data = self.UrlParam(param)#參數轉換
req = urllib2.Request(url,data)#生成一個request對象
response = urllib2.urlopen(req)#發送request請求
result = response.read()#保存結果
print restName+'\n'+result
self.WriteRes(result,restName)#保存測試結果和返回報文
return ''.join(new_jsessionStr.findall(result))#把jsessionid轉化成字符串返回,findall方法的返回值是一個list
def UrlParam(self,param):
'''
參數轉換,入參是一個dict,把這個list變爲xx=xx這樣
示例:
入參:{'oper_id':11}
出參:oper_id=11
'''
return urllib.urlencode(param)
def WriteRes(self,result,restName):
'''
:param result: 返回報文
:param restName: 接口名,用來做報文結果的文件名
:return: 無返回值
'''
res= result.find('success')#返回結果是否成功
fw_flag = open('%sTestRes.txt'%self.__ResPath__,'a')#追加方式打開測試結果文件
if res>0:
fw_flag.write('%s : pass\n'%restName)#寫入測試結果
else:
fw_flag.write('%s : fail\n'%restName)#寫入測試結果
fw_flag.close()
fw_response = open('%s%s.txt'%(self.__ResPath__,restName),'w')#打開返回報文文件,前面一個%s是路徑,後面的%s是以接口名命名的文件名
fw_response.write(result)#寫入返回報文
fw_response.close()
def BakRes(self):
'''
該函數的作用是用來備份測試結果
'''
now_time= time.strftime("%m-%d_%H:%M", time.localtime())
os.system('cd %s&&mkdir %s&&mv *.txt ./%s'%(self.__ResPath__,now_time,now_time))
def RmRes(self):
'''
清空測試目錄下的所有測試結果
'''
os.system('cd %s&&rm -rf *'%self.__ResPath__)
if __name__ == '__main__':
Test = RestTest()#創建一個實例
session_id = Test.Rest('POST','http://127.0.0.1:8080/nn_web/rest/oper/login','login',login_flag=0,oper_no='HEHH',oper_pwd=1)#調用Rest方法測試登錄接口,獲取session_id
Test.Rest('POST','http://127.0.0.1:8080/nn_web/rest/oper/getOperInfo','getOperInfo',jsessionid=session_id)#調用獲取工號信息接口,傳入登錄獲取到的seession_id
接下來繼續研究python在webservice接口測試中的應用,有哪些不足的地方大家提出來哦。