gpt4 book ai didi

python - 如何在未模拟的类中使用 autospec 修补类方法?

转载 作者:太空狗 更新时间:2023-10-29 18:03:53 25 4
gpt4 key购买 nike

我想断言 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 获取规范模拟?

最佳答案

有一个未完成的错误报告(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 并正确修补静态和类方法。

关于python - 如何在未模拟的类中使用 autospec 修补类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25587468/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com