cpython
cpython copied to clipboard
Unitest.mock.MagicMock raises a StopIteration - not following PEP 479
It looks like Unitest.mock.MagicMock raises a StopIteration when repeated calls to the mock are made and an iterable is exhausted. After Python 3.7+, due to PEP 479, this raises a Runtime Error. This makes unit tests that worked in Python 3.6 fail, including any list comprehensions on MagicMock results. These can be easily caught with a try/except, but it's a bit clunky.
According to PEP 479 instead of StopIteration MagicMock should just return return when the iterable is exhausted. See here: https://peps.python.org/pep-0479/
Please let me know if I missed something on my end. Thanks for looking into this.
This might be backwards incompatible as raising StopIteration is explicitly documented. Maybe the documentation can be updated to note how this differs from PEP 479.
https://docs.python.org/3/library/unittest.mock.html#calling
The side_effect can also be any iterable object. Repeated calls to the mock will return values from the iterable (until the iterable is exhausted and a StopIteration is raised):