I am using pytest-asyncio
.
I have the following conftest.py
file:
import asyncio
import pytest
from database.mongo_db import mongo
@pytest.fixture(scope="session", autouse=True)
async def initialise_db():
await mongo.connect_client()
await mongo.drop_db()
@pytest.fixture(scope="session")
def event_loop():
yield asyncio.new_event_loop()
The initialise_db()
function will connect to my database and clear everything from it before all of my tests are run.
Now, I want to close the event loop and also close the connection to my database once all tests are complete. I have tried adding the following function to conftest.py
:
def pytest_sessionfinish(session, exitstatus):
asyncio.get_event_loop().close()
mongo.disconnect_client()
However, this new function has two issues:
asyncio.get_event_loop().close()
raises a warning:DeprecationWarning: There is no current event loop
mongo.disconnect_client()
is an async function. If I changepytest_sessionfinish
to an async function and useawait
when closing the database, then I get the warning:RuntimeWarning: coroutine 'pytest_sessionfinish' was never awaited
, and this is called from within pytest, so I cannot change it to be awaited unless I edit the source code. Of course, if I don't make it an async function I get the warning:RuntimeWarning: coroutine 'disconnect_client' was never awaited
.
How can I resolve these two issues?