淺談pytest中重試機(jī)制的多種方法
pytest 提供了多種重試機(jī)制來處理測(cè)試失敗的情況,以下是主要的實(shí)現(xiàn)方式及示例:
1. pytest-rerunfailures 插件(最常用)
這是 pytest 最流行的重試機(jī)制實(shí)現(xiàn)方式。
安裝
pip install pytest-rerunfailures
使用方式
命令行參數(shù)
pytest --reruns 3 # 對(duì)所有失敗測(cè)試重試3次 pytest --reruns 3 --reruns-delay 2 # 重試3次,每次間隔2秒
標(biāo)記特定測(cè)試
@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. 自定義重試機(jī)制
使用 pytest 鉤子
def pytest_runtest_makereport(item, call):
if call.excinfo is not None:
# 獲取重試次數(shù)配置
reruns = getattr(item, "execution_count", 1)
if reruns > 1:
# 實(shí)現(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è)置重試次數(shù)?:通常2-3次足夠,過多會(huì)掩蓋真正問題
- ?添加延遲?:特別是對(duì)于網(wǎng)絡(luò)請(qǐng)求或資源競(jìng)爭(zhēng)的情況
- ?記錄重試信息?:使用
pytest -v查看哪些測(cè)試被重試了 - ?避免濫用?:重試機(jī)制不應(yīng)替代穩(wěn)定的測(cè)試代碼
- ?CI環(huán)境特殊處理?:在CI中可增加重試次數(shù)
# 示例CI配置 pytest --reruns 3 --reruns-delay 1 --junitxml=report.xml
到此這篇關(guān)于淺談pytest中重試機(jī)制的多種方法的文章就介紹到這了,更多相關(guān)pytest 重試機(jī)制內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于numpy中np.nonzero()函數(shù)用法的詳解
下面小編就為大家?guī)硪黄P(guān)于numpy中np.nonzero()函數(shù)用法的詳解。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-02-02
Python 內(nèi)置函數(shù)memoryview(obj)的具體用法
本篇文章主要介紹了Python 內(nèi)置函數(shù)memoryview(obj)的具體用法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-11-11
python list是否包含另一個(gè)list所有元素的實(shí)例
今天小編就為大家分享一篇python list是否包含另一個(gè)list所有元素的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-05-05
如何解決MNIST數(shù)據(jù)集下載速度較慢并失敗的問題
這篇文章主要介紹了如何解決MNIST數(shù)據(jù)集下載速度較慢并失敗的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06
python selenium登錄豆瓣網(wǎng)過程解析
這篇文章主要介紹了python selenium登錄豆瓣網(wǎng)過程解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-08-08

