淺談pytest中重試機制的多種方法
pytest 提供了多種重試機制來處理測試失敗的情況,以下是主要的實現(xiàn)方式及示例:
1. pytest-rerunfailures 插件(最常用)
這是 pytest 最流行的重試機制實現(xiàn)方式。
安裝
pip install pytest-rerunfailures
使用方式
命令行參數(shù)
pytest --reruns 3 # 對所有失敗測試重試3次 pytest --reruns 3 --reruns-delay 2 # 重試3次,每次間隔2秒
標記特定測試
@pytest.mark.flaky(reruns=3)
def test_example():
assert 1 + 1 == 2
@pytest.mark.flaky(reruns=3, reruns_delay=1)
def test_example_with_delay():
assert 2 * 2 == 4混合使用
pytest --reruns 1 --reruns-delay 1 -m flaky
2. pytest-retry 插件(更靈活)
安裝
pip install pytest-retry
使用方式
@pytest.mark.retry(tries=3, delay=1)
def test_retry_specific():
import random
assert random.choice([True, False])3. 自定義重試機制
使用 pytest 鉤子
def pytest_runtest_makereport(item, call):
if call.excinfo is not None:
# 獲取重試次數(shù)配置
reruns = getattr(item, "execution_count", 1)
if reruns > 1:
# 實現(xiàn)重試邏輯
pass使用裝飾器
def retry(times=3, delay=1):
def decorator(func):
def wrapper(*args, ?**kwargs):
for i in range(times):
try:
return func(*args, ?**kwargs)
except AssertionError as e:
if i == times - 1:
raise
time.sleep(delay)
return wrapper
return decorator
@retry(times=3, delay=0.5)
def test_custom_retry():
assert False4. 條件重試
結(jié)合 pytest-rerunfailures 的條件重試:
@pytest.mark.flaky(reruns=3, condition=os.getenv("CI") == "true")
def test_conditional_retry():
assert some_flaky_operation()最佳實踐建議
- ?合理設(shè)置重試次數(shù)?:通常2-3次足夠,過多會掩蓋真正問題
- ?添加延遲?:特別是對于網(wǎng)絡(luò)請求或資源競爭的情況
- ?記錄重試信息?:使用
pytest -v查看哪些測試被重試了 - ?避免濫用?:重試機制不應(yīng)替代穩(wěn)定的測試代碼
- ?CI環(huán)境特殊處理?:在CI中可增加重試次數(shù)
# 示例CI配置 pytest --reruns 3 --reruns-delay 1 --junitxml=report.xml
到此這篇關(guān)于淺談pytest中重試機制的多種方法的文章就介紹到這了,更多相關(guān)pytest 重試機制內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
django框架實現(xiàn)模板中獲取request 的各種信息示例
這篇文章主要介紹了django框架實現(xiàn)模板中獲取request 的各種信息,結(jié)合實例形式分析了Django框架模板直接獲取request信息的相關(guān)配置與操作技巧,需要的朋友可以參考下2019-07-07
python關(guān)于圖片和base64互轉(zhuǎn)的三種方式
無論使用cv2、PIL還是直接讀取圖片的方法進行圖片與Base64的轉(zhuǎn)換,核心步驟都涉及到二進制格式的轉(zhuǎn)換,每種方法的基本過程都是:Base64轉(zhuǎn)二進制,然后二進制轉(zhuǎn)圖片,或反向操作,這些方法均基于二進制與圖片轉(zhuǎn)換的基本原理2024-09-09
python飛機大戰(zhàn)pygame游戲框架搭建操作詳解
這篇文章主要介紹了python飛機大戰(zhàn)pygame游戲框架搭建操作,設(shè)計pygame模塊游戲創(chuàng)建、初始化、精靈組設(shè)置等相關(guān)操作技巧,需要的朋友可以參考下2019-12-12
關(guān)于Python正則表達式 findall函數(shù)問題詳解
在寫正則表達式的時候總會遇到不少的問題,本文講述了Python正則表達式中 findall()函數(shù)和多個表達式元組相遇的時候會出現(xiàn)的問題2018-03-03
python輸入整條數(shù)據(jù)分割存入數(shù)組的方法
今天小編就為大家分享一篇python輸入整條數(shù)據(jù)分割存入數(shù)組的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-11-11

