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

在pytest中如何编写返回其他函数AsyncGenerator的fixture?

异步Fixture返回异步生成器时的类型错误问题

正确示例

以下是可正常运行的异步生成器Fixture测试用例:

from collections.abc import AsyncGenerator

import pytest

@pytest.fixture()
async def fixture() -> AsyncGenerator[str, None]:
    yield "a"

@pytest.mark.asyncio
async def test(fixture: str):
    assert fixture[0] == "a"

错误示例及报错

当尝试让Fixture返回另一个函数生成的异步生成器时,会触发类型错误:

from collections.abc import AsyncGenerator

import pytest

async def _fixture() -> AsyncGenerator[str, None]:
    yield "a"

@pytest.fixture()
async def fixture() -> AsyncGenerator[str, None]:
    return _fixture()

@pytest.mark.asyncio
async def test(fixture: str):
    assert fixture[0] == "a"

报错信息:

>     assert fixture[0] == "a"
E     TypeError: 'async_generator' object is not subscriptable

问题原因与修正

你忽略的核心点是:异步Fixture的生成器需要通过yield(或yield from)传递产出值,而非直接返回生成器对象。

错误代码中,return _fixture()会把异步生成器本身返回给测试函数,导致测试里的fixture变量是async_generator对象,而非生成器产出的字符串"a",自然无法执行下标操作。

正确写法是用yield from迭代内部异步生成器,传递它的产出值:

from collections.abc import AsyncGenerator

import pytest

async def _fixture() -> AsyncGenerator[str, None]:
    yield "a"

@pytest.fixture()
async def fixture() -> AsyncGenerator[str, None]:
    yield from _fixture()  # 用yield from替代return

@pytest.mark.asyncio
async def test(fixture: str):
    assert fixture[0] == "a"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 10:15:13