Sanic项目做测试,运行 `pytest` 时报了这个错:`RuntimeError: Cannot run the event loop while another loop is running`
代码如下:
import pytest
from models.nezha import get_room_name
@pytest.mark.asyncio
async def test_get_room_name():
name = await get_room_name('a', 'b')
assert name == 'b'
# models/nezha.py
async def data_from_cache_or_http(
data_key: str, etag_key: str, url: str, renew: bool
) -> dict:
...
async def rooms_from_cache_or_http(
community: str, renew: bool = False
) -> dict:
data_key, etag_key = ROOMS_CACHED_KEY, ROOMS_ETAG_CACHED_KEY
url = HOST + f'/room-names/?community={community}'
return await data_from_cache_or_http(data_key, etag_key, url, renew)
async def get_room_name(community: str, slug: str) -> str:
"""获取小区slug和房间slug对应的房号"""
if community and slug:
rooms = await rooms_from_cache_or_http(community)
return rooms.get(slug, {}).get('name')
return ''
原因:。。。google一搜就知道了,或者看这个:https://github.com/erdewit/nest_asyncio
解决:`pip install nest_asyncio`, 然后添加`import nest_asyncio; nest_asyncio.apply()`
修改后的test文件内容如下:
import nest_asyncio
import pytest
from models.nezha import get_room_name
nest_asyncio.apply()
@pytest.mark.asyncio
async def test_get_room_name():
name = await get_room_name('a', 'b')
assert name == 'b'
然后运行pytest时,却又报了这个错误:
ValueError: Can't patch loop of type
原因:nest_asyncio不支持uvloop
解决:`pip uninstall uvloop`