python runtime_error ai_generated partial

RuntimeError: generator didn't stop after throw()

ID: python/pytest-fixture-yield-without-finally

Also available as: JSON · Markdown · 中文
80%Fix Rate
81%Confidence
0Evidence
2024-09-14First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.10 active

Root Cause

在 fixture 的 yield 之后没有正确处理异常,导致 teardown 代码未执行或生成器未正确关闭。

generic

中文

在 fixture 的 yield 之后没有正确处理异常,导致 teardown 代码未执行或生成器未正确关闭。

Workarounds

  1. 90% success 确保 yield 后没有异常中断
    @pytest.fixture
    def my_fixture():
        setup()
        yield resource
        teardown()
  2. 95% success 使用 try/finally 确保清理
    @pytest.fixture
    def my_fixture():
        try:
            yield resource
        finally:
            teardown()

Dead Ends

Common approaches that don't work:

  1. yield 后直接写清理代码 70% fail

    尝试在 yield 后直接写清理代码,但异常发生时清理代码不执行

  2. 在 finally 中再次 yield 50% fail

    尝试使用 try/finally 但 finally 中又 yield 导致错误