我正在处理以下问题,我有一个类,一个异步方法,我想模拟补丁:
class ExampleClass:
async def asy_method(self, param):
return await some_coroutine(self, param)
example_instance = ExampleClass()
我只想专门修补像
^{pr2}$通常我会用
mocker.patch('ExampleClass.asy_method', new_callable=AsyncMock)
其中mocker是pytest mock插件fixture,AsyncMock具有以下形式
class AsyncMock(mock.MagicMock):
async def __call__(self, *args, **kwargs):
return super(AsyncMock, self).__call__(*args, **kwargs)
这会给我一个模拟对象,它的行为类似于随叫随到的协同程序。
问题是,我想访问传递给方法的self
属性。self
只有在设置
autospec=True
(另请参见Python Doc on patching unbound methods),它不能与new_callable
一起使用。在
有人知道如何解决这个问题吗?在
事实上,你不能把自动选择和新的可调用代码混合在一起。相反,自动指定方法,但随后替换
side_effect
属性,给它一个AsyncMock()
实例:因为
^{pr2}$AsyncMock()
是一个可调用的对象,所以每当mock_asy_method
被调用时,它都会被称为,并将参数传递给该对象。然后使用该调用的结果从mock_asy_method()
返回:如您所见,
self
参数和参数被记录在调用中,因为mock_asy_method
是一个正确指定的函数。在当然,只有在实际等待返回的
AsyncMock()
调用结果时,我们才会看到记录的调用:相关问题 更多 >
编程相关推荐