Python unittest vs potential infinite loop

I have a python function which, if the bad data passed in, gets into an infinite loop. I would like to write a unit test to confirm that it handles bad parameters gracefully. The problem, of course, is that if he does not detect bad parameters, he will not return.

Can I use streams to write a test for this type?

import threading, unittest
import mymodule

class CallSuspectFunctionThread(threading.Thread):
    def __init__(self, func, *args):
        self.func = func
        self.args = args
        super(CallSuspectFunctionThread, self).__init__()
    def run(self):
        self.func(*self.args)

class TestNoInfiniteLoop(unittest.TestCase):
    def test_no_infinite_loop(self):
        myobj = mymodule.MyObject()
        bad_args = (-1,0)
        test_thread = CallSuspectFunctionThread(mybj.func_to_test, *bad_args)
        test_thread.daemon = True
        test_thread.start()
        # fail if func doesn't return after 8 seconds
        for i in range(32):
            test_thread.join(0.25)
            if not test_thread.is_alive():
                return
        self.fail("function doesn't return")

The only problem I see with is that if the test fails, I am stuck in this extra thread, potentially consuming processor and memory resources, and the rest of the tests run. On the other hand, I fixed the code and the probability of regressing here is very subtle, so I don’t know if even the question of whether I include the test or not matters.

+5
6

. , "" "" (.. )? , , .

: " 1,5 , , , . 2 , ". .

. .

- - , .

, .

, .

+1

, , , , . , , ( ), , .

+1

- . , .

, , python. , .

0

. , , .

0

, , . . ( , ), " ". -.

0

All Articles