我想断言Python类中的一个类方法使用一组特定的参数调用另一个类方法。我希望被模仿的类方法是“规范的”,这样它就能检测到它是否使用了错误数量的参数来调用。
当我使用patch.object(.., autospec=True, ..)修补类方法时,类方法被替换为NonCallableMagicMock,并在尝试调用它时引发错误。
from mock import patch
class A(object):
@classmethod
def api_meth(cls):
return cls._internal_classmethod(1, 2, 3)
@classmethod
def _internal_classmethod(cls, n, m, o):
return sum(n, m, o)
with patch.object(A, '_internal_classmethod') as p:
print(type(p).__name__)
with patch.object(A, '_internal_classmethod', autospec=True) as p:
print(type(p).__name__)生成输出:
MagicMock
NonCallableMagicMock当_internal_classmethod所属的类没有被模拟时,我如何为它获得一个规范的模拟?
发布于 2015-06-03 00:48:17
有一个优秀的错误报告(google code link和python bug tracker link)可以解决这个问题。在包含修复程序之前,您可以尝试以下方法,虽然我认为它在3.x中也适用,但我在2.7上使用了这些方法。
def _patched_callable(obj):
"Monkeypatch to allow autospec'ed classmethods and staticmethods."
# See https://code.google.com/p/mock/issues/detail?id=241 and
# http://bugs.python.org/issue23078 for the relevant bugs this
# monkeypatch fixes
if isinstance(obj, type):
return True
if getattr(obj, '__call__', None) is not None:
return True
if (isinstance(obj, (staticmethod, classmethod))
and mock._callable(obj.__func__)):
return True
return False
_patched_callable._old_func = mock._callable
mock._callable = _patched_callable在monkeypatch之后,您应该能够正常使用mock.patch,并正确修补静态方法和类方法。
发布于 2014-09-18 03:29:42
用spec代替autospec,直接设置即可。
with patch.object(A, '_internal_classmethod', spec=A._internal_classmethod) as p:
print(type(p).__name__)给了我
MagicMock用于输出。
https://stackoverflow.com/questions/25587468
复制相似问题