How to stub time.sleep() in Python unit testing
You can use mock library in your tests.
import time
from mock import patch
class MyTestCase(...):
@patch('time.sleep', return_value=None)
def my_test(self, patched_time_sleep):
time.sleep(666) # Should be instant
I'm using pytest and have following fixture to monkey patch time.sleep
:
import pytest
@pytest.fixture
def sleepless(monkeypatch):
def sleep(seconds):
pass
monkeypatch.setattr(time, 'sleep', sleep)
Then in test which I need to "speedup" the sleep, I just use this fixture:
import time
def test_sleep(sleepless):
time.sleep(60)
So when you run this test, you will see that it completes in much shorter time:
= 1 passed in 0.02 seconds =
The accepted answer is still valid. However, unittest.mock is since Python 3.3 an official part of the Python standard library.
import time
from unittest import TestCase
from unittest.mock import patch
class TestMyCase(TestCase):
@patch('time.sleep', return_value=None)
def test_my_method(self, patched_time_sleep):
time.sleep(60) # Should be instant
# the mock should only be called once
self.assertEqual(1, patched_time_sleep.call_count)
# or
patched_time_sleep.assert_called_once()
# alternative version using a context manager
def test_my_method_alternative(self):
with patch('time.sleep', return_value=None) as patched_time_sleep:
time.sleep(60) # Should be instant
# the mock should only be called once
self.assertEqual(1, patched_time_sleep.call_count)
# or
patched_time_sleep.assert_called_once()