[英]Test if super() was called during initialization gives AttributeError
I would like to test if in the following scenario the init routine of the Base class is called during the initialization of the Derived class: 我想测试在以下情况下是否在派生类的初始化期间调用了基类的初始化例程:
class Base(object):
def __init__(self, a):
self.a = a
class Derived(Base):
def __init__(self, a):
super(Derived, self).__init__(a)
I used this post here and this test works fine: 我在这里使用了这篇文章 ,这个测试工作正常:
@mock.patch("mocktest.Base.__init__")
def test_calls_init_routine_of_base(mock_super_init):
Derived(1)
assert mock_super_init.called
However, if the Derived class does something with the attribute a
after super(Derived, self).__init(a)
, eg if I put a print(self.a)
right after the call to super(), then the test throws an AttributeError: 但是,如果Derived类对super(Derived, self).__init(a)
之后的属性a
进行了某些操作,例如,如果我在对super()的调用之后放置了print(self.a)
),则测试将抛出一个AttributeError:
AttributeError: 'Derived' object has no attribute 'a'
How can I prevent this? 我该如何预防? Are there other/better ways to realize this test in this situation? 在这种情况下,还有其他/更好的方法来实现此测试吗?
Seriously, never do this kind of mock... If you want to test super call try to find a super behavior that you can check. 认真地说,永远不要做这种模拟...如果您想测试超级调用,请尝试查找可以检查的超级行为。
If you don't find any other way or you have some mysterious reasons to check it (I did it in the past but I cannot remember why... maybe I did the wrong thing) you can just wrap it: 如果您找不到其他方法,或者有一些神秘的原因要检查它(我以前做过,但是我不记得为什么...也许我做错了事),您可以将其包装:
@mock.patch("mocktest.Base.__init__", wraps=mocktest.Base.__init__)
def test_calls_init_routine_of_base(mock_super_init):
Derived(1)
assert mock_super_init.called
If you really need to avoid a super call (for instance you derive from something that start a thread or access to some remote resource) you should patch the attributes that you need too: 如果确实需要避免超级调用(例如,您是从启动线程或访问某些远程资源的东西派生的),则也应该修补所需的属性:
@mock.patch("mocktest.Base.a", create=True)
@mock.patch("mocktest.Base.__init__")
def test_calls_init_routine_of_base(mock_super_init):
Derived(1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.