如果你還想從頭學起Pytest,可以看看這個系列的文章哦!
https://www.cnblogs.com/poloyy/category/1690628.html
環境前提
以下先決條件才能使用pytest-rerunfailures
- 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) ,並在測試失敗時自動重新運行,需要指定最大重新運行的次數
小栗子
import pytest @pytest.mark.flaky(reruns=5) def test_example(): import random assert random.choice([True, False, False])
執行結果
collecting ... collected 1 item 11_reruns.py::test_example RERUN [100%] 11_reruns.py::test_example PASSED [100%] ========================= 1 passed, 1 rerun in 0.05s ==========================
同樣的,這個也可以指定重新運行的等待時間
@pytest.mark.flaky(reruns=5, reruns_delay=2) def test_example(): import random assert random.choice([True, False, False])
注意事項
如果指定了用例的重新運行次數,則在命令行添加 --reruns 對這些用例是不會生效的
兼容性問題
- 不可以和fixture裝飾器一起使用: @pytest.fixture()
- 該插件與pytest-xdist的 --looponfail 標志不兼容
- 該插件與核心--pdb標志不兼容