手把手帶你打造一個(gè)Pytest數(shù)據(jù)分離測試框架
數(shù)據(jù)分離測試框架是一種測試框架設(shè)計(jì)模式,旨在將測試數(shù)據(jù)與測試邏輯分離,以提高測試用例的可維護(hù)性、可讀性和復(fù)用性。這種框架通常用于自動化測試,特別是在接口測試、UI 測試和集成測試中非常有用。
在數(shù)據(jù)分離測試框架中,測試數(shù)據(jù)通常存儲在外部文件(如 Excel、CSV、JSON 等)中,而測試邏輯則編寫在測試用例中。通過將測試數(shù)據(jù)與測試邏輯分開,可以實(shí)現(xiàn)以下優(yōu)勢:
易維護(hù)性:測試數(shù)據(jù)的變化不會影響測試邏輯,反之亦然。當(dāng)測試數(shù)據(jù)需要更新時(shí),只需修改數(shù)據(jù)文件而不必修改測試用例代碼。
可讀性:測試用例更加清晰易讀,因?yàn)閿?shù)據(jù)被獨(dú)立出來并以結(jié)構(gòu)化的方式存儲在外部文件中。
復(fù)用性:可以重復(fù)使用相同的測試邏輯,只需提供不同的測試數(shù)據(jù)即可運(yùn)行多個(gè)測試場景。
擴(kuò)展性:隨著測試需求的增加,可以很容易地添加新的測試數(shù)據(jù)文件,而無需改動現(xiàn)有的測試用例。
靈活性:可以使用不同類型的數(shù)據(jù)文件進(jìn)行數(shù)據(jù)分離,根據(jù)具體需求選擇最適合的數(shù)據(jù)存儲格式。
數(shù)據(jù)分離測試框架通常包括數(shù)據(jù)讀取工具、測試邏輯編寫、日志記錄和報(bào)告生成等功能。通過有效地組織和管理測試數(shù)據(jù),測試團(tuán)隊(duì)可以更高效地執(zhí)行測試,并快速準(zhǔn)確地識別潛在的問題。
開發(fā)一個(gè)復(fù)雜的數(shù)據(jù)驅(qū)動測試框架涉及到多個(gè)方面,包括數(shù)據(jù)讀取、日志記錄、郵件發(fā)送、配置文件使用以及清晰的代碼目錄結(jié)構(gòu)等。讓我們一步一步來完成這個(gè)任務(wù)。
1.創(chuàng)建項(xiàng)目目錄結(jié)構(gòu)
首先,創(chuàng)建一個(gè)新的項(xiàng)目目錄結(jié)構(gòu),并包含以下子目錄和文件:
data_driven_testing_framework/
├── configs/
│ └── config.ini
├── data/
│ └── test_data.xlsx
├── logs/
├── tests/
│ ├── __init__.py
│ └── test_sample.py
├── utils/
│ ├── __init__.py
│ ├── excel_reader.py
│ ├── logger.py
│ ├── mailer.py
└── pytest.ini
2.安裝所需庫
確保安裝所需的庫:
pip install pytest openpyxl configparser logging yagmail
3.編寫配置文件
在 configs/config.ini 中定義配置參數(shù):
[EMAIL] email_address = your_email@example.com email_password = your_email_password [LOGGING] log_file = logs/test.log
4. 編寫工具類
在 utils/excel_reader.py 中編寫 Excel 數(shù)據(jù)讀取工具類:
import openpyxl
class ExcelReader:
@staticmethod
def read_data(file_path):
wb = openpyxl.load_workbook(file_path)
sheet = wb.active
data = []
for row in sheet.iter_rows(min_row=2, values_only=True):
data.append(row)
return data
在 utils/logger.py 中編寫日志記錄工具類:
import logging
import configparser
config = configparser.ConfigParser()
config.read('configs/config.ini')
log_file = config['LOGGING']['log_file']
logging.basicConfig(filename=log_file, level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
在 utils/mailer.py 中編寫發(fā)送郵件工具類:
import yagmail
import configparser
config = configparser.ConfigParser()
config.read('configs/config.ini')
email_address = config['EMAIL']['email_address']
email_password = config['EMAIL']['email_password']
class Mailer:
@staticmethod
def send_email(subject, contents):
yag = yagmail.SMTP(email_address, email_password)
yag.send(to=email_address, subject=subject, contents=contents)
5.編寫測試用例
在 tests/test_sample.py 中編寫測試用例:
import pytest
from utils.excel_reader import ExcelReader
from utils.logger import logging
from utils.mailer import Mailer
test_data_file = 'data/test_data.xlsx'
@pytest.mark.parametrize("data", ExcelReader.read_data(test_data_file))
def test_data_driven(data):
logging.info(f"Running test with data: {data}")
# Your test logic here
assert True
def test_send_email():
Mailer.send_email("Test Email", "This is a test email sent from the data-driven testing framework")
6.運(yùn)行測試
現(xiàn)在你可以使用 Pytest 來運(yùn)行測試。在命令行中執(zhí)行以下命令:
pytest -v
7.實(shí)際使用示例
在接口測試中,你可以使用這個(gè)框架來執(zhí)行數(shù)據(jù)驅(qū)動測試。例如,你可以從 Excel 文件中讀取測試數(shù)據(jù),然后在測試用例中使用這些數(shù)據(jù)來調(diào)用接口,并斷言結(jié)果是否符合預(yù)期。
7.1準(zhǔn)備測試數(shù)據(jù)
首先,準(zhǔn)備一個(gè) Excel 文件,例如 test_data.xlsx,其中包含了不同的測試數(shù)據(jù)。假設(shè)我們要測試一個(gè)登錄接口,測試數(shù)據(jù)文件內(nèi)容如下:
| Username | Password |
|---|---|
| user1 | password1 |
| user2 | password2 |
| user3 | password3 |
7.2編寫測試用例
在 tests/test_sample.py 中編寫測試用例,使用數(shù)據(jù)驅(qū)動的方式來運(yùn)行測試:
import pytest
from utils.excel_reader import ExcelReader
from utils.logger import logging
from utils.mailer import Mailer
from your_api_client_module import APIClient # 導(dǎo)入你的 API 客戶端模塊
test_data_file = 'data/test_data.xlsx'
@pytest.mark.parametrize("username, password", ExcelReader.read_data(test_data_file))
def test_login_api(username, password):
logging.info(f"Running test with data: Username - {username}, Password - {password}")
# 使用測試數(shù)據(jù)調(diào)用登錄接口
api_client = APIClient()
response = api_client.login(username, password)
# 斷言登錄結(jié)果是否符合預(yù)期
assert response.status_code == 200
assert 'token' in response.json()
def test_send_email():
Mailer.send_email("Test Email", "This is a test email sent from the data-driven testing framework")
在上面的示例中,我們使用 @pytest.mark.parametrize 注解來指定參數(shù)化測試數(shù)據(jù),并在測試用例中使用這些數(shù)據(jù)來調(diào)用登錄接口。通過這種方式,你可以輕松地對不同的輸入數(shù)據(jù)進(jìn)行測試,而無需為每組數(shù)據(jù)編寫單獨(dú)的測試用例。
到此這篇關(guān)于手把手帶你打造一個(gè)Pytest數(shù)據(jù)分離測試框架的文章就介紹到這了,更多相關(guān)Pytest數(shù)據(jù)分離測試內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python Autopep8實(shí)現(xiàn)按PEP8風(fēng)格自動排版Python代碼
這篇文章主要介紹了python Autopep8實(shí)現(xiàn)按PEP8風(fēng)格自動排版Python代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03
Python使用python-pptx自動化操作和生成PPT
這篇文章主要為大家詳細(xì)介紹了如何使用python-pptx庫實(shí)現(xiàn)PPT自動化,并提供實(shí)用的代碼示例和應(yīng)用場景,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2025-08-08
如何實(shí)現(xiàn)在遠(yuǎn)程linux服務(wù)器上運(yùn)行python代碼
這篇文章主要介紹了如何實(shí)現(xiàn)在遠(yuǎn)程linux服務(wù)器上運(yùn)行python代碼問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-12-12
pandas數(shù)據(jù)合并與重塑之merge詳解
這篇文章主要介紹了pandas數(shù)據(jù)合并與重塑之merge,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-02-02
一文詳解如何使用Python構(gòu)建一個(gè)可維護(hù)的項(xiàng)目結(jié)構(gòu)
在Python開發(fā)旅程中,很多開發(fā)者最初都是從編寫簡單的腳本開始的,本文將深入探討如何將一個(gè)簡單的Python腳本重構(gòu)為一個(gè)結(jié)構(gòu)良好,可維護(hù)的Python項(xiàng)目,希望對大家有所幫助2025-11-11
解析Pytorch中的torch.gather()函數(shù)
本文給大家介紹了Pytorch中的torch.gather()函數(shù),通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2021-11-11
Pytorch中torch.cat()函數(shù)舉例解析
一般torch.cat()是為了把多個(gè)tensor進(jìn)行拼接而存在的,下面這篇文章主要給大家介紹了關(guān)于Pytorch中torch.cat()函數(shù)舉例解析的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-12-12

