我为Web应用程序编写单元测试,我应该更改函数等待时间TIME_TO_WAIT来测试一些模块。 代码示例:
import time
from datetime import datetime as dt
def function_under_test():
TIME_TO_WAIT = 300
start_time = dt.now()
while True:
if (dt.now() - start_time).total_seconds() > TIME_TO_WAIT:
break
time.sleep(1)
我看到用datetime.timedelta.total_seconds()补丁解决这个问题的方法,但我不知道,这是怎么做的。
感谢。
答案 0 :(得分:1)
正如我在评论中写的那样 - 我会修补dt
和time
以控制测试执行的速度,如下所示:
from unittest import TestCase
from mock import patch
from datetime import datetime
from tested.module import function_under_test
class FunctionTester(TestCase):
@patch('tested.module.time')
@patch('tested.module.dt')
def test_info_query(self, datetime_mock, time_mock):
datetime_mock.now.side_effect = [
datetime(year=2000, month=1, day=1, hour=0, minute=0, second=0),
datetime(year=2000, month=1, day=1, hour=0, minute=5, second=0),
# this should be over the threshold
datetime(year=2000, month=1, day=1, hour=0, minute=5, second=1),
]
value = function_under_test()
# self.assertEquals(value, ??)
self.assertEqual(datetime_mock.now.call_count, 3)