You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI中factory boy风格Fixtures的异步解决方案咨询

具备异步支持的Factory Boy替代方案(针对FastAPI全异步场景)

以下是几个适配全异步FastAPI应用的Fixtures/工厂生成方案,可覆盖序列生成、复杂关联等核心需求:

  • 社区维护的Factory Boy异步分支
    官方异步支持PR停滞,但社区有基于Factory Boy修改的维护版本,保留了原有的语法风格,仅对核心创建逻辑做异步适配。定义工厂时只需将同步的_create方法替换为async def _create,直接兼容SQLAlchemy异步会话、Tortoise-ORM等异步数据库工具,可无缝迁移原有Factory Boy代码。

  • AsyncFactory
    专为异步场景设计的轻量级工厂库,语法和Factory Boy高度相似,原生支持序列生成、关联模型嵌套创建。使用时需传入异步数据库会话,通过异步方法完成实例创建与持久化,示例代码如下:

    from async_factory import AsyncFactory
    from models import User, Post
    from sqlalchemy.ext.asyncio import AsyncSession
    
    class UserFactory(AsyncFactory):
        class Meta:
            model = User
    
        username = Sequence(lambda n: f"test_user_{n}")
        email = Sequence(lambda n: f"test_user_{n}@example.org")
    
    class PostFactory(AsyncFactory):
        class Meta:
            model = Post
    
        title = "Sample Post"
        content = "Sample Content"
        author = SubFactory(UserFactory)  # 支持关联模型
    
    # 在FastAPI测试或应用中使用
    async def create_test_data(session: AsyncSession):
        user = await UserFactory.create(session=session)
        post = await PostFactory.create(session=session, author=user)
        return user, post
    
  • 自定义Pytest异步Fixture
    如果不想引入第三方库,可结合pytest-asyncio编写自定义fixture,封装序列生成、关联模型创建逻辑,完全适配项目的异步数据库流程。这种方式灵活性最高,可根据业务需求定制细节:

    import pytest
    import uuid
    from sqlalchemy.ext.asyncio import AsyncSession
    from models import User, Post
    
    @pytest.fixture
    async def create_user(async_session: AsyncSession):
        user_count = 0
        async def _create(username=None, email=None):
            nonlocal user_count
            user_count += 1
            user = User(
                username=username or f"user_{user_count}",
                email=email or f"user_{user_count}@test.com"
            )
            async_session.add(user)
            await async_session.commit()
            await async_session.refresh(user)
            return user
        return _create
    
    @pytest.fixture
    async def create_post(async_session: AsyncSession, create_user):
        async def _create(author=None, title="Test Post"):
            if not author:
                author = await create_user()
            post = Post(title=title, content="Test Content", author_id=author.id)
            async_session.add(post)
            await async_session.commit()
            await async_session.refresh(post)
            return post
        return _create
    

内容的提问来源于stack exchange,提问作者Matt Sanders

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 11:42:00