cgcardona / muse public
conftest.py python
36 lines 1.2 KB
12901c5a Initial extraction from tellurstori/maestro cgcardona <gabriel@tellurstori.com> 4d ago
1 """Fixtures for muse_cli tests requiring an in-memory database."""
2 from __future__ import annotations
3
4 from collections.abc import AsyncGenerator
5
6 import pytest_asyncio
7 from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
8 from sqlalchemy.pool import StaticPool
9
10 from maestro.db.database import Base
11
12 # Register MuseCli* models with Base.metadata before create_all is called.
13 import maestro.muse_cli.models # noqa: F401, E402
14
15
16 @pytest_asyncio.fixture
17 async def muse_cli_db_session() -> AsyncGenerator[AsyncSession, None]:
18 """In-memory SQLite session with muse_cli (and all other) tables.
19
20 Isolated per test: tables are created fresh and dropped on teardown.
21 """
22 engine = create_async_engine(
23 "sqlite+aiosqlite:///:memory:",
24 connect_args={"check_same_thread": False},
25 poolclass=StaticPool,
26 )
27 async with engine.begin() as conn:
28 await conn.run_sync(Base.metadata.create_all)
29
30 factory = async_sessionmaker(bind=engine, expire_on_commit=False)
31 async with factory() as session:
32 yield session
33
34 async with engine.begin() as conn:
35 await conn.run_sync(Base.metadata.drop_all)
36 await engine.dispose()