python runtime_error ai_generated true

TypeError: 'generator' object is not callable

ID: python/pytest-fixture-return-generator

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-03-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.9 active

Root Cause

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

generic

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

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

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

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

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