tortoise / tortoise/tortoise-orm
Tortoise.get_connection in pytest test raises a KeyError
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 5.6k
- Forks
- 516
- Avg merge
- 2d 21h
- Merged PRs (30d)
- 9
Description
Describe the bug
My project uses some raw SQL. For this, I use Tortoise.get_connection() to get a DB connection. This fails when I run unit tests with pytest with a KeyError.
To Reproduce
test_connection.py:
from tortoise import Tortoise
async def test_get_connection():
c = Tortoise.get_connection('default')
$ pytest test_connection.py
Expected behavior
The test should succeed without an exception. I also tried 'models' and 'test' for the connection name.
Additional context
This seems to be caused by tortoise.contrib.test.initializer() which contains this code:
_CONNECTIONS = Tortoise._connections.copy()
_CONN_MAP = current_transaction_map.copy()
Tortoise.apps = {}
Tortoise._connections = {}
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with test_connection.py and the tortoise.contrib.test.initializer() entry point, then trace how Tortoise._connections is cleared before Tortoise.get_connection('default') runs. Reproduce the KeyError with pytest and verify that the connection lookup succeeds without an exception for the configured connection name.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- backend, testing
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100