Last active
May 9, 2026 10:20
-
-
Save dorosch/d5198db8931632840adcbb68eda4869a to your computer and use it in GitHub Desktop.
pytest + async sqlalchemy + factoryboy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import pytest | |
| import pytest_asyncio | |
| from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker | |
| from config import settings | |
| from factories import YourFactory | |
| from models import Base | |
| @pytest_asyncio.fixture(scope="session") | |
| async def engine(): | |
| engine = create_async_engine(settings.database.url) | |
| yield engine | |
| await engine.dispose() | |
| @pytest_asyncio.fixture(scope="session", autouse=True) | |
| async def prepare_database(engine): | |
| async with engine.begin() as connection: | |
| await connection.run_sync(lambda conn: Base.metadata.create_all(conn)) | |
| yield | |
| async with engine.begin() as connection: | |
| await connection.run_sync(lambda conn: Base.metadata.drop_all(conn)) | |
| @pytest_asyncio.fixture | |
| async def session(engine): | |
| async with engine.connect() as connection: | |
| await connection.begin() | |
| async_session = async_sessionmaker( | |
| bind=connection, | |
| expire_on_commit=False, | |
| join_transaction_mode="create_savepoint", | |
| ) | |
| async with async_session() as session: | |
| yield session | |
| await connection.rollback() | |
| @pytest_asyncio.fixture(autouse=True) | |
| async def set_factory_session(session): | |
| YourFactory._meta.sqlalchemy_session = session | |
| yield | |
| YourFactory._meta.sqlalchemy_session = None |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from async_factory_boy.factory.sqlalchemy import AsyncSQLAlchemyFactory | |
| from models import Yourmodel | |
| class YourFactory(AsyncSQLAlchemyFactory): | |
| class Meta: | |
| model = Yourmodel | |
| # Factory fields |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Other configs | |
| [tool.pytest.ini_options] | |
| asyncio_mode = "auto" | |
| asyncio_default_test_loop_scope = "session" | |
| asyncio_default_fixture_loop_scope = "session" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment