如何消除PyTest运行时的DeprecationWarning: There is no current event loop警告?
消除pytest-asyncio 0.23.3的"There is no current event loop"警告
问题背景
已将pytest-asyncio添加到Poetry的test和dev分组,测试代码如下:
async def blah(): return 1 @pytest.mark.asyncio async def test_me(mock_client, mock_config, event_loop): res = await blah() assert 1 == res
运行poetry run pytest时出现警告:
/Users/ykhaburzaniya/Library/Caches/pypoetry/virtualenvs/my-project-6HJyiZWL-py3.11/lib/python3.11/site-packages/pytest_asyncio/plugin.py:884: DeprecationWarning: There is no current event loop _loop = asyncio.get_event_loop()
使用的pytest-asyncio版本为0.23.3。
解决方案
pytest-asyncio 0.23+版本已废弃通过参数注入event_loop的方式,改为自动管理事件循环,按以下方式修改即可消除警告:
移除测试函数中的
event_loop参数:无需手动注入事件循环,pytest-asyncio会自动为异步测试创建并维护事件循环。修改后的代码:async def blah(): return 1 @pytest.mark.asyncio async def test_me(mock_client, mock_config): res = await blah() assert 1 == res若测试中需要使用事件循环:在函数内部通过
asyncio.get_running_loop()获取,替代参数注入的方式:import asyncio async def blah(): return 1 @pytest.mark.asyncio async def test_me(mock_client, mock_config): loop = asyncio.get_running_loop() # 基于loop执行相关操作 res = await blah() assert 1 == res
内容的提问来源于stack exchange,提问作者Yason
相关产品推荐
相关产品推荐

