pytest 夹具中的异步 SQLAlchemy:greenlet_spawn 尚未被调用

问题描述 投票:0回答:1

所以我们假设我尝试检索所有用户进行 Pytest 测试作为固定装置:

@pytest_asyncio.fixture(scope="function")
async def test_users(db_session):
    async with db_session.begin():
        cursor = await db_session.execute(
            select(User)
        )
        return cursor.scalars().fetchall()

问题是,当我尝试访问另一个函数(例如夹具)中的对象属性时,我收到错误sqlalchemy.exc.MissingGreenlet:greenlet_spawn尚未被调用

@pytest_asyncio.fixture(scope="function")
async def another_fixture(test_users: List[User]):
    print(test_users[0].id) # sqlalchemy.exc.MissingGreenlet: greenlet_spawn has not been called

我做错了什么吗?我尝试在每个对象上使用 db_session.refresh(),但它不起作用。

更新

这是我的 db_session 夹具的实现:

@pytest_asyncio.fixture(scope="function")
async def db_session():
    async with get_db_engine().connect() as connection:
        async with get_db_session() as session:
            yield session
        await connection.rollback()
python sqlalchemy orm pytest python-asyncio
1个回答
0
投票

您收到此错误的原因是您试图引用会话之外的字段。您可以从会话中删除对象,以便能够在其他地方访问它们。因此,您需要像这样更新

test_users
夹具。

@pytest_asyncio.fixture(scope="function")
async def test_users(db_session):
    async with db_session.begin() as session:
        cursor = await session.execute(
            select(User)
        )
        users = cursor.scalars().fetchall()
        session.expunge_all()
        return users
© www.soinside.com 2019 - 2024. All rights reserved.