How to stub time.sleep() in Python unit testing

Michel Keijzers picture Michel Keijzers · Apr 3, 2014 · Viewed 17k times · Source

I want to make a stub to prevent time.sleep(..) to sleep to improve the unit test execution time.

What I have is:

import time as orgtime

class time(orgtime):
    '''Stub for time.'''
    _sleep_speed_factor = 1.0

    @staticmethod
    def _set_sleep_speed_factor(sleep_speed_factor):
        '''Sets sleep speed.'''
        time._sleep_speed_factor = sleep_speed_factor


    @staticmethod
    def sleep(duration):
        '''Sleeps or not.'''
        print duration * time._sleep_speed_factor
        super.sleep(duration * time._sleep_speed_factor) 

However, I get the following error on the second code line above (class definition):

TypeError: Error when calling the metaclass bases
module.__init__() takes at most 2 arguments (3 given).

How to fix the error?

Answer

Mikko Ohtamaa picture Mikko Ohtamaa · Apr 3, 2014

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