30 lines
1.2 KiB
Python
30 lines
1.2 KiB
Python
import pytest
|
|
from unittest.mock import patch
|
|
from sqlalchemy.ext.asyncio import create_async_engine
|
|
from sqlalchemy import text
|
|
from sqlmodel import SQLModel
|
|
from app.database import init_db
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_init_db_creates_tables():
|
|
"""Verifies that init_db() successfully creates all necessary tables.
|
|
|
|
This test uses a patched in-memory SQLite engine to ensure isolation
|
|
and verify the database initialization logic.
|
|
"""
|
|
# Use an in-memory SQLite engine for testing to avoid any impact on real data
|
|
test_engine = create_async_engine("sqlite+aiosqlite:///:memory:")
|
|
|
|
# Patch the engine in app.database so init_db uses our test engine
|
|
with patch("app.database.engine", test_engine):
|
|
await init_db()
|
|
|
|
# Check if the expected table "sleep_session" exists in the schema
|
|
async with test_engine.connect() as conn:
|
|
result = await conn.execute(text("SELECT name FROM sqlite_master WHERE type='table' AND name='sleep_session';"))
|
|
row = result.fetchone()
|
|
assert row is not None, "Table 'sleep_session' was not created by init_db()"
|
|
assert row[0] == "sleep_session"
|
|
|
|
await test_engine.dispose()
|