我无法理解模拟补丁的工作原理以及它是否能够解决我的问题。
我有 3 个文件:与外部接口 (a.py) 的通信、业务逻辑 (b.py) 和测试 (test.py)。我想在运行测试时修补业务逻辑使用的外部接口。
一个.py:
class SomeProductionClassINeedPatch(object):
name = 'Production Class (communication with some external service)'
def do_something(self):
print '<some feature with external service>'
b.py:
import mock
from src.tmp.mocks.a import SomeProductionClassINeedPatch
class WorkingClass(object):
def some_method_that_uses_external_class(self, *args):
external = self._external
external.do_something()
@property
def _external(self):
if not hasattr(self, '_ext_obj' or not self._ext_obj):
self._ext_obj = SomeProductionClassINeedPatch()
print isinstance(self._ext_obj, mock.MagicMock) # False
return self._ext_obj
b = WorkingClass()
b.some_method_that_uses_external_class()
测试.py:
import mock
from src.tmp.mocks.b import WorkingClass # class I want to test
@mock.patch('src.tmp.mocks.a.SomeProductionClassINeedPatch')
def test_some_method_of_working_class(external_mock=None, *args):
o = WorkingClass()
o.some_method_that_uses_external_class() # external interface wasn't patched: <some feature with external service> - but I need mock here!
print '<test> - '+str(isinstance(o._external, mock.MagicMock)) # False
test_some_method_of_working_class()
我希望在test.py中调用 o.some_method_that_uses_external_class()实际上不会使用外部接口,而是模拟对象。但似乎仍然使用实际对象。
此外,当我在 test.py 或 b.py 中检查外部接口对象的实例时 - 我无法让它们通过isinstance(object, MagicMock)检查,它总是返回 false。即使我尝试在b.py中应用相同的补丁(作为类装饰器)。我究竟做错了什么?
如果这很重要,我会使用 Michael Foord 的 python 2.7 和模拟库 1.0。