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

FastAPI集成Tortoise ORM的参数化测试仅首项正常,报事件循环关闭错误

异步参数化测试运行异常

异常表现

  • 运行带有@pytest.mark.parametrize标记的测试时,仅第一组参数可正常执行,从第二组开始的所有测试,无论传入何种测试数据,均抛出统一报错:

    RuntimeError: Event loop is closed

  • 若配置3组待测试数据,因仅第一组可正常运行,上述报错会连续出现2次。初步判断是第一组测试执行完成后,程序误判所有任务已结束,提前关闭了事件循环。
  • 尝试调整fixture的scope参数后,未解决原有问题,反而触发新的报错:

    ScopeMismatch: You tried to access the 'function' scoped fixture 'event_loop' with a 'module' scoped request object, involved factories
    报错堆栈指向pytest_asyncio插件内部的wrapper方法。

现有实现代码

测试用例与数据库Fixture

from tortoise import Tortoise

DATABASE_URL = 'use your own'      # 实际使用postgres数据库
DATABASE_MODELS = ['app.auth.models.rbac',]

# 数据库初始化Fixture
@pytest.fixture
async def db():
    await Tortoise.init(
        db_url=DATABASE_URL,
        modules={'models': DATABASE_MODELS}
    )
    await Tortoise.generate_schemas()

# 参数化测试配置
param = [
    ('user.create', ['AdminGroup', 'NoaddGroup']),
    ('page.create', ['DataGroup'])
]
@pytest.mark.parametrize('perm, out', param)
@pytest.mark.asyncio
async def test_permissions_get_groups(db, perm, out):
    groups = await Permission.get_groups(perm)
    assert Counter(groups) == Counter(out)

简化后的数据模型定义

class Group(models.Model):
    name = fields.CharField(max_length=191, index=True, unique=True)
    permissions: models.ManyToManyRelation['Permission'] = \
        fields.ManyToManyField('models.Permission', related_name='groups',
                               through='auth_group_permissions', backward_key='group_id')
    
    class Meta:
        table = 'auth_group'

class Permission(models.Model):
    code = fields.CharField(max_length=191, index=True, unique=True)
    
    class Meta:
        table = 'auth_permission'
    
    @classmethod
    async def get_groups(cls, code):
        groups = await Group.filter(permissions__code=code).values('name')
        return [i.get('name') for i in groups]

待解决的疑问

曾考虑手动启动事件循环,但无法确认不主动关闭事件循环会产生的影响,目前没有明确的解决路径,需要可落地的fixture实现方案,或者对应的问题排查思路。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.27 09:24:04