Python實(shí)現(xiàn)http接口自動(dòng)化測(cè)試的示例代碼
網(wǎng)上http接口自動(dòng)化測(cè)試Python實(shí)現(xiàn)有很多,我也是在慕課網(wǎng)上學(xué)習(xí)了相關(guān)課程,并實(shí)際操作了一遍,于是進(jìn)行一些總結(jié),便于以后回顧溫習(xí),有許多不完善的地方,希望大神們多多指教!
接口測(cè)試常用的工具有fiddler,postman,jmeter等,使用這些工具測(cè)試時(shí),需要了解常用的接口類型和區(qū)別,比如我用到的post和get請(qǐng)求,表面上看get用于獲取數(shù)據(jù)post用于修改數(shù)據(jù),兩者傳遞參數(shù)的方式也有不一樣,get是直接在url里通過(guò)?來(lái)連接參數(shù),而post則是把數(shù)據(jù)放在HTTP的包體內(nèi)(request body),兩者的本質(zhì)就是TCP鏈接,并無(wú)差別,但是由于HTTP的規(guī)定和瀏覽器/服務(wù)器的限制,導(dǎo)致他們?cè)趹?yīng)用過(guò)程中體現(xiàn)出一些不同。具體的可以參考此博文,講解的比較通俗易懂。這些在工具中可以直接選擇,python需要借助requests包。
確定好接口類型后,需要做的就是準(zhǔn)備測(cè)試數(shù)據(jù)和設(shè)計(jì)測(cè)試用例了,測(cè)試用例比如說(shuō)可以判斷返回狀態(tài)響應(yīng)碼,或者對(duì)返回?cái)?shù)據(jù)進(jìn)行判別等,具體可以參考postman中的echo.collections,對(duì)于python可以用unittest來(lái)組織測(cè)試用例和添加斷言進(jìn)行判斷。而對(duì)于測(cè)試數(shù)據(jù)的準(zhǔn)備,需要做到數(shù)據(jù)和業(yè)務(wù)盡量分離,即將測(cè)試數(shù)據(jù)參數(shù)化,在工具中可以通過(guò)添加變量的形式實(shí)現(xiàn),對(duì)于python設(shè)計(jì)到的有關(guān)包有xlrd,json,如果需要連接數(shù)據(jù)庫(kù)還需要mysql。
測(cè)試完成后生產(chǎn)報(bào)告或者發(fā)送郵件,也可以使用HTMLTestRunner和smtplib等。
我也從這三大方面進(jìn)行總結(jié):
1. 接口方法實(shí)現(xiàn)和封裝
requests庫(kù)可以很好的幫助我們實(shí)現(xiàn)HTTP請(qǐng)求,API參考文檔,這里我創(chuàng)建了runmethod.py,里面包含RunMethod類:
這里需要注意就是python默認(rèn)參數(shù)和可選參數(shù)要放在必選參數(shù)后面,對(duì)于相應(yīng)數(shù)據(jù)使用json格式進(jìn)行返回。參數(shù)verify=false表示忽略對(duì) SSL 證書的驗(yàn)證。
2.組織測(cè)試和生成報(bào)告
使用unittest來(lái)組織測(cè)試、添加測(cè)試用例和斷言,測(cè)試報(bào)告可以下載HTMLTestRunner.py并放在python安裝路徑lib下即可,代碼如下:
#coding:utf-8 import unittest import json import HTMLTestRunner from mock import mock #from demo import RunMain from runmethod import RunMethod from mock_demo import mock_test import os class TestMethod(unittest.TestCase): def setUp(self): #self.run=RunMain() self.run = RunMethod() def test_01(self): url = 'http://coding.imooc.com/api/cate' data = { 'timestamp':'1507034803124', 'uid':'5249191', 'uuid':'5ae7d1a22c82fb89c78f603420870ad7', 'secrect':'078474b41dd37ddd5efeb04aa591ec12', 'token':'7d6f14f21ec96d755de41e6c076758dd', 'cid':'0', 'errorCode':1001 } #self.run.run_main = mock.Mock(return_value=data) res = mock_test(self.run.run_main,data,url,"POST",data) #res = self.run.run_main(url,'POST',data) print(res) self.assertEqual(res['errorCode'],1001,"測(cè)試失敗") @unittest.skip('test_02') def test_02(self): url = 'http://coding.imooc.com/api/cate' data = { 'timestamp':'1507034803124', 'uid':'5249191', 'uuid':'5ae7d1a22c82fb89c78f603420870ad7', 'secrect':'078474b41dd37ddd5efeb04aa591ec12', 'token':'7d6f14f21ec96d755de41e6c076758dd', 'cid':'0' } res = self.run.run_main(url,'GET',data) self.assertEqual(res['errorCode'],1006,"測(cè)試失敗") def test_03(self): url = 'http://coding.imooc.com/api/cate' data = { 'timestamp':'1507034803124', 'uid':'5249191', 'uuid':'5ae7d1a22c82fb89c78f603420870ad7', 'secrect':'078474b41dd37ddd5efeb04aa591ec12', 'token':'7d6f14f21ec96d755de41e6c076758dd', 'cid':'0', 'status':11 } res = mock_test(self.run.run_main,data,url,'GET',data) print(res) self.assertGreater(res['status'],10,'測(cè)試通過(guò)') if __name__ == '__main__': filepath = os.getcwd()+'\\report.html' fp = open(filepath,'wb+') suite = unittest.TestSuite() suite.addTest(TestMethod('test_01')) suite.addTest(TestMethod('test_02')) suite.addTest(TestMethod('test_03')) runner = HTMLTestRunner.HTMLTestRunner(stream=fp,title='this is demo test') runner.run(suite) #unittest.main()
這里setUp()方法用來(lái)在測(cè)試之前執(zhí)行,同樣的有tearDown()方法,測(cè)試case以test開頭進(jìn)行編寫,然后使用TestSuit類生成測(cè)試套件,將case添加進(jìn)去,運(yùn)行run suite即可。當(dāng)測(cè)試用例較多時(shí),可以生成多個(gè)測(cè)試類別,然后使用TestLoader().LoadTestsFromTestCase(測(cè)試類)
生成測(cè)試用例,再加入testsuite執(zhí)行。
在這里,我使用了學(xué)習(xí)到的mock方法,mock即模擬數(shù)據(jù),當(dāng)我們無(wú)法實(shí)際執(zhí)行獲得數(shù)據(jù)時(shí)可以使用mock方法,模擬生成我們需要判別的數(shù)據(jù),這里mock_test方法同樣進(jìn)行了封裝:
#coding:utf-8 from mock import mock def mock_test(mock_method,request_data,url,method,response_data): mock_method = mock.Mock(return_value=response_data) res = mock_method(url,method,request_data) return res
這里模擬的是self.run.run_main()方法,將這個(gè)方法的返回值設(shè)為response_data,而最終我們要判斷的是返回值res,可以結(jié)合test_02對(duì)比,
res = self.run.run_main(url,'GET',data)
所以又需要傳入?yún)?shù)url,method,request_data,最后返回相應(yīng)數(shù)據(jù)即可,
res = mock_test(self.run.run_main,data,url,'GET',data)
這里我假設(shè)返回的數(shù)據(jù)為data,隨意添加了幾個(gè)判斷條件errorCode==1001
和status>10
作為判斷依據(jù)。最后生成報(bào)告如下:
3 測(cè)試數(shù)據(jù)處理
這一部分主要包括設(shè)計(jì)測(cè)試數(shù)據(jù),數(shù)據(jù)提取和參數(shù)化,以及解決數(shù)據(jù)依賴。這里還是以慕課網(wǎng)上學(xué)習(xí)的例子為例,主要依據(jù)測(cè)試目的和使用流程來(lái)設(shè)計(jì),如下圖:
這里首先涉及到的就是對(duì)Excel表格的操作,導(dǎo)入相關(guān)庫(kù)import xlrd
,先對(duì)如上表的測(cè)試用例進(jìn)行配置文件編寫:
class global_var: Id = '0' request_name = '1' url = '2' run = '3' request_way = '4' header = '5' case_depend = '6' data_depend = '7' field_depend = '8' data = '9' expect = '10' result = '11'
再定義返回該列的函數(shù),例如獲取caseId和URL:
def get_id(): return global_var.Id def get_url(): return global_var.url
3.1操作Excel文件
然后我們?cè)倬帉懖僮鱁xcel的模塊,主要包含了對(duì)Excel表格的操作,獲取表單、行、列、單元格內(nèi)容等。
import xlrd from xlutils.copy import copy class OperationExcel: def __init__(self,file_name=None,sheet_id=None): if file_name: self.file_name = file_name self.sheet_id = sheet_id else: self.file_name = '/dataconfig/case1.xls' self.sheet_id = 0 self.data = self.get_data() #獲取sheets的內(nèi)容 def get_data(self): data = xlrd.open_workbook(self.file_name) tables = data.sheets()[self.sheet_id] return tables #獲取單元格的行數(shù) def get_lines(self): tables = self.data return tables.nrows #獲取某一個(gè)單元格的內(nèi)容 def get_cell_value(self,row,col): return self.data.cell_value(row,col) #寫入數(shù)據(jù) def write_value(self,row,col,value): '''寫入excel數(shù)據(jù)row,col,value''' read_data = xlrd.open_workbook(self.file_name) write_data = copy(read_data) sheet_data = write_data.get_sheet(0) sheet_data.write(row,col,value) write_data.save(self.file_name)
其中寫數(shù)據(jù)用于將運(yùn)行結(jié)果寫入Excel文件,先用copy復(fù)制整個(gè)文件,通過(guò)get_sheet()獲取的sheet有write()方法。
3.2操作json文件
對(duì)于請(qǐng)求數(shù)據(jù),我是根據(jù)關(guān)鍵字從json文件里取出字段,所以還需要json格式的數(shù)據(jù)文件,如下。對(duì)應(yīng)請(qǐng)求數(shù)據(jù)中的各個(gè)關(guān)鍵字:
所以還需要編寫對(duì)應(yīng)操作json文件的模塊:
import json class OperetionJson: def __init__(self,file_path=None): if file_path == None: self.file_path = '/dataconfig/user.json' else: self.file_path = file_path self.data = self.read_data() #讀取json文件 def read_data(self): with open(self.file_path) as fp: data = json.load(fp) return data #根據(jù)關(guān)鍵字獲取數(shù)據(jù) def get_data(self,id): print(type(self.data)) return self.data[id]
讀寫操作使用的是json.load(),json.dump()
傳入的是文件句柄。
3.3 獲得測(cè)試數(shù)據(jù)
在定義好Excel和json操作模塊后,我們將其應(yīng)用于我們的測(cè)試表單,定義一個(gè)獲取數(shù)據(jù)模塊:
from util.operation_excel import OperationExcel import data.data_config from util.operation_json import OperetionJson class GetData: def __init__(self): self.opera_excel = OperationExcel() #去獲取excel行數(shù),就是我們的case個(gè)數(shù) def get_case_lines(self): return self.opera_excel.get_lines() #獲取是否執(zhí)行 def get_is_run(self,row): flag = None col = int(data_config.get_run()) run_model = self.opera_excel.get_cell_value(row,col) if run_model == 'yes': flag = True else: flag = False return flag #是否攜帶header def is_header(self,row): col = int(data_config.get_header()) header = self.opera_excel.get_cell_value(row,col) if header != '': return header else: return None #獲取請(qǐng)求方式 def get_request_method(self,row): col = int(data_config.get_run_way()) request_method = self.opera_excel.get_cell_value(row,col) return request_method #獲取url def get_request_url(self,row): col = int(data_config.get_url()) url = self.opera_excel.get_cell_value(row,col) return url #獲取請(qǐng)求數(shù)據(jù) def get_request_data(self,row): col = int(data_config.get_data()) data = self.opera_excel.get_cell_value(row,col) if data == '': return None return data #通過(guò)獲取關(guān)鍵字拿到data數(shù)據(jù) def get_data_for_json(self,row): opera_json = OperetionJson() request_data = opera_json.get_data(self.get_request_data(row)) return request_data #獲取預(yù)期結(jié)果 def get_expcet_data(self,row): col = int(data_config.get_expect()) expect = self.opera_excel.get_cell_value(row,col) if expect == '': return None return expect def write_result(self,row,value): col = int(data_config.get_result()) self.opera_excel.write_value(row,col,value)
該模塊將Excel操作類實(shí)例化后用于操作測(cè)試表單,分別獲得測(cè)試運(yùn)行所需的各種條件。
3.4 判斷條件
這里判斷一個(gè)case是否通過(guò),是將實(shí)際結(jié)果和預(yù)期結(jié)果進(jìn)行對(duì)比,比如,狀態(tài)碼status是不是200,或者在返回?cái)?shù)據(jù)中查看是否含有某一字段:
import json import operator as op class CommonUtil: def is_contain(self, str_one,str_two): ''' 判斷一個(gè)字符串是否再另外一個(gè)字符串中 str_one:查找的字符串 str_two:被查找的字符串 ''' flag = None #先將返回的res進(jìn)行格式轉(zhuǎn)換,unicode轉(zhuǎn)成string類型 if isinstance(str_one,unicode): str_one = str_one.encode('unicode-escape').decode('string_escape') return op.eq(str_one,str_two) if str_one in str_two: flag = True else: flag = False return flag def is_equal_dict(self,dict_one,dict_two): '''判斷兩個(gè)字典是否相等''' if isinstance(dict_one,str): dict_one = json.loads(dict_one) if isinstance(dict_two,str): dict_two = json.loads(dict_two) return op.eq(dict_one,dict_two)
所以我們獲得expec數(shù)據(jù)和相應(yīng)數(shù)據(jù),再調(diào)用這個(gè)類別的is_contain()
方法就能判斷。
3.5 數(shù)據(jù)依賴問(wèn)題
當(dāng)我們要執(zhí)行的某個(gè)case的相應(yīng)數(shù)據(jù)依賴于前面某個(gè)case的返回?cái)?shù)據(jù)時(shí),我們需要對(duì)相應(yīng)數(shù)據(jù)進(jìn)行更新,比如case12的相應(yīng)數(shù)據(jù)request_data[數(shù)據(jù)依賴字段]
的值應(yīng)該更新于case11的返回?cái)?shù)據(jù)response_data[依賴的返回字段]
。那么我們就需要先執(zhí)行case11拿到返回?cái)?shù)據(jù),再寫入case12的相應(yīng)數(shù)據(jù),首先對(duì)操作Excel的模塊進(jìn)行更新加入:
#獲取某一列的內(nèi)容 def get_cols_data(self,col_id=None): if col_id != None: cols = self.data.col_values(col_id) else: cols = self.data.col_values(0) return cols #根據(jù)對(duì)應(yīng)的caseid找到對(duì)應(yīng)的行號(hào) def get_row_num(self,case_id): num = 0 cols_data = self.get_cols_data() for col_data in cols_data: if case_id in col_data: return num num = num+1 #根據(jù)行號(hào),找到該行的內(nèi)容 def get_row_values(self,row): tables = self.data row_data = tables.row_values(row) return row_data #根據(jù)對(duì)應(yīng)的caseid 找到對(duì)應(yīng)行的內(nèi)容 def get_rows_data(self,case_id): row_num = self.get_row_num(case_id) rows_data = self.get_row_values(row_num) return rows_data
即我們通過(guò)依賴的caseId找到對(duì)應(yīng)的行號(hào),拿到整行的內(nèi)容。我們默認(rèn)拿到列0的內(nèi)容(即caseId)循環(huán)整列找到依賴的caseId在第幾行,然后返回整行數(shù)據(jù),即實(shí)現(xiàn)方法get_rows_data(case_id)
。然后再去執(zhí)行和更新,我們編寫一個(gè)專門處理依賴數(shù)據(jù)的模塊,同時(shí),為了獲取依賴數(shù)據(jù),還需要對(duì)獲取數(shù)據(jù)模塊進(jìn)行更新如下:
#獲取依賴數(shù)據(jù)的key def get_depend_key(self,row): col = int(data_config.get_data_depend()) depent_key = self.opera_excel.get_cell_value(row,col) if depent_key == "": return None else: return depent_key #判斷是否有case依賴 def is_depend(self,row): col = int(data_config.get_case_depend()) depend_case_id = self.opera_excel.get_cell_value(row,col) if depend_case_id == "": return None else: return depend_case_id #獲取數(shù)據(jù)依賴字段 def get_depend_field(self,row): col = int(data_config.get_field_depend()) data = self.opera_excel.get_cell_value(row,col) if data == "": return None else: return data
將方法應(yīng)用于專門處理依賴數(shù)據(jù)的模塊:
from util.operation_excel import OperationExcel from base.runmethod import RunMethod from data.get_data import GetData from jsonpath_rw import jsonpath,parse class DependdentData: def __init__(self,case_id): self.case_id = case_id self.opera_excel = OperationExcel() self.data = GetData() #通過(guò)case_id去獲取該case_id的整行數(shù)據(jù) def get_case_line_data(self): rows_data = self.opera_excel.get_rows_data(self.case_id) return rows_data #執(zhí)行依賴測(cè)試,獲取結(jié)果 def run_dependent(self): run_method = RunMethod() row_num = self.opera_excel.get_row_num(self.case_id) request_data = self.data.get_data_for_json(row_num) #header = self.data.is_header(row_num) method = self.data.get_request_method(row_num) url = self.data.get_request_url(row_num) res = run_method.run_main(method,url,request_data) return json.loads(res)#返回?cái)?shù)據(jù)是字符串需要轉(zhuǎn)成json格式方便后續(xù)查詢 #根據(jù)依賴的key去獲取執(zhí)行依賴測(cè)試case的響應(yīng),然后返回 def get_data_for_key(self,row): depend_data = self.data.get_depend_key(row) response_data = self.run_dependent() json_exe = parse(depend_data) madle = json_exe.find(response_data) return [math.value for math in madle][0]
其中jsonpath用于找到多層級(jí)數(shù)據(jù),類似于xpath,即通過(guò)依賴字段表示的層級(jí)關(guān)系在返回?cái)?shù)據(jù)中找到對(duì)應(yīng)的值,最后再執(zhí)行該case時(shí)把數(shù)據(jù)更新。
3.6 主流程
把上述所有模塊導(dǎo)入,編寫主流程模塊:
from util.operation_excel import OperationExcel from base.runmethod import RunMethod from data.get_data import GetData from jsonpath_rw import jsonpath,parse class DependdentData: def __init__(self,case_id): self.case_id = case_id self.opera_excel = OperationExcel() self.data = GetData() #通過(guò)case_id去獲取該case_id的整行數(shù)據(jù) def get_case_line_data(self): rows_data = self.opera_excel.get_rows_data(self.case_id) return rows_data #執(zhí)行依賴測(cè)試,獲取結(jié)果 def run_dependent(self): run_method = RunMethod() row_num = self.opera_excel.get_row_num(self.case_id) request_data = self.data.get_data_for_json(row_num) #header = self.data.is_header(row_num) method = self.data.get_request_method(row_num) url = self.data.get_request_url(row_num) res = run_method.run_main(method,url,request_data) return json.loads(res)#返回?cái)?shù)據(jù)是字符串需要轉(zhuǎn)成json格式方便后續(xù)查詢 #根據(jù)依賴的key去獲取執(zhí)行依賴測(cè)試case的響應(yīng),然后返回 def get_data_for_key(self,row): depend_data = self.data.get_depend_key(row) response_data = self.run_dependent() json_exe = parse(depend_data) madle = json_exe.find(response_data) return [math.value for math in madle][0]
這樣我們就完成了測(cè)試執(zhí)行,并對(duì)結(jié)果進(jìn)行了統(tǒng)計(jì),同時(shí)解決了數(shù)據(jù)依賴問(wèn)題。
到此這篇關(guān)于Python實(shí)現(xiàn)http接口自動(dòng)化測(cè)試的示例代碼的文章就介紹到這了,更多相關(guān)Python http接口自動(dòng)化測(cè)試內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Anaconda+pycharm安裝及環(huán)境配置全過(guò)程
在使用pyCharm進(jìn)行開發(fā)時(shí),需要用到Anaconda創(chuàng)建的環(huán)境,下面這篇文章主要給大家介紹了關(guān)于Anaconda+pycharm安裝及環(huán)境配置的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-09-09Django中redis的使用方法(包括安裝、配置、啟動(dòng))
下面小編就為大家分享一篇Django中redis的使用方法(包括安裝、配置、啟動(dòng)),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-02-02基于Python+QT的gui程序開發(fā)實(shí)現(xiàn)
這篇文章主要介紹了基于Python+QT的gui程序開發(fā)實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07Python用5行代碼實(shí)現(xiàn)批量摳圖的示例代碼
這篇文章主要介紹了Python用5行代碼實(shí)現(xiàn)批量摳圖的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-04-04TensorFlow實(shí)現(xiàn)簡(jiǎn)單線性回歸
這篇文章主要為大家詳細(xì)介紹了TensorFlow實(shí)現(xiàn)簡(jiǎn)單線性回歸,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03python pandas模塊基礎(chǔ)學(xué)習(xí)詳解
這篇文章主要介紹了python pandas模塊基礎(chǔ)學(xué)習(xí)詳解的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-07-07基于多進(jìn)程中APScheduler重復(fù)運(yùn)行的解決方法
今天小編就為大家分享一篇基于多進(jìn)程中APScheduler重復(fù)運(yùn)行的解決方法,具有很好的價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-07-07使用pd.merge表連接出現(xiàn)多余行的問(wèn)題解決
本文主要介紹了使用pd.merge表連接出現(xiàn)多余行的問(wèn)題解決,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06Python計(jì)算機(jī)視覺(jué)SIFT尺度不變的圖像特征變換
這篇文章主要為大家介紹了Python計(jì)算機(jī)視覺(jué)SIFT尺度不變的圖像特征變換,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05