gpt4 book ai didi

python - 单元测试 : patching an objects __base__

转载 作者:太空宇宙 更新时间:2023-11-04 03:52:34 24 4
gpt4 key购买 nike

this question 开始,我试图用 Mock() 修补类 A() ,这样当 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

需要明确的是,我不相信这是实现我想要做的事情的最佳方式,我有一半希望其他人会想出另一种方式。

最佳答案

__bases__ 是一个元组

更正版本:

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__ 属性肯定不是只读的。

关于python - 单元测试 : patching an objects __base__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20542446/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com