pythonpytestpython-unittestpython-unittest.mock

How to mock __next__ magic method?


How to mock Queue.__next__ magic method? The code below with side_effect is not working:

from unittest.mock import MagicMock


class Queue:

    def __init__(self):
        self.nums = [1, 2, 3]

    def __iter__(self):
        return self

    def __next__(self):
        try:
            num = self.nums.pop()
        except Exception:
            raise StopIteration
        return num


class Consumer:

    def __init__(self, queue):
        self._queue = queue

    def consume(self):
        for msg in self._queue:
            raise ValueError(msg)


def test_it():
    queue = MagicMock()
    queue.__next__.side_effect = [4, 5, 6]  # not working
    consumer = Consumer(queue)
    consumer.consume()

Python interpreter is not even going inside __next__ method. How to make it work?


Solution

  • In your example, the __iter__ method returns nothing.

    def test_it():
        queue = MagicMock()
        queue.__iter__.return_value = [4, 5, 6]
        consumer = Consumer(queue)
        consumer.consume()