Skip to content

Commit

Permalink
fix(test): clean_db fixtures does not break if table is missing
Browse files Browse the repository at this point in the history
  • Loading branch information
smotornyuk committed Feb 5, 2024
1 parent 5fd4913 commit 7619f81
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
12 changes: 12 additions & 0 deletions ckan/model/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,10 +270,22 @@ def delete_all(self) -> None:
self.session.remove()
## use raw connection for performance
connection: Any = self.session.connection()
inspector = sa.inspect(connection)
tables = reversed(self.metadata.sorted_tables)
for table in tables:
# `alembic_version` contains current migration version of the
# DB. If we drop this information, next attempt to apply migrations
# will fail. Don't worry about `<PLUGIN>_alembic_version` tables
# created by extensions - CKAN metadata does not track them, so
# they'll never appear in this list.
if table.name == 'alembic_version':
continue

# if custom model imported without migrations applied,
# corresponding table can be missing from DB
if not inspector.has_table(table):
continue

connection.execute(sa.delete(table))
self.session.commit()
log.info('Database table data deleted')
Expand Down
22 changes: 21 additions & 1 deletion ckan/tests/pytest_ckan/test_fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@

import pytest
from urllib.parse import urlparse
from sqlalchemy import inspect
from sqlalchemy import inspect, Column, Integer

import ckan.plugins as plugins
from ckan.common import config, asbool
from ckan.tests import factories
from ckan.lib.redis import connect_to_redis
from ckan.model.base import BaseModel


def test_ckan_config_fixture(ckan_config):
Expand Down Expand Up @@ -180,3 +181,22 @@ def test_reset_redis(self, redis, reset_redis):

reset_redis()
assert not redis.get("BBB-3")


class CustomTestModel(BaseModel):
__tablename__ = "test_table"
id = Column(Integer, primary_key=True)


@pytest.mark.parametrize("_n", [1, 2])
@pytest.mark.usefixtures("clean_db")
def test_clean_db_does_not_break_with_custom_models(_n):
"""This test verifies that `CustomTestModel` that has no corresponding
table in DB is ignored by `clean_db` fixture. If this test is executed
individually, on first run DB may be empty and `clean_db` doesn't try to
delete anything. So we have to run this test two times to guarantee, that
on the second execution tables are created and `clean_db` invokes `DELETE
...` statement.
"""
pass

0 comments on commit 7619f81

Please sign in to comment.