pytest重複執行所有或指定測試用例(pytest-repeat外掛)
我們平時在做測試的時候經常會遇到網路抖動,導致測試用例執行失敗,重新執行後用例又執行成功了;有時候還會遇到功能不穩定,偶爾會出現bug,我們經常需要反覆多次的執行用例,從而來複現問題。pytest-repeat外掛就可以實現重複執行測試用例的功能。
pytest-repeat安裝
pip install pytest-repeat
使用方式
命令列使用--count引數來指定測試用例的執行次數。
pytest --count=5 test_file.py # --count=5表示重複執行5次
舉例:
# file_name: test_repeat.py importpytest 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 -x -v --count=20
命令列中輸入上述指令後,測試用以將重複執行20遍,但重複執行的過程中一旦遇到失敗用例就會停止執行。
去期待陌生,去擁抱驚喜。