前言
在進行自動化測試的過程中,我們一定會有這樣的需求:希望失敗的用例可以自動重跑
在pytest中,提供了pytest-rerunfailures插件可以實現自動重跑的效果
插件安裝
pip命令安裝
pip install pytest-rerunfailures
使用實例
重新運行所有失敗的用例
如果需要把所有失敗的用例都重新運行,使用 --reruns 命令,並且制定要運行的最大次數
舉個🌰:
class TestDemo(object):
def setup_class(self):
print("執行setup_class")
def teardown_class(self):
print("執行teardown_class")
def test_case1(self):
print("執行測試用例1")
assert 1 + 1 == 3
def test_case2(self):
print("執行測試用例2")
assert 1 + 3 == 6
def test_case3(self):
print("執行測試用例3")
assert 1 + 3 == 4
使用命令pytest --reruns 2 -s
執行,結果如下
可以看到,case1和case2被重新執行了2次
如果希望在每次重新執行之間加上間隔時間,可以使用 --reruns-delay
命令行選項,指定下次測試重新開始之前等待的秒數
如 pytest --reruns 2 --reruns-delay 5 -s
,代表自動重跑2次,每次間隔5s
重新運行指定的用例
如果我們在測試時,只希望在某一條測試用例失敗后重新執行該如何處理呢
可以使用flaky裝飾器 @pytest.mark.flaky(reruns=, reruns_delay=)
參數說明
- reruns 重跑次數
- reruns_delay 重新運行的等待時間
舉個🌰
import pytest
@pytest.mark.flaky(reruns=2, reruns_delay=3)
def test_case1():
print("執行測試用例1")
assert 1 + 1 == 3
def test_case2():
print("執行測試用例2")
assert 1 + 3 == 6
def test_case3():
print("執行測試用例3")
assert 1 + 3 == 4
運行結果如下: