我想测试我写的一个简单的装饰器:
它看起来像这样:
#utilities.py
import other_module
def decor(f):
@wraps(f)
def wrapper(*args, **kwds):
other_module.startdoingsomething()
try:
return f(*args, **kwds)
finally:
other_module.enddoingsomething()
return wrapper
然后我使用 python-mock 对其进行测试:
#test_utilities.py
def test_decor(self):
mock_func = Mock()
decorated_func = self.utilities.decor(mock_func)
decorated_func(1,2,3)
self.assertTrue(self.other_module.startdoingsomething.called)
self.assertTrue(self.other_module.enddoingsomething.called)
mock_func.assert_called_with(1,2,3)
但它反击:
Traceback (most recent call last):
File "test_utilities.py", line 25, in test_decor
decorated_func = Mock(wraps=self.utilities.decor(mock_func))
File "utilities.py", line 35, in decor
@wraps(f)
File "/usr/lib/python2.7/functools.py", line 33, in update_wrapper
setattr(wrapper, attr, getattr(wrapped, attr))
File "/usr/local/lib/python2.7/dist-packages/mock.py", line 660, in __getattr__
raise AttributeError(name)
AttributeError: __name__
我知道functools.wraps()
只是一个辅助包装器。所以如果我把它拿出来测试就可以了。
我可以让 Mock 与 functools.wraps() 一起玩吗?
Python 2.7.3