在测试中,我无法将__exit__
方法附加到模拟模仿上,以至于在with
语句中使用该模拟时都不介意。
以下是不断提高AttributeError: __exit__
的测试示例:
# main.py
class FooManager(object):
def __enter__(self):
print "Connect"
def __exit__(self, exc_type, exc_val, exc_tb):
print "Dissconnect"
def foo(self):
print "Foo"
def function_to_be_tested(manager):
# type: (FooManager) -> None
with manager:
manager.foo()
# test.py
from mockito import mock, verify, when, any as ANY
def test():
manager_mock = mock()
# none of this has any effect:
manager_mock.__exit__ = lambda a, b, c: None
when(manager_mock).__exit__(ANY(), ANY(), ANY()).thenReturn(None)
function_to_be_tested(manager_mock)
verify(manager_mock, times=1).foo()
解决我问题的唯一方法是:
class ContextManagerMock(mock):
def __enter__(self):
return None
def __exit__(self, exc_type, exc_val, exc_tb):
return None
def test():
manager_mock = ContextManagerMock()
function_to_be_tested(manager_mock)
verify(manager_mock, times=1).foo()
但是,我想知道为什么当我尝试通过AttributeError
函数或lambda函数附加__exit__
方法时为什么会有一个when
。
答案 0 :(得分:1)
您可能只是想念也需要嘲笑__enter__
。
In [24]: m = mock()
In [25]: when(m).__enter__(...)
Out[25]: <mockito.invocation.AnswerSelector at 0x13db478>
In [26]: when(m).__exit__(...)
Out[26]: <mockito.invocation.AnswerSelector at 0x501bd00>
In [27]: with m: ...
In [28]: verify(m).__enter__()
In [29]:
如果我不嘲笑__enter__
,我会得到AttributeError: __enter__
。