I am stucked at this code for creating unittest for infinite loop.
try:
while True:
time.sleep(60)
except:
fun()
Please let me know how can we create unittests for infinite loop?
What behaviour are you testing? There doesn't appear to be any side effects or return value here. There isn't really anything to test. If it's just that fun
is called after the loop then that sounds like over-specification. If it's just that some invariant is maintained after the loop ends then you can patch sleep
to throw an exception, and then examine the state after the function has run.
from unittest import TestCase, main
from unittest.mock import patch
import module_under_test
class TestLoop(TestCase):
# patch sleep to allow loop to exit
@patch("time.sleep", side_effect=InterruptedError)
def test_state_reset(self, mocked_sleep):
# given
obj = module_under_test.SomeClass()
# when
obj.infinite_loop()
# then assert that state is maintained
self.assertFalse(obj.running)
if __name__ == "__main__":
main()
module_under_test.py
import time
class SomeClass:
def __init__(self):
self.running = False
def fun(self):
self.running = False
def infinite_loop(self):
self.running = True
try:
while True:
time.sleep(60)
except:
self.fun()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With