我有一个模拟类的沙盒框架。每当客户机试图调用该类时,都会提供一个替换。这很有效。但是,当客户机试图继承修补过的类时,我的框架就崩溃了
from unittest.mock import patch
class ProductionObject(object):
def __init__(self, name): # The number of args here are being treated as a black box.
self.name = name
class FakeObject(ProductionObject):
def __init__(self, **kwargs):
kwargs['name'] = 'sandbox_' + kwargs['name']
super(FakeObject, self).__init__(**kwargs)
@patch('__main__.ProductionObject')
def run(func, mock):
mock.side_effect = FakeObject
func()
获取客户端代码并在框架中运行:
def foo():
a = ProductionObject(name='a')
print(a.name)
run(foo) # works great
def bar():
class AnotherProductionObject(ProductionObject):
def __init__(self, name, val):
self.val = val
super(AnotherProductionObject, self).__init__(name=name)
a = AnotherProductionObject(name='a', val='b')
print(a.name)
run(bar) # doesn't work
输出
sandbox_a <-- this is the correct output
<MagicMock name='ProductionObject.name' id='#####'> <-- this is broken
可以使用以下代码执行此操作:
您遇到的问题是因为
side_effect
只会更改调用mock时的行为。当您从mock继承时,您实际上从未调用它,因此您从未收到FakeObject相关问题 更多 >
编程相关推荐