Async Factory Boy

raw JSON →
1.0.1 verified Mon Apr 27 auth: no python

An extension for factory_boy that adds asynchronous ORM support, enabling creation of model instances with async-compatible factories. Current version is 1.0.1, released in 2024. Maintained actively.

pip install async-factory-boy
error RuntimeError: No async session provided
cause Calling `create_async()` without a `sqlalchemy_session` argument.
fix
Pass sqlalchemy_session=your_async_session to create_async().
error AttributeError: 'NoneType' object has no attribute 'add'
cause Using sync `create()` on an async factory, which tries to add the object to a `sqlalchemy_session` that is None.
fix
Use await factory.create_async() instead of factory.create().
error ImportError: cannot import name 'AsyncFactory' from 'async_factory_boy'
cause Trying to import AsyncFactory from the top-level package, but it's in a submodule.
fix
Use from async_factory_boy.factory import AsyncFactory (or the ORM-specific import).
gotcha Async factories require an explicit async session. Do not rely on a global session; use 'create_async(sqlalchemy_session=session)' or 'build_async()' with session=None.
fix Always pass a session when creating instances. Use an async fixture to provide the session.
gotcha Using 'create()' (sync) with an async session will fail. Use 'create_async()' instead.
fix Replace factory.create() with await factory.create_async().
deprecated The 'AsyncFactory' base class is considered deprecated in favor of specific ORM factories like 'AsyncSQLAlchemyModelFactory'.
fix Use dedicated factory classes for your ORM (e.g., AsyncSQLAlchemyModelFactory) instead of AsyncFactory.
gotcha `Meta.sqlalchemy_session` defined on the factory class is ignored when using `create_async`. It must be passed as an argument.
fix Always pass `sqlalchemy_session` keyword argument to `create_async()`.

Define an async factory for a SQLAlchemy model and create an instance asynchronously.

import asyncio
from async_factory_boy.factory.sqlalchemy import AsyncSQLAlchemyModelFactory
from factory import Faker
from myapp.models import User

class UserFactory(AsyncSQLAlchemyModelFactory):
    class Meta:
        model = User
        sqlalchemy_session = None  # set per test
    name = Faker('name')

async def test_create_user(db_session):
    user = await UserFactory.create_async(sqlalchemy_session=db_session)
    assert user.id is not None