File size: 2,159 Bytes
35765b5 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
"""Unit tests for database module."""
import pytest
from sqlalchemy.orm import Session
from app.database import get_db, init_db, SessionLocal, Base, engine
class TestDatabase:
"""Test database initialization and session management."""
def test_init_db_creates_tables(self):
"""Test that init_db creates all model tables."""
init_db()
# Check that tables exist
from app.models import User, Project, Task, LogEntry, ProjectMembership
# Verify table names are in metadata
assert "users" in Base.metadata.tables
assert "projects" in Base.metadata.tables
assert "tasks" in Base.metadata.tables
assert "log_entries" in Base.metadata.tables
assert "project_memberships" in Base.metadata.tables
def test_session_local_returns_session(self):
"""Test SessionLocal creates a valid session."""
session = SessionLocal()
assert isinstance(session, Session)
session.close()
def test_get_db_yields_session(self):
"""Test get_db generator yields a session and closes it."""
gen = get_db()
db = next(gen)
assert isinstance(db, Session)
# Exhaust generator to trigger cleanup
try:
next(gen)
except StopIteration:
pass
def test_get_db_closes_on_exception(self):
"""Test get_db closes session even on exception."""
gen = get_db()
db = next(gen)
# Simulate exception by closing manually
try:
gen.throw(Exception("test error"))
except Exception:
pass
# Session should be closed (no error means cleanup happened)
class TestDatabaseEngine:
"""Test database engine configuration."""
def test_engine_is_sqlite(self):
"""Test engine is configured for SQLite."""
assert "sqlite" in str(engine.url)
def test_engine_allows_multithread(self):
"""Test SQLite is configured for multi-threaded access."""
# check_same_thread=False is set in database.py
assert engine.pool is not None
|