Refactor database module and add testing utilities

Simplify database module by re-organizing engine creation, session handling, and removing redundant methods. Introduce SQLite compatibility for testing and add a utility module for test database setup and teardown. Integrate initial unit tests for user models and update dependencies for security and testing.
This commit is contained in:
2025-02-28 12:31:10 +01:00
parent 5cd38c82e0
commit 5f9a63dd07
7 changed files with 140 additions and 124 deletions

View File

View File

@@ -0,0 +1,45 @@
import logging
from sqlalchemy import create_engine, event
from sqlalchemy.orm import sessionmaker, clear_mappers
from sqlalchemy.pool import StaticPool
from app.core.database import Base
logger = logging.getLogger(__name__)
def get_test_engine():
"""Create an SQLite in-memory engine specifically for testing"""
test_engine = create_engine(
"sqlite:///:memory:",
connect_args={"check_same_thread": False},
poolclass=StaticPool, # Use static pool for in-memory testing
echo=False
)
return test_engine
def setup_test_db():
"""Create a test database and session factory"""
# Create a new engine for this test run
test_engine = get_test_engine()
# Create tables
Base.metadata.create_all(test_engine)
# Create session factory
TestingSessionLocal = sessionmaker(
autocommit=False,
autoflush=False,
bind=test_engine,
expire_on_commit=False
)
return test_engine, TestingSessionLocal
def teardown_test_db(engine):
"""Clean up after tests"""
# Drop all tables
Base.metadata.drop_all(engine)
# Dispose of engine
engine.dispose()