Pytest 返回事件循环已关闭(FastAPI)

Dav*_*ave 6 pytest pytest-asyncio fastapi

使用小型 FastAPI 应用程序,但在针对我的端点运行 pytest 时出现“事件循环关闭”运行时错误。

我有一些像这样的数据库操作AsyncIOMotorClient

async def get_user_data(token: str, client = MongoClient()):
    """ Get user data from database for given token """
    return await client.db.user_data.find_one({"token": token})
Run Code Online (Sandbox Code Playgroud)

还有一些像这样的基本测试:

def test_read_user_data(auth_token):
    response = client.post("/crud/read",
        json={"token":"xxx"},
        headers=HEADERS(auth_token)
    )
    print(response.json())
    assert response.status_code == 200
Run Code Online (Sandbox Code Playgroud)

一组中的第一个测试运行良好,但第二个测试在其中一个数据库操作上总是失败:

self = <_UnixSelectorEventLoop running=False closed=True debug=False>

    def _check_closed(self):
        if self._closed:
>           raise RuntimeError('Event loop is closed')
E           RuntimeError: Event loop is closed

/usr/lib/python3.8/asyncio/base_events.py:508: RuntimeError
================================================== short test summary info ==================================================
FAILED test_routes.py::test_read_user_data - RuntimeError: Event loop is closed
Run Code Online (Sandbox Code Playgroud)

测试的顺序似乎并不重要(如果调换,其他测试会失败),在本例中,4 个数据库操作在失败之前已经成功完成。

我已尝试按照https://fastapi.tiangolo.com/advanced/async-tests/的描述将所有测试转换为异步,但仍然得到相同的结果。还尝试按照其他答案中的描述覆盖事件循环。

这里是否需要异步测试(我不需要在测试代码中同时运行东西)?

如何防止事件循环在测试期间关闭或以其他方式清除此错误?

谢谢。