pytest接口自動(dòng)化測(cè)試框架搭建的全過(guò)程
一. 背景
Pytest目前已經(jīng)成為Python系自動(dòng)化測(cè)試必學(xué)必備的一個(gè)框架,網(wǎng)上也有很多的文章講述相關(guān)的知識(shí)。最近自己也抽時(shí)間梳理了一份pytest接口自動(dòng)化測(cè)試框架,因此準(zhǔn)備寫(xiě)文章記錄一下,做到盡量簡(jiǎn)單通俗易懂,當(dāng)然前提是基本的python基礎(chǔ)已經(jīng)掌握了。如果能夠?qū)π聦W(xué)習(xí)這個(gè)框架的同學(xué)起到一些幫助,那就更好了~
二. 基礎(chǔ)環(huán)境
語(yǔ)言:python 3.8
編譯器:pycharm
基礎(chǔ):具備python編程基礎(chǔ)
框架:pytest+requests+allure
三. 項(xiàng)目結(jié)構(gòu)
項(xiàng)目結(jié)構(gòu)圖如下:
每一層具體的含義如下圖:
測(cè)試報(bào)告如下圖:
四、框架解析
4.1 接口數(shù)據(jù)文件處理
框架中使用草料二維碼的get和post接口用于demo測(cè)試,比如:
get接口:https://cli.im/qrcode/getDefaultComponentMsg
返回值:{“code”:1,“msg”:"",“data”:{xxxxx}}
數(shù)據(jù)文件這里選擇使用Json格式,文件內(nèi)容格式如下,test_http_get_data.json:
{ "dataItem": [ { "id": "testget-1", "name": "草料二維碼get接口1", "headers":{ "Accept-Encoding":"gzip, deflate, br" }, "url":"/qrcode/getDefaultComponentMsg", "method":"get", "expectdata": { "code": "1" } }, { "id": "testget-2", "name": "草料二維碼get接口2", "headers":{}, "url":"/qrcode/getDefaultComponentMsg", "method":"get", "expectdata": { "code": "1" } } ] }
表示dataitem下有兩條case,每條case里面聲明了id, name, header, url, method, expectdata。如果是post請(qǐng)求的話(huà),case中會(huì)多一個(gè)parameters表示入?yún)?,如下?/p>
{ "id":"testpost-1", "name":"草料二維碼post接口1", "url":"/Apis/QrCode/saveStatic", "headers":{ "Content-Type":"application/x-www-form-urlencoded", "Accept-Encoding":"gzip, deflate, br" }, "parameters":{ "info":11111, "content":11111, "level":"H", "size":500, "fgcolor":"#000000", "bggcolor":"#FFFFFF", "transparent":"false", "type":"text", "codeimg":1 }, "expectdata":{ "status":"1", "qrtype":"static" } }
為了方便一套腳本用于不同的環(huán)境運(yùn)行,不用換了環(huán)境后挨個(gè)兒去改數(shù)據(jù)文件,比如
測(cè)試環(huán)境URL為:https://testcli.im/qrcode/getDefaultComponentMsg
生產(chǎn)環(huán)境URL為:https://cli.im/qrcode/getDefaultComponentMsg
因此數(shù)據(jù)文件中url只填寫(xiě)后半段,不填域名。然后config》global_config.py下設(shè)置全局變量來(lái)定義域名:
# 配置HTTP接口的域名,方便一套腳本用于多套環(huán)境運(yùn)行時(shí),只需要改這里的全局配置就OK CAOLIAO_HTTP_POST_HOST = "https://cli.im" CAOLIAO_HTTP_GET_HOST = "https://nc.cli.im"
utils文件夾下,創(chuàng)建工具類(lèi)文件:read_jsonfile_utils.py, 用于讀取json文件內(nèi)容:
import json import os class ReadJsonFileUtils: def __init__(self, file_name): self.file_name = file_name self.data = self.get_data() def get_data(self): fp = open(self.file_name,encoding='utf-8') data = json.load(fp) fp.close() return data def get_value(self, id): return self.data[id] @staticmethod def get_data_path(folder, fileName): BASE_PATH = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) data_file_path = os.path.join(BASE_PATH, folder, fileName) return data_file_path if __name__ == '__main__': opers = ReadJsonFileUtils("..\\resources\\test_http_post_data.json") #讀取文件中的dataItem,是一個(gè)list列表,list列表中包含多個(gè)字典 dataitem=opers.get_value('dataItem') print(dataitem)
運(yùn)行結(jié)果如下:
4.2 封裝測(cè)試工具類(lèi)
utils文件夾下,除了上面提到的讀取Json文件工具類(lèi):read_jsonfile_utils.py,還有封裝request 請(qǐng)求的工具類(lèi):http_utils.py
從Excel文件中讀取數(shù)據(jù)的工具類(lèi):get_excel_data_utils.py(雖然本次框架中暫時(shí)未采用存放接口數(shù)據(jù)到Excel中,但也寫(xiě)了個(gè)工具類(lèi),需要的時(shí)候可以用)
http_utils.py內(nèi)容:
import requests import json class HttpUtils: @staticmethod def http_post(headers, url, parameters): print("接口請(qǐng)求url:" + url) print("接口請(qǐng)求headers:" + json.dumps(headers)) print("接口請(qǐng)求parameters:" + json.dumps(parameters)) res = requests.post(url, data=parameters, headers=headers) print("接口返回結(jié)果:"+res.text) if res.status_code != 200: raise Exception(u"請(qǐng)求異常") result = json.loads(res.text) return result @staticmethod def http_get(headers, url): req_headers = json.dumps(headers) print("接口請(qǐng)求url:" + url) print("接口請(qǐng)求headers:" + req_headers) res = requests.get(url, headers=headers) print("接口返回結(jié)果:" + res.text) if res.status_code != 200: raise Exception(u"請(qǐng)求異常") result = json.loads(res.text) return result
get_excel_data_utils.py內(nèi)容:
import xlrd from xlrd import xldate_as_tuple import datetime class ExcelData(object): ''' xlrd中單元格的數(shù)據(jù)類(lèi)型 數(shù)字一律按浮點(diǎn)型輸出,日期輸出成一串小數(shù),布爾型輸出0或1,所以我們必須在程序中做判斷處理轉(zhuǎn)換 成我們想要的數(shù)據(jù)類(lèi)型 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error ''' def __init__(self, data_path, sheetname="Sheet1"): #定義一個(gè)屬性接收文件路徑 self.data_path = data_path # 定義一個(gè)屬性接收工作表名稱(chēng) self.sheetname = sheetname # 使用xlrd模塊打開(kāi)excel表讀取數(shù)據(jù) self.data = xlrd.open_workbook(self.data_path) # 根據(jù)工作表的名稱(chēng)獲取工作表中的內(nèi)容 self.table = self.data.sheet_by_name(self.sheetname) # 根據(jù)工作表的索引獲取工作表的內(nèi)容 # self.table = self.data.sheet_by_name(0) # 獲取第一行所有內(nèi)容,如果括號(hào)中1就是第二行,這點(diǎn)跟列表索引類(lèi)似 self.keys = self.table.row_values(0) # 獲取工作表的有效行數(shù) self.rowNum = self.table.nrows # 獲取工作表的有效列數(shù) self.colNum = self.table.ncols # 定義一個(gè)讀取excel表的方法 def readExcel(self): # 定義一個(gè)空列表 datas = [] for i in range(1, self.rowNum): # 定義一個(gè)空字典 sheet_data = {} for j in range(self.colNum): # 獲取單元格數(shù)據(jù)類(lèi)型 c_type = self.table.cell(i,j).ctype # 獲取單元格數(shù)據(jù) c_cell = self.table.cell_value(i, j) if c_type == 2 and c_cell % 1 == 0: # 如果是整形 c_cell = int(c_cell) elif c_type == 3: # 轉(zhuǎn)成datetime對(duì)象 date = datetime.datetime(*xldate_as_tuple(c_cell, 0)) c_cell = date.strftime('%Y/%d/%m %H:%M:%S') elif c_type == 4: c_cell = True if c_cell == 1 else False sheet_data[self.keys[j]] = c_cell # 循環(huán)每一個(gè)有效的單元格,將字段與值對(duì)應(yīng)存儲(chǔ)到字典中 # 字典的key就是excel表中每列第一行的字段 # sheet_data[self.keys[j]] = self.table.row_values(i)[j] # 再將字典追加到列表中 datas.append(sheet_data) # 返回從excel中獲取到的數(shù)據(jù):以列表存字典的形式返回 return datas if __name__ == "__main__": data_path = "..\\resources\\test_http_data.xls" sheetname = "Sheet1" get_data = ExcelData(data_path, sheetname) datas = get_data.readExcel() print(datas)
4.3 測(cè)試用例代碼編寫(xiě)
testcases文件夾下編寫(xiě)測(cè)試用例:
test_caoliao_http_get_interface.py內(nèi)容:
import logging import allure import pytest from utils.http_utils import HttpUtils from utils.read_jsonfile_utils import ReadJsonFileUtils from config.global_config import CAOLIAO_HTTP_GET_HOST @pytest.mark.httptest @allure.feature("草料二維碼get請(qǐng)求測(cè)試") class TestHttpInterface: # 獲取文件相對(duì)路徑 data_file_path = ReadJsonFileUtils.get_data_path("resources", "test_http_get_data.json") # 讀取測(cè)試數(shù)據(jù)文件 param_data = ReadJsonFileUtils(data_file_path) data_item = param_data.get_value('dataItem') # 是一個(gè)list列表,list列表中包含多個(gè)字典 """ @pytest.mark.parametrize是數(shù)據(jù)驅(qū)動(dòng); data_item列表中有幾個(gè)字典,就運(yùn)行幾次case ids是用于自定義用例的名稱(chēng) """ @pytest.mark.parametrize("args", data_item, ids=['測(cè)試草料二維碼get接口1', '測(cè)試草料二維碼get接口2']) def test_caoliao_get_demo(self, args, login_test): # 打印用例ID和名稱(chēng)到報(bào)告中顯示 print("用例ID:{}".format(args['id'])) print("用例名稱(chēng):{}".format(args['name'])) print("測(cè)試conftest傳值:{}".format(login_test)) logging.info("測(cè)試開(kāi)始啦~~~~~~~") res = HttpUtils.http_get(args['headers'], CAOLIAO_HTTP_GET_HOST+args['url']) # assert斷言,判斷接口是否返回期望的結(jié)果數(shù)據(jù) assert str(res.get('code')) == str(args['expectdata']['code']), "接口返回status值不等于預(yù)期"
test_caoliao_http_post_interface.py內(nèi)容:
import pytest import logging import allure from utils.http_utils import HttpUtils from utils.read_jsonfile_utils import ReadJsonFileUtils from config.global_config import CAOLIAO_HTTP_POST_HOST # pytest.ini文件中要添加markers = httptest,不然會(huì)有warning,說(shuō)這個(gè)Mark有問(wèn)題 @pytest.mark.httptest @allure.feature("草料二維碼post請(qǐng)求測(cè)試") class TestHttpInterface: # 獲取文件相對(duì)路徑 data_file_path = ReadJsonFileUtils.get_data_path("resources", "test_http_post_data.json") # 讀取測(cè)試數(shù)據(jù)文件 param_data = ReadJsonFileUtils(data_file_path) data_item = param_data.get_value('dataItem') #是一個(gè)list列表,list列表中包含多個(gè)字典 """ @pytest.mark.parametrize是數(shù)據(jù)驅(qū)動(dòng); data_item列表中有幾個(gè)字典,就運(yùn)行幾次case ids是用于自定義用例的名稱(chēng) """ @pytest.mark.parametrize("args", data_item, ids=['測(cè)試草料二維碼post接口1','測(cè)試草料二維碼post接口2']) def test_caoliao_post_demo(self, args): # 打印用例ID和名稱(chēng)到報(bào)告中顯示 print("用例ID:{}".format(args['id'])) print("用例名稱(chēng):{}".format(args['name'])) logging.info("測(cè)試開(kāi)始啦~~~~~~~") res = HttpUtils.http_post(args['headers'], CAOLIAO_HTTP_POST_HOST+args['url'], args['parameters']) # assert斷言,判斷接口是否返回期望的結(jié)果數(shù)據(jù) assert str(res.get('status')) == str(args['expectdata']['status']), "接口返回status值不等于預(yù)期" assert str(res.get('data').get('qrtype')) == str(args['expectdata']['qrtype']), "接口返回qrtype值不等于預(yù)期"
企業(yè)中的系統(tǒng)接口,通常都有認(rèn)證,需要先登錄獲取token,后續(xù)接口調(diào)用時(shí)都需要認(rèn)證token。因此框架需要能處理在運(yùn)行用例前置和后置做一些動(dòng)作,所以這里用到了conftest.py文件,內(nèi)容如下:
import logging import traceback import pytest import requests """ 如果用例執(zhí)行前需要先登錄獲取token值,就要用到conftest.py文件了 作用:conftest.py 配置里可以實(shí)現(xiàn)數(shù)據(jù)共享,不需要import導(dǎo)入 conftest.py,pytest用例會(huì)自動(dòng)查找 scope參數(shù)為session,那么所有的測(cè)試文件執(zhí)行前執(zhí)行一次 scope參數(shù)為module,那么每一個(gè)測(cè)試文件執(zhí)行前都會(huì)執(zhí)行一次conftest文件中的fixture scope參數(shù)為class,那么每一個(gè)測(cè)試文件中的測(cè)試類(lèi)執(zhí)行前都會(huì)執(zhí)行一次conftest文件中的fixture scope參數(shù)為function,那么所有文件的測(cè)試用例執(zhí)行前都會(huì)執(zhí)行一次conftest文件中的fixture """ # 獲取到登錄請(qǐng)求返回的ticket值,@pytest.fixture裝飾后,testcase文件中直接使用函數(shù)名"login_ticket"即可得到ticket值 @pytest.fixture(scope="session") def login_ticket(): header = { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' } params = { "loginId": "username", "pwd": "password", } url = 'http://testxxxxx.xx.com/doLogin' logging.info('開(kāi)始調(diào)用登錄接口:{}'.format(url)) res = requests.post(url, data=params, headers=header, verify=False) # verify:忽略https的認(rèn)證 try: ticket = res.headers['Set-Cookie'] except Exception as ex: logging.error('登錄失??!接口返回:{}'.format(res.text)) traceback.print_tb(ex) logging.info('登錄成功,ticket值為:{}'.format(ticket)) return ticket #測(cè)試一下conftest.py文件和fixture的作用 @pytest.fixture(scope="session") def login_test(): print("運(yùn)行用例前先登錄!") # 使用yield關(guān)鍵字實(shí)現(xiàn)后置操作,如果上面的前置操作要返回值,在yield后面加上要返回的值 # 也就是yield既可以實(shí)現(xiàn)后置,又可以起到return返回值的作用 yield "runBeforeTestCase" print("運(yùn)行用例后退出登錄!")
由于用例中用到了@pytest.mark.httptest給用例打標(biāo),因此需要?jiǎng)?chuàng)建pytest.ini文件,并在里面添加markers = httptest,不然會(huì)有warning,說(shuō)這個(gè)Mark有問(wèn)題。并且用例中用到的日志打印logging模板也需要在pytest.ini文件中增加日志配置。pytest.ini文件內(nèi)容如下:
[pytest] markers = httptest: run http interface test dubbotest: run dubbo interface test log_cli = true log_cli_level = INFO log_cli_format = %(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s log_cli_date_format=%Y-%m-%d %H:%M:%S log_format = %(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)4s: %(message)s log_date_format=%Y-%m-%d %H:%M:%S
4.4 測(cè)試用例運(yùn)行生成報(bào)告 ???????
運(yùn)行方式:
Terminal窗口,進(jìn)入到testcases目錄下,執(zhí)行命令:
運(yùn)行某一條case:pytest test_caoliao_http_post_interface.py
運(yùn)行所有case: pytest
運(yùn)行指定標(biāo)簽的case:pytest -m httptest
運(yùn)行并打印過(guò)程中的詳細(xì)信息:pytest -s test_caoliao_http_post_interface.py
運(yùn)行并生成pytest-html報(bào)告:pytest test_caoliao_http_post_interface.py --html=../testoutput/report.html
運(yùn)行并生成allure測(cè)試報(bào)告:
1. 先清除掉testoutput/result文件夾下的所有文件
2. 運(yùn)行case,生成allure文件:pytest --alluredir ../testoutput/result
3. 根據(jù)文件生成allure報(bào)告:allure generate ../testoutput/result/ -o ../testoutput/report/ --clean
4. 如果不是在pycharm中打開(kāi),而是直接到report目錄下打開(kāi)index.html文件打開(kāi)的報(bào)告無(wú)法展示數(shù)據(jù),需要雙擊generateAllureReport.bat生成allure報(bào)告;
pytest-html報(bào)告:
generateAllureReport.bat文件位置:
文件內(nèi)容:
allure open report/
Allure報(bào)告:
框架中用到的一些細(xì)節(jié)知識(shí)點(diǎn)和問(wèn)題,如:
conftest.py和@pytest.fixture()結(jié)合使用
pytest中使用logging打印日志
python中獲取文件相對(duì)路徑的方式
python虛擬環(huán)境
pytest框架下Allure的使用
我會(huì)在后續(xù)寫(xiě)文章再介紹。另外框架同樣適用于dubbo接口的自動(dòng)化測(cè)試,只需要添加python調(diào)用dubbo的工具類(lèi)即可,后續(xù)也會(huì)寫(xiě)文章專(zhuān)門(mén)介紹。
總結(jié)
到此這篇關(guān)于pytest接口自動(dòng)化測(cè)試框架搭建的文章就介紹到這了,更多相關(guān)pytest接口自動(dòng)化測(cè)試內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Pytest 自動(dòng)化測(cè)試框架的使用
- pytest自動(dòng)化測(cè)試數(shù)據(jù)驅(qū)動(dòng)yaml/excel/csv/json
- python+pytest自動(dòng)化測(cè)試函數(shù)測(cè)試類(lèi)測(cè)試方法的封裝
- Pytest+Yaml+Excel?接口自動(dòng)化測(cè)試框架的實(shí)現(xiàn)示例
- 淺談基于Pytest框架的自動(dòng)化測(cè)試開(kāi)發(fā)實(shí)踐
- Python自動(dòng)化測(cè)試框架pytest的詳解安裝與運(yùn)行
- 自動(dòng)化測(cè)試Pytest單元測(cè)試框架的基本介紹
- python使用pytest接口自動(dòng)化測(cè)試的使用
- Pytest接口自動(dòng)化測(cè)試框架搭建模板
- 詳解如何使用Pytest進(jìn)行自動(dòng)化測(cè)試
- Pytest自動(dòng)化測(cè)試的具體使用
相關(guān)文章
使用pygame寫(xiě)一個(gè)古詩(shī)詞填空通關(guān)游戲
這篇文章主要介紹了使用pygame寫(xiě)一個(gè)古詩(shī)詞填空通關(guān)游戲,之前寫(xiě)的詩(shī)詞填空的游戲支持python2,現(xiàn)在對(duì)程序進(jìn)行了修改,兼容支持python2和python3,需要的朋友可以參考下2019-12-12Python編程實(shí)現(xiàn)及時(shí)獲取新郵件的方法示例
這篇文章主要介紹了Python編程實(shí)現(xiàn)及時(shí)獲取新郵件的方法,涉及Python實(shí)時(shí)查詢(xún)郵箱及郵件獲取相關(guān)操作技巧,需要的朋友可以參考下2017-08-08簡(jiǎn)單了解什么是神經(jīng)網(wǎng)絡(luò)
這篇文章主要介紹了簡(jiǎn)單了解什么是神經(jīng)網(wǎng)絡(luò),具有一定借鑒價(jià)值,需要的朋友可以參考下。2017-12-12PyQT實(shí)現(xiàn)菜單中的復(fù)制,全選和清空的功能的方法
今天小編就為大家分享一篇PyQT實(shí)現(xiàn)菜單中的復(fù)制,全選和清空的功能的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-06-06PyTorch之torch.randn()如何創(chuàng)建正態(tài)分布隨機(jī)數(shù)
這篇文章主要介紹了PyTorch之torch.randn()如何創(chuàng)建正態(tài)分布隨機(jī)數(shù)問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02python Django批量導(dǎo)入數(shù)據(jù)
這篇文章主要為大家詳細(xì)介紹了python Django批量導(dǎo)入數(shù)據(jù)的相關(guān)資料感興趣的小伙伴們可以參考一下2016-03-03詳細(xì)分析Python collections工具庫(kù)
這篇文章主要介紹了詳解Python collections工具庫(kù)的相關(guān)資料,文中講解非常細(xì)致,代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下2020-07-07python三元運(yùn)算符實(shí)現(xiàn)方法
這篇文章主要介紹了python實(shí)現(xiàn)三元運(yùn)算符的方法,大家參考使用吧2013-12-12Python使用Matplotlib實(shí)現(xiàn)創(chuàng)建動(dòng)態(tài)圖形
動(dòng)態(tài)圖形是使可視化更具吸引力和用戶(hù)吸引力的好方法,它幫助我們以有意義的方式展示數(shù)據(jù)可視化,本文將利用Matplotlib實(shí)現(xiàn)繪制一些常用動(dòng)態(tài)圖形,希望對(duì)大家有所幫助2024-02-02