2016-08-24 35 views
0

我在写在__init__.py文件Python的单元测试嘲讽,无法修补`这是一个在`__init __被导入time`模块。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'

回答

2

我所要做的就是

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

相反的,

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

看起来你相处得很好:+1: –