pytest运行时错误: Event loop is closed FastApi

标签 pytest

每次我尝试在测试中创建多个异步调用函数时,我都会收到错误 RuntimeError: Event loop is closed。我已经尝试使用 stackoverflow 上的所有建议来重写 event_loop fixture 但没有任何效果。我想知道我错过了什么

运行测试命令:python -m pytest tests/--asyncio-mode=auto

需求.txt

pytest==7.1.2
pytest-asyncio==0.18.3
pytest-html==3.1.1
pytest-metadata==2.0.1

测试.py

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


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

    )

    request_second = test_client_fast_api.post( # recieve RuntimeError: Event loop is closed
        "/second_route",
    )

conftest.py

@pytest.fixture()
def event_loop():
    try:
        loop = asyncio.get_running_loop()
    except RuntimeError:
        loop = asyncio.new_event_loop()
    yield loop
    loop.close()

最佳答案

解决这个问题花了我一下午的时间。 我也尝试从别人的代码中获得成功,这是我的代码。

在放置测试脚本的目录下添加文件conftest.py。 并编写如下代码。

import pytest
from main import app
from httpx import AsyncClient


@pytest.fixture(scope="session")
def anyio_backend():
    return "asyncio"


@pytest.fixture(scope="session")
async def client():
    async with AsyncClient(app=app, base_url="http://test") as client:
        print("Client is ready")
        yield client

然后编写测试脚本test_xxx.py

import pytest
from httpx import AsyncClient


@pytest.mark.anyio
async def test_run_not_exists_schedule(client: AsyncClient):
    response = await client.get("/schedule/list")
    assert response.status_code == 200
    schedules = response.json()["data"]["schedules"]
    schedules_exists = [i["id"] for i in schedules]
    not_exists_id = max(schedules_exists) + 1
    request_body = {"id": not_exists_id}
    response = await client.put("/schedule/run_cycle", data=request_body)
    assert response.status_code != 200


@pytest.mark.anyio
async def test_run_adfasdfw(client: AsyncClient):
    response = await client.get("/schedule/list")
    assert response.status_code == 200
    schedules = response.json()["data"]["schedules"]
    schedules_exists = [i["id"] for i in schedules]
    not_exists_id = max(schedules_exists) + 1
    request_body = {"id": not_exists_id}
    response = await client.put("/schedule/run_cycle", data=request_body)
    assert response.status_code != 200

这是我自己项目的真实测试代码。可以改成自己的。最后在项目的终端运行python -m pytest。如果一切顺利,应该就ok了。这可能涉及到需要安装的库。

pytest
httpx

关于pytest运行时错误: Event loop is closed FastApi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72960518/

相关文章:

python-3.x - 如何使用 PyTest 使用 Locust 执行负载测试?

python - pytest下unittest subTest元素的输出不足

python - 将实参或参数传递给固定功能

Python pytest pytest_exception_interact 从VCR.py异常自定义异常信息

python - Pytest xdist 和参数化测试正在每个线程执行设置?

python - 运行 py.test 时的 .coveragerc 文件位置

python - 自定义 pytest 参数化测试名称

python - 使用 Motor AsyncIO 和 Pytest 测试 MongoDB 功能

python - 在 pytest 中,如何跳过或 xfail 某些固定装置?

python - 审核 url 对允许的方案开放。允许使用 "file:"或自定义方案通常是意外的