我想测试一个简单的装潢师,我写道:
看起来是这样的:
#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
发布于 2014-03-05 17:22:02
只需给出您的模拟属性:
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__就可以设置为任何值。
https://stackoverflow.com/questions/22204660
复制相似问题