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()
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.