-1

How would I make my mock return False twice and then any additional call to return True. Here's what I have so far:

def test_moc(self):
    class A:

        def __init__(self):
            self.value = False

        def getValue(self):
            return self.value


    m = mock.Mock(A)
    m.getValue.side_effect = [False, False]
    m.getValue.return_value = True

    self.assertFalse(m.getValue())
    self.assertFalse(m.getValue())
    self.assertTrue(m.getValue())
    self.assertTrue(m.getValue())
    self.assertTrue(m.getValue())

This errors out with StopIteration error since the iterable given to side_effect is len(2) but we've used the function 3 more times afterwards.

self = <Mock name='mock.getValue' id='140154507443744'>, args = (), kwargs = {}
effect = <list_iterator object at 0x7f7843a13d00>

    def _execute_mock_call(self, /, *args, **kwargs):
        # separate from _increment_mock_call so that awaited functions are
        # executed separately from their call, also AsyncMock overrides this method
    
        effect = self.side_effect
        if effect is not None:
            if _is_exception(effect):
                raise effect
            elif not _callable(effect):
>               result = next(effect)
E               StopIteration

../../miniconda3/envs/py39/lib/python3.9/unittest/mock.py:1154: StopIteration
CiaranWelsh
  • 7,014
  • 10
  • 53
  • 106
  • There are several [`side_effect`](https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.side_effect) options, you could pass a function or create an iterator that yields two Falses then potentially infinite Trues. One example: https://stackoverflow.com/a/69903578/3001761 – jonrsharpe Feb 20 '23 at 13:30

1 Answers1

1

You can use the builtin itertools to do just that:

import itertools
..
m.getValue.side_effect = itertools.chain(itertools.repeat(False, 2), itertools.repeat(True))

itertools.repeat(False, 2) returns False two times, while itertools.repeat(True) would return True till infinity. itertools.chain groups them together to a single iterator.

Peter K
  • 1,959
  • 1
  • 16
  • 22