Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 490
Michel Keijzers Avatar asked Apr 03 '14 11:04

Michel Keijzers


People also ask

What is time sleep in Python?

Python time sleep function is used to add delay in the execution of a program. We can use python sleep function to halt the execution of the program for given time in seconds.

How do you mock a function in Python?

How do we mock in Python? Mocking in Python is done by using patch to hijack an API function or object creation call. When patch intercepts a call, it returns a MagicMock object by default. By setting properties on the MagicMock object, you can mock the API call to return any value you want or raise an Exception .

What is mocking in PyTest?

In pytest , mocking can replace the return value of a function within a function. This is useful for testing the desired function and replacing the return value of a nested function within that desired function we are testing.


1 Answers

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 
like image 86
Mikko Ohtamaa Avatar answered Sep 19 '22 13:09

Mikko Ohtamaa