unittests for infinite loop
You could code the infinite loop using the itertools.count
funсtion instead of while True: ...
. This might make the code slightly less efficient, but it makes it possible to mock the infinite loop:
import itertools
try:
for _ in itertools.count():
time.sleep(60)
except:
fun()
Then in your test do:
from unittest.mock import patch
with patch("itertools.count") as mock_count:
# tests go here
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()