必须使用x实例作为第一个参数调用unbound方法f()(改为使用str实例)

时间:2016-03-09 09:14:32

标签: python magicmock

这是我的班级:

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')则可行。 但是我们不想要那个,是吗?

1 个答案:

答案 0 :(得分:1)

lambda在这种情况下非常有用,请尝试:

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