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

如何在pytest测试前通过Fixture填充FastAPI测试数据库?

问题解决方法

错误原因很明确:get_db是你定义的FastAPI依赖函数,不是pytest的fixture,所以无法在test_data fixture的参数中直接引用。以下是具体修复步骤:

1. 在conftest.py中创建测试数据库会话的pytest fixture

添加一个专门用于获取测试数据库连接的fixture,替代直接调用FastAPI的依赖函数:

# conftest.py 原有代码保留,新增以下fixture
@pytest.fixture(scope="function")
def db():
    """获取测试数据库会话,每个测试用例独立使用,测试后自动清理"""
    db = TestingSessionLocal()
    try:
        yield db
    finally:
        # 回滚未提交的操作并关闭连接,避免数据污染其他测试
        db.rollback()
        db.close()

同时建议把数据库初始化逻辑也放到fixture中(避免顶级代码在pytest收集用例时就执行):

@pytest.fixture(scope="module")
def setup_database():
    """整个测试模块仅初始化一次数据库"""
    Base.metadata.drop_all(bind=engine)
    Base.metadata.create_all(bind=engine)
    yield
    # 测试结束后清理数据库
    Base.metadata.drop_all(bind=engine)

# 修改原test_client fixture,依赖数据库初始化
@pytest.fixture(scope="module")
def test_client(setup_database):
    client = TestClient(app)
    yield client

2. 修改test_data fixture使用新的db fixture

把原来的get_db参数替换为上面创建的db fixture:

@pytest.fixture(scope="function")
def test_data(db):
    waiter = Waiter(
        id=1,
        username="User name",
        password="$12$BQhTQ6/OLAmkG/LU6G2J2.ngFk6EI9hBjFNjeTnpj2eVfQ3DCAtT.",
    )
    dish = Dish(
        id=1,
        name="Some dish",
        description="Some description",
        image_url="https://some.io/fhjhd.jpg",
        cost=1.55,
    )
    db.add(waiter)
    db.add(dish)
    db.commit()
    # 可选:返回数据给测试用例直接使用
    return {"waiter": waiter, "dish": dish}

3. 修正测试用例中的fixture名称错误

你的测试用例里写的waiter_data不存在,应该改为定义好的test_data:

def test_get_waiter(test_client, test_data):
    """Test Get a waiter by id."""
    response = test_client.get("/waiters/1")
    assert response.status_code == 200

核心逻辑说明

  • FastAPI的get_db依赖是给接口请求用的,测试fixture需要单独创建数据库会话
  • 用function级别的db fixture可以保证每个测试用例的数据库环境独立,避免数据干扰
  • 把数据库初始化放到module级别的fixture中,避免重复执行创建/删除表的操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 11:25:18