我想测试一个我写的简单装饰器:
看起来像这样:
#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()
只是一个辅助包装器。因此,如果我将其取出来,则测试有效。我可以让functools.wraps()与Mock一起玩吗?
Python 2.7.3
最佳答案
只需给你的模拟那个属性:
mock_func.__name__ = 'foo'
就是这样。
演示:
>>> from functools import wraps
>>> from mock import Mock
>>> def decor(f):
... @wraps(f)
... def wrapper(*args, **kwds):
... return f(*args, **kwds)
... return wrapper
...
>>> mock_func = Mock()
>>> decor(mock_func)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in decor
File ".../opt/lib/python2.7/functools.py", line 33, in update_wrapper
setattr(wrapper, attr, getattr(wrapped, attr))
File ".../lib/python2.7/site-packages/mock.py", line 660, in __getattr__
raise AttributeError(name)
AttributeError: __name__
>>> mock_func.__name__ = 'foo'
>>> decor(mock_func)
<function foo at 0x10c4321b8>
设置
__name__
非常好; @wraps
装饰器只需将__name__
属性复制到包装器,然后在函数对象上将该属性通常设置为字符串值。在任何情况下,它都是函数的可写属性,只要您使用字符串function.__name__
都可以设置为任何值。关于python模拟: @wraps(f) problems,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22204660/