python runtime_error ai_generated true

StopIteration: # 在测试中 side_effect 列表耗尽后引发

StopIteration: # raised inside test where side_effect list was consumed

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

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2024-05-14首次发现

版本兼容性

版本状态引入弃用备注
3.10 active
3.11 active
3.12 active

根因分析

Mock 的 side_effect 被设置为有限列表,但被测代码调用 mock 的次数超过列表长度;多余的调用引发 StopIteration。

English

A Mock's side_effect was set to a finite list, but the code under test calls the mock more times than the list has entries; the extra call raises StopIteration.

generic

解决方案

  1. 95% 成功率
    mock.get.side_effect = lambda key: {'a': 1, 'b': 2}.get(key, 0)
  2. 88% 成功率
    from itertools import chain, repeat
    mock.get.side_effect = chain([1, 2], repeat(0))

无效尝试

常见但无效的做法:

  1. 75% 失败

    Fixes the current call count but breaks again when the code loops over a different-sized input.

  2. 70% 失败

    Loses the ability to return different values per call, which is often the whole point of the test.