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?
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 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 .
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.
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
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