11

我想测试我写的一个简单的装饰器:

它看起来像这样:

#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

4

1 回答 1

16

只需给您的模拟该属性:

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__,就可以将其设置为任何值。

于 2014-03-05T17:22:02.250 回答