# 停止迭代：从 side_effect 捕获到 StopIteration；考虑使用可迭代对象作为 side_effect

- **ID:** `python/unittest-mock-side-effect-iteration`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

将 mock.side_effect 设置为可迭代对象（如生成器），当迭代耗尽时引发 StopIteration，而测试调用模拟的次数超过了可迭代对象中的项数。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.9 | active | — | — |

## 解决方案

1. **** (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.
   ```
2. **** (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.
   ```

## 无效尝试

- **** — 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. (50% 失败率)
- **** — 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. (40% 失败率)
