我在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??
...只是让它在那里,你的构建将超时。 –