前言
平常在做功能測試的時候,經常會遇到某個模塊不穩定,偶然會出現一些bug,對於這種問題我們會針對此用例反復執行多次,最終復現出問題來。
自動化運行用例時候,也會出現偶然的bug,可以針對單個用例,或者針對某個模塊的用例重復執行多次。
pytest-repeat
pytest-repeat是pytest的一個插件,用於重復執行單個用例,或多個測試用例,並指定重復次數,pytest-repeat支持的版本:
- python 2.7,3.4+ 或 PyPy
- py.test 2.8或更高
使用pip 安裝pytest-repeat
使用--count命令行選項指定要運行測試用例和測試次數
py.test --count=10 腳本名.py
重復執行--count
運行以下代碼,項目結果如下:
代碼參考:
#web_item_py/conftest.py # coding:utf-8 import pytest @pytest.fixture(scope="session") def begin(): print("\n打開首頁") #web_item_py/qq/conftest.py # coding:utf-8 import pytest @pytest.fixture(scope="session") def open_baidu(): print("打開百度頁面_session") #web_item_py/qq/test_1_qq.py # coding:utf-8 import pytest def test_q1(begin,open_baidu): print("測試用例test_q1") assert 1 def test_q2(begin,open_baidu): print("測試用例test_q2") assert 1 if __name__=="__main__": pytest.main(["-s","test_1_QQ.py"]) #web_item_py/qq/test_q2.py # coding:utf-8 import pytest def test_q8(begin,open_baidu): print("測試用例test_q8") assert 1 def test_q9(begin,open_baidu): print("測試用例test_q9") assert 1 if __name__=="__main__": pytest.main(["-s","test_q2.py"])
cmd到相應腳本目錄后,不帶--count參數只會執行一次
加上參數--count=5,用例會重復執行5次;
pytest test_q2.py -s --count=5
從運行的用例結果看,是先重復5次test_q8,再重復5次test_q9,有時候我們希望執行的順序是test_q8,test_q9按這樣順序重復五次,接下來就用到一個參數--repeat-scope
--repeat-scope
--repeat-scope類似於pytest fixture的scope參數,--repeat-scope也可以設置參數:session,module,class或者function(默認值)
- function(默認)范圍針對每個用例重復執行,再執行下一個用例
- class 以class為用例集合單位,重復執行class里面的用例,在執行下一個
- module 以模塊為單位,重復執行模塊里面的用例,再執行下一個
- session 重復整個測試會話,即所有收集的測試執行一次,然后所有這些測試再次執行等等
使用--repeat-scope=session重復執行整個會話用例
pytest test_q2.py -s --count=5 --repeat-scope=session
@pytest.mark.repeat(count)
如果要在代碼中標記要重復多次的測試,可以使用@pytest.mark.repeat(count)裝飾器
#web_item_py/qq/test_q2.py # coding:utf-8 import pytest @pytest.mark.repeat(5) def test_q8(begin,open_baidu): print("測試用例test_q8") assert 1 def test_q9(begin,open_baidu): print("測試用例test_q9") assert 1 if __name__=="__main__": pytest.main(["-s","test_q2.py"])
這樣執行用例時候,就不用帶上--count參數,只針對test_q8重復執行5次
這樣執行時,再加上--count=3,只對無count裝飾器的重復3次。
重復測試直至失敗
如果您正在嘗試診斷間歇性故障,那么一遍又一遍地運行相同的測試直至失敗是有用的。您可以將pytest的-x選項與pytest-repeat結合使用,以強制測試運行器在第一次失敗時停止。例如:
py.test --count=1000 -x test_q2.py 或 pytest --count=1000 -x test_q2.py
這樣嘗試運行test_q2.py 1000次,但一旦發生故障就會停止
UnitTest樣式測試
不幸的是,此插件不支持unittest框架的用例,pytest-repeat無法使用unittest.TestCase測試類。無論如何,這些測試將始終運行一次--count,並顯示警告
更多資料參考【官方文檔:https://pypi.org/project/pytest-repeat/】