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

PyTest报错ValueError: did not yield a value,fixture用yield遇问题求助

解决pytest fixture中ValueError: did not yield a value报错的问题

你的代码存在两个核心问题导致报错:

  • 在with代码块里使用了return data,这会直接终止函数执行,后面的yield语句永远不会被执行,pytest检测到fixture函数没有产出值,就会抛出该错误。
  • pytest的fixture如果采用yield模式,不能同时使用return,两者只能二选一。

修正后的代码如下:

import pytest
import json

@pytest.fixture
def names_resp():
    with open('ropo_resp.json', 'r') as names:
        data = json.load(names)
        yield data  # 用yield替代return,传递fixture数据给测试用例
    print("a")  # yield之后的代码为清理逻辑,测试用例执行完毕后自动运行

额外说明:

  • 移除了不必要的global data,fixture产出的数据可以直接被测试用例接收,无需全局变量。
  • yield之前的代码是fixture的初始化逻辑,会在测试用例执行前运行;yield之后的代码是资源清理逻辑,会在测试用例执行完成后触发。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 14:40:29