Patching datetime.timedelta.total_seconds

萝らか妹 提交于 2019-12-11 06:36:38

问题


I write unit-tests for web application and i should change function waiting time TIME_TO_WAIT to test some modules. Example of code:

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)

I see a way to solve this problem with patch of datetime.timedelta.total_seconds(), but i don`t know, how do this correctly.

Thanks.


回答1:


As I wrote in the comment - I would patch out dt and time in order to control the speed of of test execution like so:

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)


来源:https://stackoverflow.com/questions/45566825/patching-datetime-timedelta-total-seconds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!