如何在Python单元测试中存根time.sleep() [英] How to stub time.sleep() in Python unit testing
本文介绍了如何在Python单元测试中存根time.sleep()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个存根以防止time.sleep(..)进入睡眠状态,以缩短单元测试的执行时间.
I want to make a stub to prevent time.sleep(..) to sleep to improve the unit test execution time.
我所拥有的是:
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).
如何解决该错误?
推荐答案
您可以在测试中使用 mock 库
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
这篇关于如何在Python单元测试中存根time.sleep()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文