python
runtime_error
ai_generated
true
StopIteration: Caught StopIteration from side_effect; consider using side_effect with an iterable
ID: python/unittest-mock-side-effect-iteration
80%Fix Rate
86%Confidence
0Evidence
2025-11-05First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.9 | active | — | — | — |
Root Cause
Setting mock.side_effect to an iterable (e.g., a generator) that raises StopIteration when exhausted, and the test calls the mock more times than the number of items in the iterable.
generic中文
将 mock.side_effect 设置为可迭代对象(如生成器),当迭代耗尽时引发 StopIteration,而测试调用模拟的次数超过了可迭代对象中的项数。
Workarounds
-
85% success
Ensure the number of mock calls matches the length of the side_effect iterable, or use side_effect with a function that handles arbitrary calls.
-
80% success
Set side_effect to a list with enough items to cover all expected calls, and use a sentinel value for extra calls if needed.
Dead Ends
Common approaches that don't work:
-
50% fail
Using a list instead of a generator for side_effect still raises StopIteration if the list is exhausted, but the error may be more predictable.
-
40% fail
Setting side_effect to a function that returns a default value after exhaustion may mask the fact that the mock is called too many times.