Here is my class:
这是我的类:
class GoogleCloudLayer:
def deleteMachine(self, machineName):
return machineName + ' is dead. (stubbed)'
It works:
工作原理:
>>> gc = GoogleCloudLayer()
>>> gc.deleteMachine('test')
test is dead (stubbed)
But I want to use in test and I want to have the assert_called_with
method defined on it:
但是我想在测试中使用,我想要有assert_called_withmethod定义的方法:
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)
But then I get
但后来我得到
>>> gc = GoogleCloudLayer()
>>> gc.deleteMachine('test')
unbound method deleteMachine() must be called with GoogleCloudLayer instance as first argument (got str instance instead)
If I change production code to gc.deleteMachine(gc, 'test')
it works. But we don't want that , do we?
如果我将生产代码更改为gc. deletemachine (gc, 'test'),它就可以工作了。但我们不想这样,不是吗?
1 个解决方案
#1
1
lambda
can be useful in this situation, try:
lambda在这种情况下是有用的,试试:
GoogleCloudLayer.createMachine = MagicMock(side_effect = lambda *args, **kwargs: GoogleCloudLayer.createMachine)
#1
1
lambda
can be useful in this situation, try:
lambda在这种情况下是有用的,试试:
GoogleCloudLayer.createMachine = MagicMock(side_effect = lambda *args, **kwargs: GoogleCloudLayer.createMachine)