从this question开始,我尝试使用A()
修补课程Mock()
,以便在初始化B()
时,将Mock用作基础,例如:
class A(object): ...
class B(A): ...
def setUp(self):
with patch('A', new_callable=Mock) as MockObject:
self.b = B()
self.b.__class__.__base__ = MockOjbect
哪个不起作用,因为 base 是只读的。这样做的正确方法是什么?
更新
>>> from mock import Mock
>>> class A(object):
... pass
...
>>> class B(A):
... pass
...
>>> b.__class__.__bases__ = (Mock, )
>>> b.__class__.__bases__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/envs/myenv/local/lib/python2.7/site-packages/mock.py", line 656, in __getattr__
elif self._mock_methods is not None:
File "/opt/envs/myenv/local/lib/python2.7/site-packages/mock.py", line 655, in __getattr__
raise AttributeError(name)
AttributeError: _mock_methods
要说清楚,我不相信这是实现我想要做的最好的方式,我一半希望别人会想出另一种方式。
答案 0 :(得分:2)
__bases__
是tuple
。
更正版本:
class A(object): ...
class B(A): ...
def setUp(self):
with patch('A', new_callable=Mock) as MockObject:
self.b = B()
self.b.__class__.__bases__ = (MockOjbect,)
请参阅:
>>> class Foo(object):
... pass
...
>>> Foo.__class__.__bases__
(<type 'object'>,)
tuple
是不可变的,但__bases__
属性肯定不是只读的。