我在python上越來越好,但我想找到一種方法來證明一段代碼不在無限循環中。假設我有一個方法foo(),它有一個無限循環,並且每次嘗試都會減少參數。如果循環在嘗試達到零時發生,我很好,但如果我在代碼中留下了一個錯誤,它將永遠循環。例如,假設我意外遞增而不是遞減,單元測試有沒有辦法檢測無限循環並且通過測試?類似於處理器上的看門狗,可以檢測進程是否佔用了所有CPU週期。見下面的代碼:證明代碼的單元測試避免了無限循環
# Given the following set of methods
def foo(attempts):
while(attempts >= 0)
attempts += 1 # OH OH!! ACCIDENTAL INFINITE LOOP!!!!
# Keep doing work until attempts reaches zero (or so was expected...)
return True # return true once broken out of the loop
# Here comes the Unit test
class FooTestCase(unittest.TestCase):
def test_foo(self):
self.assertTrue(foo(5)) # Test foo - but how to test that an inf loop is not present??
...只是讓它在那裏,你的構建將超時。 –