如何在未锁定的类中用autospec修补classmethod?

2024-06-07 03:09:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我想断言Python类中的一个类方法调用另一个具有特定参数集的类方法。我希望mocked类方法被“规范化”,这样它就可以检测是否使用错误数量的参数调用它。在

当我使用patch.object(.., autospec=True, ..)修补classmethod时,classmethod将被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__)

产生输出:

^{pr2}$

_internal_classmethod所属的类未被模拟时,如何为_internal_classmethod获取规范化的mock?在


Tags: 方法true参数returnobjectdef错误with
2条回答

有一个未完成的错误报告(google code linkpython bug tracker link)来解决这个问题。在合并修复程序之前,您可以尝试下面的方法,这对我[在2.7上有效,但我认为它在3.x中也可以工作。在

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,并且正确地修补了静态和类方法。在

使用spec代替autospec,并直接设置它。在

with patch.object(A, '_internal_classmethod', spec=A._internal_classmethod) as p:
    print(type(p).__name__)

给了我

^{pr2}$

用于输出。在

相关问题 更多 >