前言
接口測(cè)試是對(duì)系統(tǒng)和組件之間的接口進(jìn)行測(cè)試,主要是效驗(yàn)數(shù)據(jù)的交換,傳遞和控制管理過程,以及相互邏輯依賴關(guān)系。其中接口協(xié)議分為HTTP,RPC,Webservice,Dubbo,RESTful等類型。
接口測(cè)試流程
1、需求評(píng)審,熟悉業(yè)務(wù)和需求
2、開發(fā)提供接口文檔
3、編寫接口測(cè)試用例
4、用例評(píng)審
5、提測(cè)后開始測(cè)試
6、提交測(cè)試報(bào)告
兩種常見的 HTTP 請(qǐng)求方法:GET 和 POST
框架是一套基于Python+Pytest+Requests+Allure+Jenkins而設(shè)計(jì)的數(shù)據(jù)驅(qū)動(dòng)接口自動(dòng)化測(cè)試的框架。
技術(shù)棧:
Python、Pytest、Requests、Pactverity、Excel、Json、Mysql、Allure、Logbook、Git、Jenkins
框架結(jié)構(gòu)圖:
項(xiàng)目功能:
Python+Pytest+Allure+Jenkins接口自動(dòng)化框架,實(shí)現(xiàn)Excel或Json維護(hù)測(cè)試用例,支持?jǐn)?shù)據(jù)庫操作,利用封裝的請(qǐng)求基類調(diào)取相應(yīng)的測(cè)試用例接口,獲取配置文件中的環(huán)境地址與環(huán)境變量,
結(jié)合Pytest進(jìn)行單元測(cè)試,使用LogBook進(jìn)行記錄日志,并生成allure測(cè)試報(bào)告,最后進(jìn)行Jenkins集成項(xiàng)目實(shí)現(xiàn)集成部署,并發(fā)送測(cè)試報(bào)告郵件。
工具類封裝
1、日志模塊
項(xiàng)目中的log日志是logbook進(jìn)行日志記錄的,方便測(cè)試開發(fā)調(diào)試時(shí)進(jìn)行排錯(cuò)糾正或修復(fù)優(yōu)化。日志可選擇是否打印在屏幕上即運(yùn)行時(shí)是否在終端輸出打印。日志格式輸出可調(diào)整。
handle_log.py部分源碼
def log_type(record, handler):
log = "[{date}] [{level}] [{filename}] [{func_name}] [{lineno}] {msg}".format(
date=record.time, # 日志時(shí)間
level=record.level_name, # 日志等級(jí)
filename=os.path.split(record.filename)[-1], # 文件名
func_name=record.func_name, # 函數(shù)名
lineno=record.lineno, # 行號(hào)
msg=record.message # 日志內(nèi)容
)
return log
# 日志存放路徑
LOG_DIR = BasePath + '/log'
print(LOG_DIR)
if not os.path.exists(LOG_DIR):
os.makedirs(LOG_DIR)
# 日志打印到屏幕
log_std = ColorizedStderrHandler(bubble=True)
log_std.formatter = log_type
# 日志打印到文件
log_file = TimedRotatingFileHandler(
os.path.join(LOG_DIR, '%s.log' % 'log'), date_format='%Y-%m-%d', bubble=True, encoding='utf-8')
log_file.formatter = log_type
# 腳本日志
run_log = Logger("global_log")
def init_logger():
logbook.set_datetime_format("local")
run_log.handlers = []
run_log.handlers.append(log_file)
run_log.handlers.append(log_std)
return ""
打印在終端的日志,如下圖所示。
同時(shí)運(yùn)行項(xiàng)目后,會(huì)在項(xiàng)目文件log中自動(dòng)生成一個(gè)以當(dāng)天日期命名的log文件。點(diǎn)擊log日志文件可查看日志詳情即項(xiàng)目運(yùn)行時(shí)所記錄的日志或報(bào)錯(cuò)日志。如下圖所示。
2、配置文件模塊
項(xiàng)目中涉及到一些配置文件如username、password或環(huán)境變量時(shí),我們可通過配置文件來獲取配置值。通過配置文件中key與value的定義來確定獲取配置文件的值。
handle_init.py部分源碼
class HandleInit:
# 讀取配置文件
def load_ini(self):
file_path = BasePath + "/config/config.ini"
cf = configparser.ConfigParser()
cf.read(file_path, encoding='UTF-8')
return cf
# 獲取ini里面對(duì)應(yīng)key的value
def get_value(self, key, node=None):
if node == None:
node = 'Test'
cf = self.load_ini()
try:
data = cf.get(node, key)
logger.info('獲取配置文件的值,node:{},key:{}, data:{}'.format(node, key, data))
except Exception:
logger.exception('沒有獲取到對(duì)應(yīng)的值,node:{},key:{}'.format(node, key))
data = None
return data
獲取配置文件中的值日志如下圖所示。
3、接口請(qǐng)求封裝
獲取相關(guān)測(cè)試用例及接口用例配置,記錄請(qǐng)求相關(guān)參數(shù)的日志,定義Allure測(cè)試報(bào)告的步驟。
handle_apirequest.py部分代碼
class ApiRequest:
def api_request(self, base_url, test_case_data, case_data):
get_name = None
get_url = None
get_method = None
get_headers = None
get_cookies = None
get_case_name = None
get_case_params = None
response_data = None
try:
get_name = test_case_data['config']['name']
get_url = base_url + test_case_data['config']['url']
get_method = test_case_data['config']['method']
get_headers = test_case_data['config']['headers']
get_cookies = test_case_data['config']['cookies']
except Exception as e:
logger.exception('獲取用例基本信息失敗,{}'.format(e))
try:
get_case_name = case_data['name']
get_case_params = case_data['params']
except Exception as e:
logger.exception('獲取測(cè)試用例信息失敗,{}'.format(e))
with allure.step("請(qǐng)求接口:%s,請(qǐng)求地址:%s,請(qǐng)求方法:%s,請(qǐng)求頭:%s,請(qǐng)求Cookies:%s" % (
get_name, get_url, get_method, get_headers, get_cookies)):
allure.attach("接口用例描述:", "{0}".format(get_case_name))
allure.attach("接口用例請(qǐng)求參數(shù):", "{0}".format(get_case_params))
logger.info(
'請(qǐng)求接口名:%r,請(qǐng)求地址:%r,請(qǐng)求方法:%r,請(qǐng)求頭:%r,請(qǐng)求Cookies:%r' %\
(get_name, get_url, get_method, get_headers, get_cookies))
logger.info('請(qǐng)求接口名:%r,請(qǐng)求接口用例名:%r,接口用例請(qǐng)求參數(shù):%r' %\
(get_name, get_case_name, get_case_params))
try:
response_data = baseRequest.run_main(get_method, get_url, get_case_params, get_headers)
except Exception as e:
logger.exception('用例請(qǐng)求返回失敗,{}'.format(e))
logger.info('請(qǐng)求接口名:%r,請(qǐng)求接口用例名:%r,返回參數(shù):%r' % (get_name, get_case_name, response_data.json()))
return response_data
4、Excel數(shù)據(jù)處理-測(cè)試用例
測(cè)試用例中維護(hù)在Excel文件中,類中定義如何獲取Excel中的相關(guān)數(shù)據(jù)(如獲取某個(gè)單元格的內(nèi)容,獲取單元格的行數(shù),以及將數(shù)據(jù)寫入Excel中等操作)。
handle_exceldata.py部分源碼
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 = ''
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)
5、JSON數(shù)據(jù)處理-測(cè)試用例
{
"config":{
"name":"post接口名",
"url":"/langdetect",
"method":"POST",
"headers":{
"Content-Type":"application/json"
},
"cookies":{
}
},
"testcase":[
{
"name":"測(cè)試用例1",
"params":{
"query":"測(cè)試"
},
"validate":[
{
"check":"status_code",
"comparator":"eq",
"expect":"200"
}
]
},
{
"name":"測(cè)試用例2",
"params":{
"query":"python"
},
"validate":[
{
"check":"msg",
"comparator":"eq",
"expect":"success"
}
]
}
]
}
獲取Json文件中里具體字段的值。
handle.json.py部分源碼
class HandleJson:
# 讀取json文件
def load_json(self, file_name):
if file_name == None:
file_path = ""
else:
file_path = file_name
try:
with open(file_path, encoding='UTF-8') as f:
data = json.load(f)
return data
except Exception:
print("未找到j(luò)son文件")
return {}
# 讀取json文件里具體的字段值
def getJson_value(self, key, file_name):
if file_name == None:
return ""
jsonData = self.load_json(file_name)
if key == None:
getJsonValue = ""
else:
getJsonValue = jsonData.get(key)
return getJsonValue
基類封裝
接口支持Get、Post請(qǐng)求,調(diào)用requests請(qǐng)求來實(shí)現(xiàn)接口的調(diào)用與返回。接口參數(shù)包括,接口地址、接口請(qǐng)求參數(shù)、cookie參數(shù)、header參數(shù)。
class BaseRequest:
def send_get(self, url, data, header=None, cookie=None):
"""
Requests發(fā)送Get請(qǐng)求
:param url:請(qǐng)求地址
:param data:Get請(qǐng)求參數(shù)
:param cookie:cookie參數(shù)
:param header:header參數(shù)
"""
response = requests.get(url=url, params=data, cookies=cookie, headers=header)
return response
def send_post(self, url, data, header=None, cookie=None):
"""
Requests發(fā)送Post請(qǐng)求
:param url:請(qǐng)求地址
:param data:Post請(qǐng)求參數(shù)
:param data:Post請(qǐng)求參數(shù)
:param cookie:cookie參數(shù)
:param header:header參數(shù)
"""
response = requests.post(url=url, json=data, cookies=cookie, headers=header)
return response
# 主函數(shù)調(diào)用
def run_main(self, method, url, data, header, cookie=None):
try:
result = ''
if method.upper() == 'GET':
result = self.send_get(url, data, header, cookie)
elif method.upper() == 'POST':
result = self.send_post(url, data, header, cookie)
return result
except Exception as e:
logger.exception('請(qǐng)求主函數(shù)調(diào)用失?。簕}'.format(e))
測(cè)試用例編寫
引用Pytest來進(jìn)行接口的單元測(cè)試,通過JSON中多個(gè)測(cè)試用例來做為參數(shù)化數(shù)據(jù)驅(qū)動(dòng)。結(jié)合Allure制定相應(yīng)接口的測(cè)試報(bào)告。在接口返回?cái)嘌灾?,我們先進(jìn)行該接口的契約測(cè)試,
我們采用的是Pactverity的全量契約校驗(yàn)測(cè)試。當(dāng)契約測(cè)試通過時(shí),我們?cè)龠M(jìn)行返回參數(shù)的相關(guān)校驗(yàn)測(cè)試。
test_getRequestJson.py部分源碼
@allure.feature('測(cè)試GET請(qǐng)求模塊')
class TestRequestOne():
@allure.title('測(cè)試標(biāo)題')
@allure.testcase('測(cè)試地址:https://www.imooc.com')
@pytest.mark.parametrize('case_data', testCaseData['testcase'])
def test_requestOne(self, case_data):
try:
api_response = apiRequest.api_request(baseurl, testCaseData, case_data)
api_response_data = api_response.json()
# pactverity——全量契約校驗(yàn)
config_contract_format = Like({
"msg": "成功",
"result": 0,
"data": EachLike({
"word": Like("testng")
})
})
mPactVerify = PactVerify(config_contract_format)
try:
mPactVerify.verify(api_response_data)
logger.info(
'verify_result:{},verify_info:{}'.format(mPactVerify.verify_result, mPactVerify.verify_info))
assert mPactVerify.verify_result == True
except Exception:
err_msg = '契約校驗(yàn)錯(cuò)誤'
logger.exception('測(cè)試用例契約校驗(yàn)失敗,verify_result:{},verify_info:{}'.format(mPactVerify.verify_result,
mPactVerify.verify_info))
try:
for case_validate in case_data['validate']:
logger.info('斷言期望相關(guān)參數(shù):check:{},comparator:{},expect:{}'.format(case_validate['check'],
case_validate['comparator'],
case_validate['expect']))
comparatorsTest.comparators_Assert(api_response, case_validate['check'],
case_validate['comparator'], case_validate['expect'])
logger.info('測(cè)試用例斷言成功')
except Exception as e:
logger.exception('測(cè)試用例斷言失敗')
except Exception as e:
logger.exception('測(cè)試用例請(qǐng)求失敗,原因:{}'.format(e))
主運(yùn)行:
運(yùn)用Pytest和Allure的特性,命令行運(yùn)行測(cè)試用例文件夾,并生成對(duì)應(yīng)的allure測(cè)試報(bào)告。
if __name__ == "__main__":
pytest.main(['-s', '-v', 'test_case/testRequest/', '-q', '--alluredir', 'reports'])
Alluer2 測(cè)試報(bào)告
當(dāng)我們運(yùn)行主函數(shù)時(shí),并生成對(duì)應(yīng)的測(cè)試用例報(bào)告時(shí),我們可以看到在該文件夾中會(huì)生成對(duì)應(yīng)的json文件的測(cè)試報(bào)告。
reports是json格式測(cè)試報(bào)告存放的目錄位置,allure_reports是html測(cè)試報(bào)告文件生成的目錄位置。allure命令如下。
allure generate reports -o allure_result/
項(xiàng)目根目錄下的allure_reports文件,存放的是allure生成的測(cè)試報(bào)告??煽闯鑫募掠幸粋€(gè)HTML文件,可通過Python的編輯器Pycharm來打開該HTML文件(測(cè)試報(bào)告),或可通過allure命令來打開該HTML。
下面是我整理的2023年最全的軟件測(cè)試工程師學(xué)習(xí)知識(shí)架構(gòu)體系圖 |
一、Python編程入門到精通
二、接口自動(dòng)化項(xiàng)目實(shí)戰(zhàn)
三、Web自動(dòng)化項(xiàng)目實(shí)戰(zhàn)
四、App自動(dòng)化項(xiàng)目實(shí)戰(zhàn)
五、一線大廠簡(jiǎn)歷
六、測(cè)試開發(fā)DevOps體系
七、常用自動(dòng)化測(cè)試工具
八、JMeter性能測(cè)試
九、總結(jié)(尾部小驚喜)
勇攀高峰,永不言棄,奮斗的旅程猶如綻放的花朵;跨越征程,超越極限,拼搏的力量鑄就輝煌的人生。相信自己的潛能,釋放內(nèi)心的火焰,用汗水和努力砥礪出屬于自己的輝煌之路。
披荊斬棘,破浪前行,奮斗是人生最壯麗的交響樂;勇往直前,超越極限,夢(mèng)想是心靈最美的翅膀。相信堅(jiān)持,追逐光芒,奮斗點(diǎn)亮未來的星空,譜寫屬于自己的輝煌篇章。文章來源:http://www.zghlxwxcb.cn/news/detail-624904.html
不畏艱辛,奮斗向前,執(zhí)著追尋心中的星辰大海;擁抱挑戰(zhàn),超越極限,每一次努力都是成長(zhǎng)的腳印。相信自己的力量,燃燒激情,創(chuàng)造出屬于自己的輝煌人生。文章來源地址http://www.zghlxwxcb.cn/news/detail-624904.html
到了這里,關(guān)于從0到1框架搭建,Python+Pytest+Allure+Git+Jenkins接口自動(dòng)化框架(超細(xì)整理)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!