python runtime_error ai_generated true

StopIteration: 由 side_effect 列表耗尽引发

StopIteration: raised by side_effect list exhausted

ID: python/unittest-mock-side-effect

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

版本兼容性

版本状态引入弃用备注
3.8 active — — —
3.12 active — — —

根因分析

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

English

A mock's side_effect was set to a finite list, and the code under test called the mock more times than the list length, raising StopIteration.

generic

解决方案

  1. 90% 成功率
    Use a callable for side_effect that handles any number of calls:
    
    m.side_effect = lambda x: x * 2
  2. 88% 成功率
    Extend the list to match the expected call count and assert:
    
    m.side_effect = [1, 2, 3]
    run()
    assert m.call_count == 3

无效尝试

常见但无效的做法:

  1. 85% 失败

    This hides the real issue: the test exercises more calls than expected, or the list is too short.

  2. 80% 失败

    Adding one None only delays the problem; a subsequent call raises StopIteration again.