一、腳本中設置超時退出
由於某些測試用例步驟長,執行時間比較久,為了防止程序長時間處於等待狀態,浪費寶貴時間。為此,我們可以設置一個超時時間,當測試在指定的時間長度內沒有完成(即使程序並沒有“僵死”,只是處理得比較慢),測試會被強行終止。再此,需要安裝一個插件pytest-timeout。如下:
pip install pytest-timeout
比如,下例中設計的用例超過2秒時,就不再等待,並停止執行。
#test_timeout.py
import time
import pytest
class TestMyCode:
@pytest.mark.timeout(4)
def test_timeout_001(self):
"""正常執行,並通過"""
time.sleep(3)
assert 1 == 1
@pytest.mark.timeout(2)
def test_timeout_002(self):
"""超時,強制報錯"""
time.sleep(3)
assert 1 == 1
def test_timeout_003(self):
"""正常執行,並通過"""
assert 1 == 1
if __name__ == '__main__':
pytest.main(["-s", "test_timeout.py"])
結果:

二、jenkins中設置超時退出
另外,在jenkins中也可以設置超時停止任務,如圖:

