test for absence of infinite loop

Cameron Simpson cs at cskk.id.au
Tue Jul 17 19:28:10 EDT 2018


On 17Jul2018 12:39, Robin Becker <robin at reportlab.com> wrote:
>On 17/07/2018 12:16, Cameron Simpson wrote:
>>On 17Jul2018 10:10, Robin Becker <robin at reportlab.com> wrote:
>>>A user reported an infinite loop in reportlab. I determined a 
>>>possible cause and fix and would like to test for absence of the 
>>>loop. Is there any way to check for presence/absence of an 
>>>infinite loop in python? I imagine we could do something like call 
>>>an external process and see if it takes too long, but that seems a 
>>>bit flaky.
>>
>>While others have kindly pointed you at the halting problem 
>>(unsolvable in the general case) you can usually verify that the 
>>specific problem you fixed is fixed. Can you figure out how long the 
>>task should run with your fix in a test case? Not as time, but in 
>>loop iterations? Put a counter in the loop and check that its value 
>>doesn't exceed that.
>
>well I understand the problem about not halting. However as you point 
>out in a fixed case I know that the test should take fractions of a 
>second to complete. I certainly don't want to put instrumentation into 
>the source code. It's relatively easy to imagine polling termination 
>of a separate thread/process, but that's not particularly reliable. I 
>don't know if there is a way to ask a python interpeter how many instructions 
>it has carried out.

Hmm. You can set a hard timeout with signal.alarm. Something like:

  import signal
  def test_timeout(maxtime):
    signal.alarm(maxtime)
    your_looping_function(...)
    signal.alarm(0)

The OS (if UNIX) will send SIGALRM after that number of seconds, which should 
abort the program by raising an exception. So any test suite will fail the 
test, or a bare test run will terminate anyway without running forever.

Cheers,
Cameron Simpson <cs at cskk.id.au>



More information about the Python-list mailing list