python runtime_error ai_generated true

StopIteration:

ID: python/unittest-mock-side-effect-iterator-exhausted

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.8 active
3.12 active

Root Cause

A mock with side_effect set to an iterator (e.g., a list) has been called more times than there are items in the iterator.

generic

中文

一个 mock 的 side_effect 设置为迭代器(例如列表),但被调用的次数超过了迭代器中的项目数。

Workarounds

  1. 90% success
    def side_effect(*args, **kwargs):
        while True:
            yield 'value'
    
    mock.side_effect = side_effect()
  2. 95% success
    mock.assert_called_once()  # or assert_called_with
    This will fail earlier with a clearer message if called too many times.

Dead Ends

Common approaches that don't work:

  1. 80% fail

    This may mask the real issue of unexpected extra calls.

  2. 70% fail

    Changes behavior and may hide bugs.