未绑定方法 f() 必须使用 x 实例作为第一个参数调用(取而代之的是 str 实例)



这是我的类:

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)

相关内容

  • 没有找到相关文章

最新更新