Summary
I'm using pytest-django with a MySQL Testcontainer and overriding Django's database settings via the documented django_db_modify_db_settings fixture.
The container starts correctly, but Django still tries to connect using the original .env database host/user from settings.DATABASES.
In my case, the app .env contains a Docker Compose hostname:
DATABASE_URL=mysql://innotter:***@mysql:3306/innotter
That hostname is valid inside Docker Compose, but not when running pytest from the host machine.
Even though django_db_modify_db_settings replaces settings.DATABASES["default"] with the Testcontainer host/port, Django still attempts to connect to mysql.
Environment
- Python: 3.13.5
- Django: 6.1
- pytest: 9.1.1
- pytest-django: 4.14.0
- OS: Windows
- DB backend: MySQL
- Test DB:
testcontainers.community.mysql.MySqlContainer
Minimal fixture
import pytest
from django.conf import settings
from django.db import connections
from testcontainers.community.mysql import MySqlContainer
@pytest.fixture(scope="session")
def mysql_container():
with MySqlContainer(
"mysql:8.4",
username="root",
password="test",
root_password="test",
dbname="test",
) as mysql:
yield mysql
@pytest.fixture(scope="session")
def django_db_modify_db_settings(mysql_container):
settings.DATABASES["default"] = {
"ENGINE": "django.db.backends.mysql",
"NAME": mysql_container.dbname,
"USER": mysql_container.username,
"PASSWORD": mysql_container.password,
"HOST": mysql_container.get_container_host_ip(),
"PORT": mysql_container.get_exposed_port(3306),
}
connections.close_all()
Test
import pytest
from myapp.models import Tag
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
async def test_creates_tag():
tag = await Tag.objects.acreate(name="python")
assert tag.name == "python"
Actual behavior
The MySQL Testcontainer starts, but Django still tries to connect using the original .env database settings.
Stack excerpt:
django.db.utils.OperationalError: (2005, "Unknown server host 'mysql' (11001)")
Relevant part of the stack:
pytest_django.fixtures.py:186: in django_db_setup
db_cfg = setup_databases(...)
django.test.utils.py:220: in setup_databases
connection.creation.create_test_db(...)
django.db.backends.base.creation.py:227: in _create_test_db
with self._nodb_cursor() as cursor:
django.db.backends.base.base.py:279: in ensure_connection
self.connect()
MySQLdb.connections.py:206:
super().__init__(*args, **kwargs)
E django.db.utils.OperationalError:
E (2005, "Unknown server host 'mysql' (11001)")
The important detail is that the connection kwargs still contain the app .env values, not the Testcontainer values.
Expected behavior
When django_db_modify_db_settings overrides settings.DATABASES, pytest-django/Django test database setup should use the updated database settings.
At minimum, the documentation should explain that changing settings.DATABASES may not be enough if Django has already created or cached the default connection wrapper.
Root cause / what I found
connections.close_all() is not enough.
It closes existing DB connections, but it does not remove the existing DatabaseWrapper from Django's ConnectionHandler.
So if connections["default"] was materialized earlier from the original .env settings, Django can keep using that stale wrapper during test DB creation.
In newer Django versions, connections.databases is also not the useful cache to clear. It is only a compatibility property:
@property
def databases(self):
return self.settings
The actual cached value is connections.settings, stored in connections.__dict__.
Workaround
This fixed the issue:
@pytest.fixture(scope="session")
def django_db_modify_db_settings(mysql_container):
settings.DATABASES["default"] = {
"ENGINE": "django.db.backends.mysql",
"NAME": mysql_container.dbname,
"USER": mysql_container.username,
"PASSWORD": mysql_container.password,
"HOST": mysql_container.get_container_host_ip(),
"PORT": mysql_container.get_exposed_port(3306),
}
# close existing connections
connections.close_all()
# remove stale DatabaseWrapper created from old settings
try:
del connections["default"]
except AttributeError:
pass
# clear Django's cached ConnectionHandler.settings
connections.__dict__.pop("settings", None)
After this, Django used the Testcontainer database host/port instead of the .env host.
Why I'm raising this
The fixture name django_db_modify_db_settings strongly suggests this is the right place to override database settings before pytest-django creates the test database.
But in practice, if anything has already touched django.db.connections["default"], the override can silently fail because the stale connection wrapper survives.
This is a hard failure to diagnose because the Testcontainer is running correctly, the fixture is being called, and settings.DATABASES looks correct after mutation.
It would be very helpful if pytest-django either:
- documented this caveat clearly,
- provided a recommended way to reset Django's connection handler after changing DB settings,
- or internally ensured stale wrappers are not reused after
django_db_modify_db_settings.
I'm happy to adjust the repro if this is considered expected Django behavior rather than a pytest-django bug, but from a user perspective this feels like a sharp edge in the documented extension point.
Summary
I'm using
pytest-djangowith a MySQL Testcontainer and overriding Django's database settings via the documenteddjango_db_modify_db_settingsfixture.The container starts correctly, but Django still tries to connect using the original
.envdatabase host/user fromsettings.DATABASES.In my case, the app
.envcontains a Docker Compose hostname:That hostname is valid inside Docker Compose, but not when running pytest from the host machine.
Even though
django_db_modify_db_settingsreplacessettings.DATABASES["default"]with the Testcontainer host/port, Django still attempts to connect tomysql.Environment
testcontainers.community.mysql.MySqlContainerMinimal fixture
Test
Actual behavior
The MySQL Testcontainer starts, but Django still tries to connect using the original
.envdatabase settings.Stack excerpt:
Relevant part of the stack:
The important detail is that the connection kwargs still contain the app
.envvalues, not the Testcontainer values.Expected behavior
When
django_db_modify_db_settingsoverridessettings.DATABASES, pytest-django/Django test database setup should use the updated database settings.At minimum, the documentation should explain that changing
settings.DATABASESmay not be enough if Django has already created or cached the default connection wrapper.Root cause / what I found
connections.close_all()is not enough.It closes existing DB connections, but it does not remove the existing
DatabaseWrapperfrom Django'sConnectionHandler.So if
connections["default"]was materialized earlier from the original.envsettings, Django can keep using that stale wrapper during test DB creation.In newer Django versions,
connections.databasesis also not the useful cache to clear. It is only a compatibility property:The actual cached value is
connections.settings, stored inconnections.__dict__.Workaround
This fixed the issue:
After this, Django used the Testcontainer database host/port instead of the
.envhost.Why I'm raising this
The fixture name
django_db_modify_db_settingsstrongly suggests this is the right place to override database settings before pytest-django creates the test database.But in practice, if anything has already touched
django.db.connections["default"], the override can silently fail because the stale connection wrapper survives.This is a hard failure to diagnose because the Testcontainer is running correctly, the fixture is being called, and
settings.DATABASESlooks correct after mutation.It would be very helpful if pytest-django either:
django_db_modify_db_settings.I'm happy to adjust the repro if this is considered expected Django behavior rather than a pytest-django bug, but from a user perspective this feels like a sharp edge in the documented extension point.