我正在尝试使用 mock 和 pytest-asyncio 编写一个单元测试用例。我有一个正常的功能,使用asyncio.run
. 【使用python3.7】
import asyncio
async def sample_async(arg2):
# do something
proc = await asyncio.create_subprocess_shell(arg2)
# some more asyncio calls
rc = proc.returncode
return rc
def launcher(arg1, arg2):
if arg1 == "no_asyncio":
# do something
print("No asyncio")
return 0
else:
return_code = asyncio.run(sample_async(arg2))
# do something
return return_code
我能够为 asyncio 函数编写单元测试,sample_async
但不能为launcher
. 这是我尝试过的:
class AsyncMock(MagicMock):
async def __call__(self, *args, **kwargs):
return super(AsyncMock, self).__call__(*args, **kwargs)
@patch("asyncio.create_subprocess_shell", new_callable=AsyncMock)
def test_launcher(async_shell):
arg1 = "async"
arg2 = "/bin/bash ls"
sample.launcher(arg1, arg2)
async_shell.assert_called_once()
当我尝试运行 pytest 时,由于该函数不是 asyncio 协程,因此我一直RuntimeError: There is no current event loop in thread 'MainThread'.
无法@pytest.mark.asyncio
用于此测试。launcher
我在这里做错了什么?