私が書いた単純なデコレータをテストしたい:
次のようになります。
#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 をうまくプレイさせることはできますか?
パイソン 2.7.3