首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >pytest RuntimeError:事件循环是关闭的FastApi

pytest RuntimeError:事件循环是关闭的FastApi
EN

Stack Overflow用户
提问于 2022-07-13 03:13:30
回答 2查看 336关注 0票数 3

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

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

requirements.txt

代码语言:javascript
运行
复制
pytest==7.1.2
pytest-asyncio==0.18.3
pytest-html==3.1.1
pytest-metadata==2.0.1

test.py

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
@pytest.fixture()
def event_loop():
    try:
        loop = asyncio.get_running_loop()
    except RuntimeError:
        loop = asyncio.new_event_loop()
    yield loop
    loop.close()
EN

回答 2

Stack Overflow用户

发布于 2022-09-22 08:58:43

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

将文件conftest.py添加到放置测试脚本的目录中。并编写以下代码。

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
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

这是我自己的项目的真正测试代码。您可以将其更改为您的own.Finally,在项目的终端python -m pytest.If中运行,一切都进行得很顺利,应该没有问题,这可能涉及需要安装的库。

代码语言:javascript
运行
复制
pytest
httpx
票数 4
EN

Stack Overflow用户

发布于 2022-10-06 06:11:32

是的,哇,我有一个和你的经历相似的下午

这是为我工作的事件循环夹具和TestClient模式:

代码语言:javascript
运行
复制
from asyncio import get_event_loop
from unittest import TestCase

from async_asgi_testclient import TestClient

@pytest.fixture(scope="module")
def event_loop():
    loop = get_event_loop()
    yield loop

@pytest.mark.asyncio
    async def test_example_test_case(self):
        async with TestClient(app) as async_client:
            response = await async_client.get(
                "/api/v1/example",
                query_string={"example": "param"},
            )
        assert response.status_code == HTTP_200_OK

参考相关的GitHub问题:https://github.com/tiangolo/fastapi/issues/2006#issuecomment-689611040

请注意-我不知道我们如何使用基于类的测试。unittest.TestCaseasynctest.case.TestCase都不会为我工作。pytest-asyncio docs (https://pypi.org/project/pytest-asyncio/)声明:

不支持对标准单元测试库进行子类的测试类,建议用户使用unittest.IsolatedAsyncioTestCase或异步测试等异步框架。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72960518

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档