在一些asyncio测试用例中,我发现我经常想等待某个方法被调用,所以我编写了下面的上下文管理器:使用mock.patch.object包装一个类的所有对象的方法
@contextmanager
def wait_for_call(loop, obj, method, calls = 1):
# set up some bookkeeping including a future called fut
def cb(*args, **kwards):
# Set fut's result to true if the right number of calls happen
try:
with mock.patch.object(obj, method,
wraps = getattr(obj, method),
side_effect = cb):
yield
loop.run_until_complete(asyncio.wait_for(fut, 0.5))
except asyncio.futures.TimeoutError:
raise AssertionError("Timeout waiting for call to {} of {}".format(
method, obj)) from None
如果我修补某个特定的实例或者修补类方法,这会很好。然而,有一对夫妇的情况下,我想修补常规(实例)方法是这样的:
class foo:
def bar(self): pass
x = foo()
with wait_for_call(loop, x, 'bar'): x.bar()
当我这样做,我得到一个TypeError
因为x.bar
没有得到self
。我认为这是因为MagicMock
没有像函数那样实现描述符协议。 如何包装一个方法并获得self
的正确处理?
这是行不通的? '用wait_for_call(...)作为w:w()' – Dan
@Dan如果我在那里传递自己,它可能会,但它不是很有用,因为我通常在等待一个在通话中很深的通话图形。 –