python runtime_error ai_generated true

StopIteration:

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

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

版本兼容性

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

根因分析

一个 mock 的 side_effect 设置为迭代器(例如列表),但被调用的次数超过了迭代器中的项目数。

English

A mock with side_effect set to an iterator (e.g., a list) has been called more times than there are items in the iterator.

generic

解决方案

  1. 90% 成功率
    def side_effect(*args, **kwargs):
        while True:
            yield 'value'
    
    mock.side_effect = side_effect()
  2. 95% 成功率
    mock.assert_called_once()  # or assert_called_with
    This will fail earlier with a clearer message if called too many times.

无效尝试

常见但无效的做法:

  1. 80% 失败

    This may mask the real issue of unexpected extra calls.

  2. 70% 失败

    Changes behavior and may hide bugs.