python runtime_error ai_generated true

类型错误:'generator' 对象不可调用

TypeError: 'generator' object is not callable

ID: python/pytest-fixture-return-generator

其他格式: JSON · Markdown 中文 · English
80%修复率
85%置信度
0证据数
2024-03-15首次发现

版本兼容性

版本状态引入弃用备注
3.9 active

根因分析

在 pytest fixture 中使用了 yield 但忘记添加 @pytest.fixture 装饰器,导致生成器对象被当作函数调用。

English

在 pytest fixture 中使用了 yield 但忘记添加 @pytest.fixture 装饰器,导致生成器对象被当作函数调用。

generic

解决方案

  1. 95% 成功率 添加 @pytest.fixture 装饰器
    @pytest.fixture
    def my_fixture():
        yield 42
  2. 90% 成功率 在测试函数参数中接收 fixture
    def test_func(my_fixture):
        assert my_fixture == 42

无效尝试

常见但无效的做法:

  1. 将 yield 改为 return,忽略 teardown 70% 失败

    尝试将 fixture 改为普通函数并直接 return,但 fixture 需要 teardown 逻辑,导致资源泄漏

  2. 在测试函数中直接调用 fixture 名称 60% 失败

    在测试函数中直接调用 fixture 名称而不加括号,但 fixture 是生成器,无法被直接调用