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

FastAPI+Tortoise ORM下,如何在异步类单元测试中使用pytest fixtures?

解决FastAPI+Tortoise ORM中pytest fixture在类测试中的引入问题

核心问题

你当前使用的Tortoise.contrib.test.TestCase基于Python标准库的unittest.TestCase,这类测试类无法直接像pytest原生测试那样自动注入fixture,需要调整写法来兼容。

推荐方案:改用pytest原生异步测试风格

放弃继承Tortoise的TestCase,配合pytest-asyncio插件和Tortoise的初始化工具来实现测试,这种方式更贴合pytest生态,fixture注入更顺畅。

步骤1:更新conftest.py

添加Tortoise数据库初始化的fixture,同时保留client fixture:

import pytest
from app.main import app
from httpx import AsyncClient
from tortoise.contrib.test import initializer, finalizer
from app import models  # 导入你的所有模型模块

@pytest.fixture(scope='module')
def setup_tortoise():
    # 初始化内存数据库,可替换为你的测试数据库配置
    initializer(['app.models'], db_url='sqlite://:memory:')
    yield
    # 测试结束后清理资源
    finalizer()

@pytest.fixture(scope='module')
async def client(setup_tortoise):
    async with AsyncClient(app=app, base_url='http://test') as c:
        yield c

步骤2:修改测试文件tests.py

使用pytest风格的测试类,用@pytest.mark.asyncio标记异步测试方法:

import pytest

class TestDashboard:
    @pytest.mark.asyncio
    async def test_get_dashboard(self, client):
        r = await client.get('/dashboard/')
        assert r.status_code == 200

备选方案:兼容unittest风格的TestCase

如果坚持使用Tortoise的TestCase,可以通过pytest.mark.usefixtures装饰器显式引入fixture:

from tortoise.contrib.test import TestCase
import pytest

@pytest.mark.usefixtures('client')
class MyTestcase(TestCase):
    async def test_get_dashboard(self, client):
        r = await client.get('/dashboard/')
        assert r.status_code == 200

注意事项

  • 确保已安装pytest-asyncio插件,pytest本身不支持异步测试函数:
    pip install pytest-asyncio
    
  • 测试数据库配置可根据实际需求调整,比如使用真实测试数据库而非内存库。

内容的提问来源于stack exchange,提问作者Tom Hamilton Stubber

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 12:42:54