python
runtime_error
ai_generated
true
停止迭代:从 side_effect 捕获到 StopIteration;考虑使用可迭代对象作为 side_effect
StopIteration: Caught StopIteration from side_effect; consider using side_effect with an iterable
ID: python/unittest-mock-side-effect-iteration
80%修复率
86%置信度
0证据数
2025-11-05首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.9 | active | — | — | — |
根因分析
将 mock.side_effect 设置为可迭代对象(如生成器),当迭代耗尽时引发 StopIteration,而测试调用模拟的次数超过了可迭代对象中的项数。
English
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.
解决方案
-
85% 成功率
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% 成功率
Set side_effect to a list with enough items to cover all expected calls, and use a sentinel value for extra calls if needed.
无效尝试
常见但无效的做法:
-
50% 失败
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% 失败
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.