Pytest returning event loop closed (FastAPI)
Asked Answered
D

0

7

Playing with a small FastAPI application but getting 'event loop closed' RuntimeError when running pytest against my endpoints.

I have some database operations like this using 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})

And some basic tests like this:

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

First test in a set runs fine but the 2nd test invariably fails on one of the database operations:

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

The order of the tests doesn't appear to matter (it fails on others if swapped around), and in this case 4 database operations have already completed successfully before failure.

I have tried converting all the tests to async as described https://fastapi.tiangolo.com/advanced/async-tests/, but still get the same result. Also tried overriding the event loop as described in other answers.

Are async tests are required here at all (I have no requirement to run stuff concurrently within the test code)?

How can I prevent the event loop closing during the tests or otherwise clear this error?

Thanks.

Dorina answered 25/7, 2022 at 19:20 Comment(2)
You can refer to the answer I just answered.Here's a link!Trevar
@BaiJinge unfortunately your solution does not work. I have the exact same issue than at Dave and I tried your solution but I am still getting the same RunTime ErrorMenam

© 2022 - 2024 — McMap. All rights reserved.