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

如何让带yield的async pytest fixture返回结果而非AsyncGenerator?

问题:pytest异步fixture返回AsyncGenerator而非预期值

代码示例

import pytest


@pytest.fixture
async def my_fixture():
    result = 5
    yield result
    print("Db connection closing or smth yet")


@pytest.mark.asyncio
async def test_my_fixt(my_fixture):
    assert my_fixture == 5

报错信息

FAILED tests/t.py::test_my_fixt - assert <async_generator object my_fixture at 0x7fa13415c450> == 5

解决方法

方法1:无需清理操作时直接返回值

如果不需要yield后的清理代码,把yield result改成return result即可:

@pytest.fixture
async def my_fixture():
    return 5

方法2:保留清理操作时升级依赖

如果需要保留yield后的清理逻辑,问题出在pytest-asyncio版本过低,旧版本不支持异步fixture的yield语法自动解析值。执行以下命令升级依赖:

pip install --upgrade pytest-asyncio

升级后测试函数无需修改,即可直接获取yield返回的5。

方法3:手动迭代异步生成器(不推荐)

如果暂时无法升级依赖,可以在测试函数中手动迭代异步生成器来获取值:

@pytest.mark.asyncio
async def test_my_fixt(my_fixture):
    async for value in my_fixture:
        assert value == 5

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 19:36:11