gpt4 book ai didi

python - python-3.3 模拟工具

转载 作者:太空宇宙 更新时间:2023-11-04 03:54:45 27 4
gpt4 key购买 nike

我有几个依赖于 time.perf_counter() 的类来为事件添加时间戳并在经过一定时间后执行操作,如下所示:

class Alarm:
def setAlarm(self):
self.alarmed = False
self._saved = time.perf_counter()

def runStep(self):
now = time.perf_counter()
if now - self._saved > 1000.0 and self._saved != -1:
self.alarmed = True
self._saved = -1

我想用一个假时钟测试Alarm类,不一定要调用time.perf_counter()(虽然它会更我猜,如果它确实很优雅)。我希望假时钟不会自行递增,而是根据我的命令递增,如下所示:

    alarm = Alarm()
alarm.setAlarm()
clock.increment(999.0)
alarm.runStep()
self.assertFalse(alarm.alarmed)
clock.increment(1.1) # tick another second
alarm.runStep()
self.assertTrue(alarm.alarmed)

能否请您建议如何模拟 time.perf_counter() 或为此模拟我的类,以及应该使用什么样的工具来完成这种工作?

最佳答案

您可以使用 unittest.mock .

例如:

import time
import unittest
import unittest.mock

class Alarm:
def setAlarm(self):
self.alarmed = False
self._saved = time.perf_counter()
def runStep(self):
now = time.perf_counter()
if now - self._saved > 1000.0 and self._saved != -1:
self.alarmed = True
self._saved = -1

class MockPerfCounter:
def __init__(self):
self.t = 0
def increment(self, n):
self.t += n
def perf_counter(self):
return self.t

class TestAlarm(unittest.TestCase):
def test_foo(self):
clock = MockPerfCounter()
with unittest.mock.patch('time.perf_counter', clock.perf_counter):
alarm = Alarm()
alarm.setAlarm()
clock.increment(999.0)
alarm.runStep()
self.assertFalse(alarm.alarmed)
clock.increment(1.1) # tick another second
alarm.runStep()
self.assertTrue(alarm.alarmed)

if __name__ == '__main__':
unittest.main()

或者,您也可以使用 unittest.mock.Mock 而不是手动 MockPerfCounter :

class TestAlarm(unittest.TestCase):
def test_foo(self):
clock = unittest.mock.Mock()
clock.t = 0
with unittest.mock.patch('time.perf_counter', lambda: clock.t):
alarm = Alarm()
alarm.setAlarm()
clock.t += 999.0
alarm.runStep()
self.assertFalse(alarm.alarmed)
clock.t += 1.1
alarm.runStep()
self.assertTrue(alarm.alarmed)

关于python - python-3.3 模拟工具,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19338748/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com