python - 必须使用 x 实例作为第一个参数调用未绑定(bind)方法 f() (改为使用 str 实例)

标签 python magicmock

这是我的类(class):

class GoogleCloudLayer:

    def deleteMachine(self, machineName):
        return machineName + ' is dead. (stubbed)'

它有效:

>>> gc = GoogleCloudLayer()
>>> gc.deleteMachine('test')
test is dead (stubbed)

但我想在测试中使用,并且希望在其上定义 assert_ Called_with 方法:

from mock import MagicMock
#Stubbing with itself just so it will have the `assert_called_with` method defined on it
GoogleCloudLayer.deleteMachine = MagicMock(side_effect = GoogleCloudLayer.deleteMachine)

但后来我明白

>>> gc = GoogleCloudLayer()
>>> gc.deleteMachine('test')
unbound method deleteMachine() must be called with GoogleCloudLayer instance as first argument (got str instance instead)

如果我将生产代码更改为 gc.deleteMachine(gc, 'test') 它就可以工作。 但我们不希望这样,不是吗?

最佳答案

lambda 在这种情况下可能很有用,请尝试:

GoogleCloudLayer.createMachine = MagicMock(side_effect = lambda *args, **kwargs: GoogleCloudLayer.createMachine)

关于python - 必须使用 x 实例作为第一个参数调用未绑定(bind)方法 f() (改为使用 str 实例),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35887323/

相关文章:

python - 在 Cython 中使用/编译 C++

Python:检查字典是否为空的有效方法

python - 如何将 ctypes c_void_p 对象转换为实际类型?

sqlalchemy - SQLAlchemy 连接的模拟异步上下文管理器

python - 当 Nose 测试发现测试时,Magic Mock 失败

python - Django URL 在 root 和包含的 url 之间给我空间

python - 在另一个里面画一个窗口

python - 如何使用方法 MagicMock 对象列表并获取断言计数

python - MagicMock 如何在调用随机方法时避免抛出 AttributeError?

对于公共(public)方法,Python 模拟补丁无法按预期工作