pytest接口自動化測試框架搭建的全過程
一. 背景
Pytest目前已經(jīng)成為Python系自動化測試必學必備的一個框架,網(wǎng)上也有很多的文章講述相關(guān)的知識。最近自己也抽時間梳理了一份pytest接口自動化測試框架,因此準備寫文章記錄一下,做到盡量簡單通俗易懂,當然前提是基本的python基礎已經(jīng)掌握了。如果能夠?qū)π聦W習這個框架的同學起到一些幫助,那就更好了~
二. 基礎環(huán)境
語言:python 3.8
編譯器:pycharm
基礎:具備python編程基礎
框架:pytest+requests+allure
三. 項目結(jié)構(gòu)
項目結(jié)構(gòu)圖如下:

每一層具體的含義如下圖:

測試報告如下圖:

四、框架解析
4.1 接口數(shù)據(jù)文件處理

框架中使用草料二維碼的get和post接口用于demo測試,比如:
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請求的話,case中會多一個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)境運行,不用換了環(huán)境后挨個兒去改數(shù)據(jù)文件,比如
測試環(huán)境URL為:https://testcli.im/qrcode/getDefaultComponentMsg
生產(chǎn)環(huán)境URL為:https://cli.im/qrcode/getDefaultComponentMsg
因此數(shù)據(jù)文件中url只填寫后半段,不填域名。然后config》global_config.py下設置全局變量來定義域名:
# 配置HTTP接口的域名,方便一套腳本用于多套環(huán)境運行時,只需要改這里的全局配置就OK CAOLIAO_HTTP_POST_HOST = "https://cli.im" CAOLIAO_HTTP_GET_HOST = "https://nc.cli.im"
utils文件夾下,創(chuàng)建工具類文件: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,是一個list列表,list列表中包含多個字典
dataitem=opers.get_value('dataItem')
print(dataitem)運行結(jié)果如下:

4.2 封裝測試工具類
utils文件夾下,除了上面提到的讀取Json文件工具類:read_jsonfile_utils.py,還有封裝request 請求的工具類:http_utils.py
從Excel文件中讀取數(shù)據(jù)的工具類:get_excel_data_utils.py(雖然本次框架中暫時未采用存放接口數(shù)據(jù)到Excel中,但也寫了個工具類,需要的時候可以用)

http_utils.py內(nèi)容:
import requests
import json
class HttpUtils:
@staticmethod
def http_post(headers, url, parameters):
print("接口請求url:" + url)
print("接口請求headers:" + json.dumps(headers))
print("接口請求parameters:" + json.dumps(parameters))
res = requests.post(url, data=parameters, headers=headers)
print("接口返回結(jié)果:"+res.text)
if res.status_code != 200:
raise Exception(u"請求異常")
result = json.loads(res.text)
return result
@staticmethod
def http_get(headers, url):
req_headers = json.dumps(headers)
print("接口請求url:" + url)
print("接口請求headers:" + req_headers)
res = requests.get(url, headers=headers)
print("接口返回結(jié)果:" + res.text)
if res.status_code != 200:
raise Exception(u"請求異常")
result = json.loads(res.text)
return resultget_excel_data_utils.py內(nèi)容:
import xlrd
from xlrd import xldate_as_tuple
import datetime
class ExcelData(object):
'''
xlrd中單元格的數(shù)據(jù)類型
數(shù)字一律按浮點型輸出,日期輸出成一串小數(shù),布爾型輸出0或1,所以我們必須在程序中做判斷處理轉(zhuǎn)換
成我們想要的數(shù)據(jù)類型
0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
'''
def __init__(self, data_path, sheetname="Sheet1"):
#定義一個屬性接收文件路徑
self.data_path = data_path
# 定義一個屬性接收工作表名稱
self.sheetname = sheetname
# 使用xlrd模塊打開excel表讀取數(shù)據(jù)
self.data = xlrd.open_workbook(self.data_path)
# 根據(jù)工作表的名稱獲取工作表中的內(nèi)容
self.table = self.data.sheet_by_name(self.sheetname)
# 根據(jù)工作表的索引獲取工作表的內(nèi)容
# self.table = self.data.sheet_by_name(0)
# 獲取第一行所有內(nèi)容,如果括號中1就是第二行,這點跟列表索引類似
self.keys = self.table.row_values(0)
# 獲取工作表的有效行數(shù)
self.rowNum = self.table.nrows
# 獲取工作表的有效列數(shù)
self.colNum = self.table.ncols
# 定義一個讀取excel表的方法
def readExcel(self):
# 定義一個空列表
datas = []
for i in range(1, self.rowNum):
# 定義一個空字典
sheet_data = {}
for j in range(self.colNum):
# 獲取單元格數(shù)據(jù)類型
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對象
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)每一個有效的單元格,將字段與值對應存儲到字典中
# 字典的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 測試用例代碼編寫
testcases文件夾下編寫測試用例:

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請求測試")
class TestHttpInterface:
# 獲取文件相對路徑
data_file_path = ReadJsonFileUtils.get_data_path("resources", "test_http_get_data.json")
# 讀取測試數(shù)據(jù)文件
param_data = ReadJsonFileUtils(data_file_path)
data_item = param_data.get_value('dataItem') # 是一個list列表,list列表中包含多個字典
"""
@pytest.mark.parametrize是數(shù)據(jù)驅(qū)動;
data_item列表中有幾個字典,就運行幾次case
ids是用于自定義用例的名稱
"""
@pytest.mark.parametrize("args", data_item, ids=['測試草料二維碼get接口1', '測試草料二維碼get接口2'])
def test_caoliao_get_demo(self, args, login_test):
# 打印用例ID和名稱到報告中顯示
print("用例ID:{}".format(args['id']))
print("用例名稱:{}".format(args['name']))
print("測試conftest傳值:{}".format(login_test))
logging.info("測試開始啦~~~~~~~")
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值不等于預期"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,不然會有warning,說這個Mark有問題
@pytest.mark.httptest
@allure.feature("草料二維碼post請求測試")
class TestHttpInterface:
# 獲取文件相對路徑
data_file_path = ReadJsonFileUtils.get_data_path("resources", "test_http_post_data.json")
# 讀取測試數(shù)據(jù)文件
param_data = ReadJsonFileUtils(data_file_path)
data_item = param_data.get_value('dataItem') #是一個list列表,list列表中包含多個字典
"""
@pytest.mark.parametrize是數(shù)據(jù)驅(qū)動;
data_item列表中有幾個字典,就運行幾次case
ids是用于自定義用例的名稱
"""
@pytest.mark.parametrize("args", data_item, ids=['測試草料二維碼post接口1','測試草料二維碼post接口2'])
def test_caoliao_post_demo(self, args):
# 打印用例ID和名稱到報告中顯示
print("用例ID:{}".format(args['id']))
print("用例名稱:{}".format(args['name']))
logging.info("測試開始啦~~~~~~~")
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值不等于預期"
assert str(res.get('data').get('qrtype')) == str(args['expectdata']['qrtype']), "接口返回qrtype值不等于預期"企業(yè)中的系統(tǒng)接口,通常都有認證,需要先登錄獲取token,后續(xù)接口調(diào)用時都需要認證token。因此框架需要能處理在運行用例前置和后置做一些動作,所以這里用到了conftest.py文件,內(nèi)容如下:
import logging
import traceback
import pytest
import requests
"""
如果用例執(zhí)行前需要先登錄獲取token值,就要用到conftest.py文件了
作用:conftest.py 配置里可以實現(xiàn)數(shù)據(jù)共享,不需要import導入 conftest.py,pytest用例會自動查找
scope參數(shù)為session,那么所有的測試文件執(zhí)行前執(zhí)行一次
scope參數(shù)為module,那么每一個測試文件執(zhí)行前都會執(zhí)行一次conftest文件中的fixture
scope參數(shù)為class,那么每一個測試文件中的測試類執(zhí)行前都會執(zhí)行一次conftest文件中的fixture
scope參數(shù)為function,那么所有文件的測試用例執(zhí)行前都會執(zhí)行一次conftest文件中的fixture
"""
# 獲取到登錄請求返回的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('開始調(diào)用登錄接口:{}'.format(url))
res = requests.post(url, data=params, headers=header, verify=False) # verify:忽略https的認證
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
#測試一下conftest.py文件和fixture的作用
@pytest.fixture(scope="session")
def login_test():
print("運行用例前先登錄!")
# 使用yield關(guān)鍵字實現(xiàn)后置操作,如果上面的前置操作要返回值,在yield后面加上要返回的值
# 也就是yield既可以實現(xiàn)后置,又可以起到return返回值的作用
yield "runBeforeTestCase"
print("運行用例后退出登錄!")由于用例中用到了@pytest.mark.httptest給用例打標,因此需要創(chuàng)建pytest.ini文件,并在里面添加markers = httptest,不然會有warning,說這個Mark有問題。并且用例中用到的日志打印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 測試用例運行生成報告 ???????
運行方式:
Terminal窗口,進入到testcases目錄下,執(zhí)行命令:
運行某一條case:pytest test_caoliao_http_post_interface.py
運行所有case: pytest
運行指定標簽的case:pytest -m httptest
運行并打印過程中的詳細信息:pytest -s test_caoliao_http_post_interface.py
運行并生成pytest-html報告:pytest test_caoliao_http_post_interface.py --html=../testoutput/report.html
運行并生成allure測試報告:
1. 先清除掉testoutput/result文件夾下的所有文件
2. 運行case,生成allure文件:pytest --alluredir ../testoutput/result
3. 根據(jù)文件生成allure報告:allure generate ../testoutput/result/ -o ../testoutput/report/ --clean
4. 如果不是在pycharm中打開,而是直接到report目錄下打開index.html文件打開的報告無法展示數(shù)據(jù),需要雙擊generateAllureReport.bat生成allure報告;
pytest-html報告:

generateAllureReport.bat文件位置:
文件內(nèi)容:
allure open report/
Allure報告:

框架中用到的一些細節(jié)知識點和問題,如:
conftest.py和@pytest.fixture()結(jié)合使用
pytest中使用logging打印日志
python中獲取文件相對路徑的方式
python虛擬環(huán)境
pytest框架下Allure的使用
我會在后續(xù)寫文章再介紹。另外框架同樣適用于dubbo接口的自動化測試,只需要添加python調(diào)用dubbo的工具類即可,后續(xù)也會寫文章專門介紹。
總結(jié)
到此這篇關(guān)于pytest接口自動化測試框架搭建的文章就介紹到這了,更多相關(guān)pytest接口自動化測試內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python驗證公網(wǎng)ip與內(nèi)網(wǎng)ip的實現(xiàn)示例
本文主要介紹了python驗證公網(wǎng)ip與內(nèi)網(wǎng)ip的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-07-07
PyQt中使用QTabWidget實現(xiàn)多頁面布局的方法
在使用PyQt編寫桌面應用程序的過程中,要實現(xiàn)多頁面布局方案,可以使用QTabWidget控件來實現(xiàn),本案例提供了完整的標簽頁管理功能,同時保持了響應式設計的核心原則,能夠很好地適應不同屏幕尺寸和內(nèi)容變化,感興趣的朋友一起看看吧2025-04-04
python數(shù)據(jù)預處理 :數(shù)據(jù)抽樣解析
這篇文章主要介紹了python數(shù)據(jù)預處理 :數(shù)據(jù)抽樣解析,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02

