Skip to content

Commit

Permalink
Keep SQLAlchemy and Django tests in separate DBs
Browse files Browse the repository at this point in the history
This is because Django's TransactionTest do a TRUNCATE flush at the end to clean up
the database. However, this fails due to SQLAlchemy's ongoing transactions in the DB.
So, it's probably best to keep the 2 types of tests separate for now.
  • Loading branch information
michelletran-codecov committed Nov 1, 2024
1 parent a1836d5 commit 0c9de7e
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
35 changes: 34 additions & 1 deletion conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,30 @@ def fin():


@pytest.fixture(scope="session")
def db(engine, sqlalchemy_connect_url, django_db_setup):
@pytest.mark.django_db
def db(
request: pytest.FixtureRequest,
engine,
sqlalchemy_connect_url,
django_db_blocker,
):
# Bootstrap the DB by running the Django bootstrap version.
from django.conf import settings
from django.test.utils import setup_databases, teardown_databases

with django_db_blocker.unblock():
# Temporarily reset the database to the SQLAlchemy DBs
original_name = settings.DATABASES["default"]["NAME"]
original_test_name = settings.DATABASES["default"]["TEST"]["NAME"]
settings.DATABASES["default"]["NAME"] = "test_postgres_sqlalchemy"
settings.DATABASES["default"]["TEST"]["NAME"] = "test_postgres_sqlalchemy"
db_cfg = setup_databases(
verbosity=request.config.option.verbose,
interactive=False,
)
settings.DATABASES["default"]["NAME"] = original_name
settings.DATABASES["default"]["TEST"]["NAME"] = original_test_name

database_url = sqlalchemy_connect_url
if not database_exists(database_url):
raise RuntimeError(f"SQLAlchemy cannot connect to DB at {database_url}")
Expand Down Expand Up @@ -104,6 +126,17 @@ def db(engine, sqlalchemy_connect_url, django_db_setup):
bind=engine
)

yield

try:
teardown_databases(db_cfg, verbosity=request.config.option.verbose)
except Exception as exc: # noqa: BLE001
request.node.warn(
pytest.PytestWarning(
f"Error when trying to teardown test databases: {exc!r}"
)
)


@pytest.fixture
def dbsession(db, engine):
Expand Down
2 changes: 1 addition & 1 deletion pytest.ini
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[pytest]
DJANGO_SETTINGS_MODULE = django_scaffold.tests_settings
addopts = --sqlalchemy-connect-url="postgresql://postgres@postgres:5432/test_postgres" --ignore-glob=**/test_results*
addopts = --sqlalchemy-connect-url="postgresql://postgres@postgres:5432/test_postgres_sqlalchemy" --ignore-glob=**/test_results*
markers=
integration: integration tests (includes tests with vcrs)
real_checkpoint_logger: prevents use of stubbed CheckpointLogger
Expand Down

0 comments on commit 0c9de7e

Please sign in to comment.