2

我有一些类依赖于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()为它模拟或模拟我的课程,以及这种工作应该使用什么样的工具?

4

1 回答 1

2

您可以使用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()

MockPerfCounter或者,您也可以使用以下命令代替手动unittest.mock.Mock

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)
于 2013-10-12T20:23:59.480 回答