我們平時在做測試的時候經常會遇到網絡抖動,導致測試用例執行失敗,重新之下用例又成功了;有時候還會遇到功能不穩定,偶爾會出現bug,我們經常需要反復多次的運行用例,從而來復現問題。pytest-repeat插件就可以實現重復運行測試用例的功能。
pytest-repeat安裝
pip install pytest-repeat
使用方式
命令行使用--count參數來指定測試用例的運行次數。
pytest --count=5 test_file.py # --count=5表示重復執行5次
舉例:
# file_name: test_repeat.py import pytest def test_01(): print("\n測試用例test_01") def test_02(): print("\n測試用例test_02") def test_03(): print("\n測試用例test_03") if __name__ == '__main__': pytest.main(['-s', 'test_repeat.py'])
命令行輸入指令:pytest --count=3 test_repeat.py -s -v,運行結果:

從結果中可以看到,每個測試用例被重復運行了三次。
通過指定--repeat-scope參數來控制重復范圍
從上面例子的運行結果中可以看到,首先重復運行了3次test_01,然后重復運行了3次test_02,最后重復運行了3次test_03。但是有的時候我們想按照執行順序為test_01,test_02,test_03這樣的順序來重復運行3次呢,這時候就需要用到另外一個參數了:--repeat-scope。
--repeat-scope與pytest的fixture的scope是類似的,--repeat-scope可設置的值為:module、class、session、function(默認)。
- module:以整個.py文件為單位,重復執行模塊里面的用例,然后再執行下一個(以.py文件為單位,執行一次.py,然后再執行一下.py);
- class:以class為單位,重復運行class中的用例,然后重復執行下一個(以class為單位,運行一次class,再運行一次class這樣);
- session:重復運行整個會話,所有測試用例運行一次,然后再所有測試用例運行一次;
- function(默認):針對每個用例重復運行,然后再運行下一次用例;
使用--repeat-scope=session重復運行整個會話,命令行輸入指令:pytest test_repeat.py -s -v --count=3 --repeat-scope=session,運行結果為:

從結果中可以看到,執行順序為:test_01、test_02、test_03;然后重復運行3次;
通過裝飾器@pytest.mark.repeat(count)指定某個用例重復執行
# file_name: test_repeat.py import pytest def test_01(): print("\n測試用例test_01") @pytest.mark.repeat(3) def test_02(): print("\n測試用例test_02") def test_03(): print("\n測試用例test_03") if __name__ == '__main__': pytest.main(['-s', 'test_repeat.py'])
命令行輸入指令:pytest test_repeat.py -s -v,運行結果:

從結果中可以看到只有被裝飾器@pytest.mark.repeat(3)標記的用例test_02被重復運行了3次。
重復運行用例直到遇到失敗用例就停止運行
通過pytest -x 和 pytest-repeat 的結合就能實現重復運行測試用例直到遇到第一次失敗用例就停止運行。
pytest test_file.py -s -v --count=20
命令行中輸入上述指令后,測試用以將重復運行20遍,但重復運行的過程中一旦遇到失敗用例就會停止運行。
