python runtime_error ai_generated true

StopIteration: # raised inside test where side_effect list was consumed

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-05-14First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.10 active
3.11 active
3.12 active

Root Cause

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

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 75% fail

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

  2. 70% fail

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