1. 程式人生 > >unittest設定用例執行超時時間

unittest設定用例執行超時時間

通過python自帶的unittest框架執行測試套的時候,如果其中一個測試用例執行出問題,可能會無限迴圈等待或者等待時間超長,這個時候如果能設定超時時間,那麼就可以暫時跳過這個錯誤用例,繼續執行後續的用例。  對於這個問題,除了在用例中設定執行的時間,還可以通過裝飾器來解決。

import unittest
import timeout_decorator
import time


class TimeOut(unittest.TestCase):
    def setUp(self):
        pass

    @timeout_decorator.timeout(seconds=5)
    def test(self):
        for i in range(0, 40):
            print i
            time.sleep(1)

    def tearDown(self):
        pass


if __name__ == '__main__':
    unittest.main()

從執行的結果看,執行到第六次迴圈的時候,因為超時用例執行失敗。原因:超時