小编Dmi*_*kzn的帖子

使用 pytest-asyncio 测试 FastAPI 路由时出现“RuntimeError:事件循环已关闭”

我收到错误

运行时错误:事件循环已关闭

每次我尝试在测试中进行多个异步调用时。我已经尝试使用其他 Stack Overflow 帖子中的所有其他建议来重写固定event_loop装置,但没有任何效果。我想知道我错过了什么?

运行测试命令:

python -m pytest tests/ --asyncio-mode=auto
Run Code Online (Sandbox Code Playgroud)

要求.txt

pytest==7.1.2
pytest-asyncio==0.18.3
pytest-html==3.1.1
pytest-metadata==2.0.1
Run Code Online (Sandbox Code Playgroud)

测试.py

async def test_user(test_client_fast_api):
    assert 200 == 200

    # works fine
    request_first = test_client_fast_api.post("/first_route")

    # recieve RuntimeError: Event loop is closed
    request_second = test_client_fast_api.post("/second_route")
Run Code Online (Sandbox Code Playgroud)

测试.py

@pytest.fixture()
def event_loop():
    try:
        loop = asyncio.get_running_loop()
    except RuntimeError:
        loop = asyncio.new_event_loop()
    yield loop
    loop.close()
Run Code Online (Sandbox Code Playgroud)

python pytest pytest-asyncio

7
推荐指数
1
解决办法
5901
查看次数

标签 统计

pytest ×1

pytest-asyncio ×1

python ×1