<p>实际上,Monkey补丁<code>time.time</code>可能已经足够了,因为它为Python中几乎所有其他基于时间的例程提供了基础。这似乎可以很好地处理您的用例,而无需使用更复杂的技巧,而且何时执行也无所谓(除了少数stdlib包,如Queue.py和threading.py,在这种情况下,您必须在导入它们之前进行修补):</p>
<pre><code>>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2010, 4, 17, 14, 5, 35, 642000)
>>> import time
>>> def mytime(): return 120000000.0
...
>>> time.time = mytime
>>> datetime.datetime.now()
datetime.datetime(1973, 10, 20, 17, 20)
</code></pre>
<p>也就是说,在多年来为各种类型的自动化测试模拟对象的过程中,我很少需要这种方法,因为大多数时候需要模拟的是我自己的应用程序代码,而不是stdlib例程。毕竟,你知道他们已经开始工作了。如果遇到自己的代码必须处理库例程返回的值的情况,则可能需要模拟库例程本身,至少在检查自己的应用程序如何处理时间戳时是这样。</p>
<p>到目前为止,最好的方法是构建您自己的日期/时间服务例程,您只在应用程序代码中使用这些例程,并在其中构建测试功能,以便根据需要提供假结果。例如,有时我会做一个更复杂的类似的事情:</p>
<pre><code># in file apptime.py (for example)
import time as _time
class MyTimeService(object):
def __init__(self, get_time=None):
self.get_time = get_time or _time.time
def __call__(self):
return self.get_time()
time = MyTimeService()
</code></pre>
<p>现在在我的应用程序代码中,我只需要<code>import apptime as time; time.time()</code>来获取当前时间值,而在测试代码中,我可以首先在<code>apptime.time = MyTimeService(mock_time_func)</code>代码中<code>setUp()</code>来提供假时间结果。</p>
<p><em>更新:</em>几年后有一个替代方案,如<a href="https://stackoverflow.com/a/45066594/221537">Dave Forgac's answer</a>所述。</p>