Python单元测试模拟,无法修补`__init __。py中导入的`time`模块

时间:2016-08-24 14:00:17

标签: python-2.7 unit-testing mocking

我在 __ init __。py 文件中有以下代码

from time import sleep
from functools import wraps

def multi_try(func):
    @wraps(func)
    def inner(*args, **kwargs):
        count = 0
        while count < 5:
            resp = func(*args, **kwargs)
            if resp.status_code in [200, 201]:
                return resp
            sleep(1)
            count += 1
    return inner

在为上面的装饰器编写测试时,我无法正确修补 time.sleep

参见下面的测试,即使我修补了时间模块,仍然会调用装饰器内部的睡眠功能,因此测试用例需要5秒以上才能完成。

def test_multi_try_time():
    with patch("time.sleep") as tm: 
       mocker = MagicMock(name="mocker")
       mocker.__name__ = "blah"
       resp_mock = MagicMock()
       resp_mock.status_code=400
       _json = '{"test":"twist"}'
       resp_mock.json=_json
       mocker.return_value = resp_mock
       wrapped = multi_try(mocker)
       resp = wrapped("p", "q")
       assert mocker.call_count == 5
       mocker.assert_called_with('p', 'q')
       assert resp == None

我也试过了,

with patch("dir.__init__.time" ) as tm:

with patch("dir.utils.time" ) as tm:

结果

AttributeError: <module 'dir/__init__.pyc'> does not have the attribute 'time'

1 个答案:

答案 0 :(得分:2)

我所要做的只是

with patch("dir.sleep" ) as tm:

而不是,

with patch("time.sleep") as tm: