为什么嘲笑在调用时忽略了传递给嘲笑方法的实例/对象? [英] Why does mock ignore the instance/object passed to a mocked out method when it is called?
问题描述
我最近注意到,如果我使用mock.patch
模拟方法,则不会在call_args
字段中列出传递给模拟方法的实例对象.这是设计使然吗?下面的代码/输出可能会更好地解释我的意思:
I have recently noticed that if I mock out a method using mock.patch
it doesn't list the instance object passed to the mocked method in the call_args
field. Is this by design? Code/output below may better explain what I mean:
#!/usr/bin/env python2
from mock import patch
class Dog(object):
def bark(self):
print("Woof woof!")
Dog().bark()
def new_method(*args):
print("args = %s" % str(args))
Dog.bark = new_method
Dog().bark()
with patch.object(Dog, "bark"):
d = Dog()
d.bark()
print("d.bark was called: %s" % str(d.bark.called))
print("d.bark was called with args/kwargs: %s" % str(d.bark.call_args))
输出为:
Woof woof!
args = (<__main__.Dog object at 0x7f42c2dbc3d0>,)
# Mocking bit
d.bark was called: True
d.bark was called with args/kwargs: ((), {})
您可以看到,当实例对象替换bark
时,该实例对象已传递给new_method
.但是您无法在模拟方法的call_args
中看到它.这不是很奇怪吗?我正在使用python模拟库的1.01版.
You can see that the instance object is passed to new_method
when it replaces bark
. But you cannot see it in the call_args
of the mocked out method. Isn't this strange? I am using version 1.01 of the python mock library.
推荐答案
通过
with patch.object(Dog, "bark"):
要修补Dog.bark
方法的静态实例,是因为要修补Dog
类而不是Dog
对象.
You are patching the static instance of Dog.bark
method because you are patching Dog
class and not a Dog
object.
现在,模拟方法将被称为静态方法,而不是对象方法:这意味着self
属性将不会通过.
Now the mock method will be called as a static method and not as object method: that means the self
attribute will not passed.
如果要创建具有与原始方法相同签名的补丁,则可以使用autospec=True
属性:在这种情况下,模拟方法将是对象方法,而不是静态方法.
If you want create a patch with the same signature of original method you can use autospec=True
attribute: in this case the mock method will be an object method instead of a static method.
>>> from mock import patch
>>> with patch.object(Dog, "bark", autospec=True):
... d = Dog()
... d.bark()
... print("d.bark was called with args/kwargs: %s" % str(d.bark.call_args))
...
<MagicMock name='bark()' id='139848306278672'>
d.bark was called with args/kwargs: call(<Dog object at 0x7f30f89ef390>)
这篇关于为什么嘲笑在调用时忽略了传递给嘲笑方法的实例/对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!