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 <class 'uvloop.Loop'>

原因:nest_asyncio不支持uvloop

解决:`pip uninstall uvloop`

 

相关文章:

  • 2021-10-23
  • 2021-10-19
  • 2021-09-29
  • 2022-01-16
  • 2021-11-12
  • 2021-04-06
  • 2021-06-12
  • 2021-12-15
猜你喜欢
  • 2021-10-18
  • 2022-01-19
  • 2021-05-27
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案