python runtime_error ai_generated true

test_x 拆卸时出错 RuntimeError:throw() 之后生成器未停止

ERROR at teardown of test_x RuntimeError: generator didn't stop after throw()

ID: python/pytest-fixture-yield-teardown-error

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

版本兼容性

版本状态引入弃用备注
7.x active — — —
8.x active — — —

根因分析

yield fixture 的拆卸引发了被吞掉的异常,或生成器捕获了 GeneratorExit 并继续 yield。

English

A yield fixture's teardown raised an exception that was swallowed, or the generator caught GeneratorExit and continued yielding.

generic

解决方案

  1. 95% 成功率
    @pytest.fixture
    def resource():
        r = acquire()
        try:
            yield r
        finally:
            r.close()
  2. 92% 成功率
    import contextlib
    
    @contextlib.contextmanager
    def resource_cm():
        r = acquire()
        try:
            yield r
        finally:
            r.close()
    
    @pytest.fixture
    def resource():
        with resource_cm() as r:
            yield r

无效尝试

常见但无效的做法:

  1. 90% 失败

    Hides the original error and can leak resources.

  2. 85% 失败

    Loses teardown entirely; resources leak.

  3. 95% 失败

    Unrelated to generator teardown.