2024軟件測試面試刷題,這個小程序(永久刷題),靠它快速找到工作了?。ㄋ㈩}APP的天花板)
最近在這整理知識,發(fā)現(xiàn)在pytest的知識文檔缺少系統(tǒng)性,這里整理一下,方便后續(xù)回憶。
在python中,大家比較熟悉的兩個框架是unittest和pytest:
Unittest是Python標(biāo)準(zhǔn)庫中自帶的單元測試框架,Unittest有時候也被稱為PyUnit,就像JUnit是Java語言的標(biāo)準(zhǔn)單元測試框架一樣,Unittest則是Python語言的標(biāo)準(zhǔn)單元測試框架。
Pytest是Python的另一個第三方單元測試庫。它的目的是讓單元測試變得更容易,并且也能擴(kuò)展到支持應(yīng)用層面復(fù)雜的功能測試。
兩者之間的區(qū)別如下:
這里試用的pytest框架,加上request來實現(xiàn)接口自動化的測試,整個框架考慮到使用數(shù)據(jù)驅(qū)動的方式,將數(shù)據(jù)維護(hù)在Excel文檔中。
1、下載安裝allure
下載地址:
https://github.com/allure-framework/allure2/releases
https://repo.maven.apache.org/maven2/io/qameta/allure/allure-commandline/
選擇需要的版本下載,這里我下載的是2.13.2版本
下載好后,解壓到你需要存放的路目錄,并配置環(huán)境變量
檢查是否配置成功,執(zhí)行cmd,輸入命令 allure,出現(xiàn)如下圖,則表示安裝成功
2、下載安裝python
下載地址https://www.python.org/
下載好后,安裝并配置環(huán)境變量,具體流程可以網(wǎng)絡(luò)查找
3、python安裝依賴包
cmd命令執(zhí)行,也可以通過項目中的requirements.txt來安裝,安裝步驟后面再說
pip3 install allure-pytest
pip3 install pytest
pip3 install pytest_html
pip3 install request
4、下載并安裝pycharm工具
查看網(wǎng)絡(luò)教程
5、在pycharm,新建項目及編碼
項目目錄如圖:
base:存放一些最底層的方法封裝,協(xié)議,請求發(fā)送等。
common:存放一些公共方法。
config:存放配置文件。
testData:存放測試數(shù)據(jù)。
log:存放日志。
report:存放報告。
testCase:存放用例。
utils:存放公共類。
readme:用于說明文檔。
requirements.txt: 用于記錄所有依賴包極其版本號,便于環(huán)境部署,可以通過pip命令自動生成和安裝
這里采用數(shù)據(jù)驅(qū)動的方式,數(shù)據(jù)通過讀取excel文件來執(zhí)行測試,所以這里需要封裝讀取excel的方法,使用xlrd來操作讀取
# operationExcel.py
import json
from common.contentsManage import filePath
import xlrd, xlwt
class OperationExcel:
# 獲取shell表
def getSheet(self, index=0):
book = xlrd.open_workbook(filePath())
return book.sheet_by_index(index) #根據(jù)索引獲取到sheet表
# 以列表形式讀取出所有數(shù)據(jù)
def getExcelData(self, index=0):
data = []
sheet = self.getSheet(index=index)
title = sheet.row_values(0) # (0)獲取第一行也就是表頭
for row in range(1, sheet.nrows): # 從第二行開始獲取
row_value = sheet.row_values(row)
data.append(dict(zip(title, row_value))) # 將讀取出第一條用例作為一個字典存放近列表
return data
# 對excel表頭進(jìn)行全局變量定義
class ExcelVarles:
case_Id = "用例ID"
case_module="用例模塊"
case_name="用例名稱"
case_server="用例地址"
case_url="請求地址"
case_method="請求方法"
case_type="請求類型"
case_data="請求參數(shù)"
case_headers="請求頭"
case_preposition="前置條件"
case_isRun = "是否執(zhí)行"
case_code = "狀態(tài)碼"
case_result = "期望結(jié)果"
if __name__ == "__main__":
opExcel = OperationExcel()
# opExcel.getSheet()
# print(opExcel.getExcelData())
opExcel.writeExcelData(1, 7, f"test{2}")
excel 文件內(nèi)容如圖
封裝用例
# test_api_all.py
# 參數(shù)化運用所有用例
import json
import pytest
from utils.operationExcel import OperationExcel, ExcelVarles
from base.method import ApiRequest
from common.log import logger
opExcel = OperationExcel()
apiRequest = ApiRequest()
@pytest.mark.parametrize('data', opExcel.getExcelData()) # 裝飾器進(jìn)行封裝用例
def test_api(data, login_token=None):
if data[ExcelVarles.case_isRun] == "N" :
logger.info("跳過執(zhí)行用例")
return
# 請求頭作為空處理并添加token
headers = data[ExcelVarles.case_headers]
if len(str(headers).split()) == 0:
pass
elif len(str(headers).split()) >= 0:
headers = json.loads(headers) # 轉(zhuǎn)換為字典
# headers['Authorization'] = login_token # 獲取登錄返回的token并添加到讀取出來的headers里面
headers = headers
# 對請求參數(shù)做為空處理
params = data[ExcelVarles.case_data]
if len(str(params).split()) == 0:
pass
elif len(str(params).split()) == 0:
params = params
url = data[ExcelVarles.case_server] + data[ExcelVarles.case_url] + "?" + params
r = apiRequest.all_method( data[ExcelVarles.case_method] ,url, headers=headers)
logger.info(f"響應(yīng)結(jié)果{r}")
responseResult = json.loads(r)
case_result_assert(data[ExcelVarles.case_code], responseResult['code'])
# 斷言封裝
def case_result_assert(expectedResult, actualReuls) :
'''
斷言封裝
:param expectedResult: 預(yù)期結(jié)果
:param actualReuls: 實際結(jié)果
:return:
'''
assert expectedResult == actualReuls # 狀態(tài)碼
封裝日志文件
# log.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
import logging
import time
import os
from common.contentsManage import logDir
# BASE_PATH = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
# # 定義日志文件路徑
# LOG_PATH = os.path.join(BASE_PATH, "log")
# if not os.path.exists(LOG_PATH):
# os.mkdir(LOG_PATH)
# 方法1
# 封裝自己的logging
class MyLogger:
def __init__(self):
self._logName = os.path.join(logDir(), "{}.log".format(time.strftime("%Y%m%d")))
self._logger = logging.getLogger("logger")
self._logger.setLevel(logging.DEBUG)
self._formatter = logging.Formatter('[%(asctime)s][%(filename)s %(lineno)d][%(levelname)s]:%(message)s')
self._streamHandler = logging.StreamHandler()
self._fileHandler = logging.FileHandler(self._logName, mode='a', encoding="utf-8")
self._streamHandler.setFormatter(self._formatter)
self._fileHandler.setFormatter(self._formatter)
self._logger.addHandler(self._streamHandler)
self._logger.addHandler(self._fileHandler)
# 獲取logger日志記錄器
def get_logger(self):
return self._logger
logger = MyLogger().get_logger()
封裝請求方法
# method.py
import json
import requests
from common.log import logger
from utils.commonUtils import isJson
class ApiRequest(object):
# ---- 第一種請求方式封裝requests庫,調(diào)用可根據(jù)實際情況傳參 ----
# def send_requests(self, method, url, data=None, params=None, headers=None,
# cookies=None,json=None,files=None,auth=None,timeout=None,
# proxies=None,verify=None,cert=None):
# self.res = requestes.request(method=method, url= url, headers=headers,data=data,
# params=params, cookies=cookies,json = json,files=files,
# auth=auth, timeout= timeout, proxies=proxies,verify=verify,
# cert=cert)
# return self.res
# 第二種封裝方法
def get(self, url, data=None, headers=None, payload=None):
if headers is not None:
res = requests.get(url=url, data=data,headers=headers)
else:
res = requests.get(url=url, data=data)
return res
def post(self, url, data, headers, payload:dict, files=None):
if headers is not None:
res = requests.post(url=url, data=data, headers=headers)
else :
res = requests.post(url=url, data=data)
if str(res) == "<Response [200]>" :
return res.json()
else :
return res.text
def put(self,url,data,headers, payload:dict, files=None):
if headers is not None :
res = requests.put(url=url,data=data,headers=headers)
else:
res = requests.put(url=url,data=data)
return res
def delete(self,url,data,headers, payload:dict):
if headers is not None :
res = requests.delete(url=url,data=data,headers=headers)
else:
res = requests.delete(url=url,data=data)
return res
def all_method(self, method, url, data=None, headers=None, payload=None, files=None):
logger.info(f"請求方法是{method}, 請求地址{url}")
if headers == None:
headers = {}
if method.upper()=='GET':
res = self.get(url,data,headers, payload)
elif method.upper()=='POST':
res = self.post(url, data, headers, payload, files)
elif method.upper() == 'PUT':
res = self.put(url, data, headers, payload, files)
elif method.upper() == 'DELETE':
res = self.delete(url, data, headers, payload)
else :
res = f'請求{method}方式不支持,或者不正確'
return json.dumps(res, ensure_ascii=False, indent=4, sort_keys=True, separators=(',',':'))
運行
# run.py
import shutil
import pytest
import os
from common.log import logger
import subprocess # 通過標(biāo)準(zhǔn)庫中的subprocess包來fork一個子進(jìn)程,并運行一個外部的程序
from common.contentsManage import htmlDir, resultDir
if __name__ == '__main__':
htmlPath = htmlDir()
resultPath = resultDir()
if os.path.exists(resultPath) and os.path.isdir(resultPath):
logger.info("清理上一次執(zhí)行的結(jié)果")
shutil.rmtree(resultPath, True)
logger.info("開始測試")
pytest.main(["-s", "-v", "--alluredir", resultPath]) #運行輸出并在resport/result目錄下生成json文件
logger.info("結(jié)束測試")
# 如果是代碼單獨執(zhí)行,需要立馬看到報告,可以執(zhí)行下面語句,如果配合Jenkins使用,則可以不需要執(zhí)行,Jenkins自帶的插件allure會操作
# logger.info("生成報告")
# subprocess.call('allure generate ' + resultPath + ' -o '+ htmlPath +' --clean', shell=True) # 讀取json文件并生成html報告,--clean諾目錄存在則先清楚
# logger.info("查看報告")
# subprocess.call('allure open -h 127.0.0.1 -p 9999 '+htmlPath+'', shell=True) #生成一個本地的服務(wù)并自動打開html報告
依賴包安裝,可以執(zhí)行命令 pip3 install -r requirements.txt,來安裝
# requirements.txt
pytest==7.4.3
pytest-html==4.1.1
pytest-xdist==3.5.0
pytest-ordering==0.6
pytest-rerunfailures==13.0
allure-pytest==2.13.2
xlrd==1.2.0
requests==2.31.0
至此,項目的代碼框架就基本結(jié)束了
6、安裝并配置Jenkins
Jenkins的安裝,看你需要在Windows還是Linux下安裝,具體教程可以網(wǎng)絡(luò)查找
Jenkins安裝allure插件
Jenkins安裝并登錄后,可以創(chuàng)建任務(wù)
添加構(gòu)建步驟,根據(jù)你安裝環(huán)境的不同,選擇不同的構(gòu)建
添加構(gòu)建后操作,選擇 allure Report
配置代碼執(zhí)行的結(jié)果地址
運行測試后,可以在任務(wù)中查看allure生成的報告
至此,jenkins+python+pytest+requests+allure的接口自動化測試就記錄到這里,剛興趣的可以去看看pytest的官方文檔,了解更多知識。
行動吧,在路上總比一直觀望的要好,未來的你肯定會感謝現(xiàn)在拼搏的自己!如果想學(xué)習(xí)提升找不到資料,沒人答疑解惑時,請及時加入群: 786229024,里面有各種測試開發(fā)資料和技術(shù)可以一起交流哦。
最后: 下方這份完整的軟件測試視頻教程已經(jīng)整理上傳完成,需要的朋友們可以自行領(lǐng)取 【保證100%免費】
文章來源:http://www.zghlxwxcb.cn/news/detail-790312.html
軟件測試面試文檔
我們學(xué)習(xí)必然是為了找到高薪的工作,下面這些面試題是來自阿里、騰訊、字節(jié)等一線互聯(lián)網(wǎng)大廠最新的面試資料,并且有字節(jié)大佬給出了權(quán)威的解答,刷完這一套面試資料相信大家都能找到滿意的工作。文章來源地址http://www.zghlxwxcb.cn/news/detail-790312.html
到了這里,關(guān)于測開新手:pytest+requests+allure自動化測試接入Jenkins學(xué)習(xí)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!