Skip to content

Commit

Permalink
feat: add database truncation functionality for tests
Browse files Browse the repository at this point in the history
Generated-by: aiautocommit
  • Loading branch information
iloveitaly committed Nov 26, 2024
1 parent 94fa8e2 commit 177abf9
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions activemodel/pytest/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
from sqlmodel import SQLModel

from activemodel import logger

from ..session_manager import get_engine


def truncate_db():
# TODO Problem with truncation is you can't run multiple tests in parallel without separate containers

logger.info("Truncating database")

# TODO get additonal tables to preserve from config
exception_tables = ["alembic_version"]

assert (
SQLModel.metadata.sorted_tables
), "No model metadata. Ensure model metadata is imported before running truncate_db"

with get_engine().connect() as connection:
for table in reversed(SQLModel.metadata.sorted_tables):
transaction = connection.begin()

if table.name not in exception_tables:
logger.debug("truncating table=%s", table.name)
connection.execute(table.delete())

transaction.commit()

0 comments on commit 177abf9

Please sign in to comment.