Description
I am using testcontainers to run PostgreSQL in a Docker container and override Django’s database settings dynamically via django_db_setup. However, the tests still attempt to connect to the database defined in settings.py instead of the one from django_db_setup.
Code Snippets
#pyproject.toml
[tool.pytest.ini_options]
DJANGO_SETTINGS_MODULE = "emailcrm.core.settings"
python_files = "tests.py test_*.py *_tests.py"
# settings.py
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": "emailcrm",
"USER": "admin",
"PASSWORD": "password",
"HOST": "localhost",
"PORT": "5432",
}
}
# conftest.py
from typing import Generator
import pytest
from testcontainers.postgres import PostgresContainer
@pytest.fixture(scope="session")
def postgres_container() -> Generator[PostgresContainer, None, None]:
with PostgresContainer("postgres:17") as postgres:
yield postgres
@pytest.fixture(scope="session")
def django_db_setup(postgres_container) -> None:
from django.conf import settings
settings.DATABASES["default"] = {
"ENGINE": "django.db.backends.postgresql",
"NAME": postgres_container.dbname,
"USER": postgres_container.username,
"PASSWORD": postgres_container.password,
"HOST": postgres_container.get_container_host_ip(),
"PORT": postgres_container.get_exposed_port(5432),
}
# test_some_test.py
import pytest
@pytest.mark.django_db
def test_can_connect_to_database() -> None:
assert 1 == 1
Environment
- Python version: 3.13.2
- Django version: 5.1.7
- pytest version: 8.3.5
- pytest-django version: 4.10.0
- testcontainers version: 4.9.2
Expected Behavior
Tests should connect to the database provided by PostgresContainer.
Actual Behavior
Tests attempt to connect to the database from settings.py, leading to
ERROR tests/integration/test_some_test.py::test_can_connect_to_database - django.db.utils.OperationalError: connection failed: connection to server at "127.0.0.1", port 5432 failed: Connection refused
.
.
.
Is this the expected behavior? Should django_db_setup override settings before pytest.mark.django_db initializes the database connection? If not, what is the recommended approach for dynamically setting up test databases with testcontainers?