環境依賴
- Python 3.5, 最高 3.8, or PyPy3
- pytest 5.0或更高版本
插件安裝
pip3 install pytest-rerunfailures -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
參數解釋
命令行參數:--reruns n(重新運行次數),--reruns-delay m(等待運行秒數)
裝飾器參數:reruns=n(重新運行次數),reruns_delay=m(等待運行秒數)
重新運行所有失敗的用例
使用 --reruns 命令行選項,並指定要運行測試的最大次數:
pytest --reruns 5 -s
運行失敗的fixture或setup_class也將重新執行
重新運行的延時設置
要在兩次重試之間增加延遲時間,使用 --reruns-delay 命令行選項,指定下次測試重新開始之前等待的秒數
pytest --reruns 5 --reruns-delay 10 -s
重新運行指定的測試用例
添加flaky裝飾器 @pytest.mark.flaky(reruns=5) ,並指定最大重新運行次數,示例代碼如下:
# -*- coding: utf-8 -*-
# @Time : 2020/11/25 20:36
# @Author : longrong.lang
# @FileName: test_retry.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang
from collections import Counter
import random
import pytest
@pytest.mark.flaky(reruns=5)
def test_retry1():
n = random.randint(0, 9)
print(f"\n 輸出隨機數: {n} ")
assert n == 2
@pytest.mark.flaky(reruns=5)
def test_retry2():
assert random.choice([True, False, False])
執行結果:
對單個測試用例設置重新運行等待時間
示例代碼如下:
@pytest.mark.flaky(reruns=5,reruns_delay=2)
def test_retry1():
n = random.randint(0, 9)
print(f"\n 輸出隨機數: {n} ")
assert n == 2
運行結果:
注意事項
如果指定了用例的重新運行次數,則在命令行添加--reruns對這些用例是不會生效的
兼容性問題
- 不可以和fixture裝飾器一起使用: @pytest.fixture()
- 該插件與pytest-xdist的 --looponfail 標志不兼容
- 該插件與核心--pdb標志不兼容
系列參考文章:
https://www.cnblogs.com/poloyy/category/1690628.html