FastAPI-template
FastAPI-template copied to clipboard
RuntimeError After Pytest Completion
Issue
Encountering a RuntimeError: Event loop is closed error when running pytest in a Docker environment. This issue arises even though the tests complete successfully.
Environment
- Database: MySQL
- ORM: SQLAlchemy
- Command used for running tests:
docker compose -f deploy/docker-compose.yml -f deploy/docker-compose.dev.yml --project-directory . run --build --rm api pytest -vv
Error Observed
template_test/tests/test_dummy.py::test_creation PASSED
template_test/tests/test_dummy.py::test_getting PASSED
template_test/tests/test_echo.py::test_echo PASSED
template_test/tests/test_template_test.py::test_health PASSED
======================================================================================================== 4 passed in 5.37s =========================================================================================================
Exception ignored in: <function Connection.__del__ at 0x7f626e7e3a60>
Traceback (most recent call last):
File "/usr/local/lib/python3.11/site-packages/aiomysql/connection.py", line 1131, in __del__
self.close()
File "/usr/local/lib/python3.11/site-packages/aiomysql/connection.py", line 339, in close
self._writer.transport.close()
File "/usr/local/lib/python3.11/asyncio/selector_events.py", line 860, in close
self._loop.call_soon(self._call_connection_lost, None)
File "/usr/local/lib/python3.11/asyncio/base_events.py", line 761, in call_soon
self._check_closed()
File "/usr/local/lib/python3.11/asyncio/base_events.py", line 519, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Exception ignored in: <function Connection.__del__ at 0x7f626e7e3a60>
Traceback (most recent call last):
self.close()
File "/usr/local/lib/python3.11/site-packages/aiomysql/connection.py", line 339, in close
self._writer.transport.close()
File "/usr/local/lib/python3.11/asyncio/selector_events.py", line 860, in close
self._loop.call_soon(self._call_connection_lost, None)
File "/usr/local/lib/python3.11/asyncio/base_events.py", line 761, in call_soon
self._check_closed()
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
This RuntimeError is logged after the successful completion of tests.
Attempted Fix
- Added
await engine.dispose()at the end of the 'drop_database' and 'create_database' functions in the [created_project_name]/db/utils.py file. - Not certain if this is the correct approach and seeking feedback on this.