0

I'm asking this question having viewed these 2 similar ones:

How to patch multiple repeated inputs in python unit test?

Python mock multiple return values

But neither satisfactorily gives me the answer I'm looking for.

I need to be able to patch multiple calls to input() using the with statement rather than a decorator.

The reason for this is that the test I'm writing doesn't allow me to use a decorator, nor modify the signature of the test method to add the mocked input as in:

@mock.patch('builtins.input')
def test_myMethod(self, mocked_input):
    mock_args = ['20', 100]
    mocked_input.side_effect = mock_args
    res = mymethod()
    self.assertEqual(res, 120)

My question is how can I achieve the same effect using as with statement as in:

def test_myMethod(self):
    with mock.patch('builtins.input', ...)

Any help would be greatly appreciated

femibyte
  • 3,317
  • 7
  • 34
  • 59

1 Answers1

1

Use as... in order to get the mock instance as it is created by the with statement:

def test_myMethod(self):
    mock_args = ['20', 100]
    with mock.patch('builtins.input') as mocked_input:
        mocked_input.side_effect = mock_args
        res = mymethod()
    self.assertEqual(res, 120)

Alternatively, you can pass in the side effect directly to the patch call:

def test_myMethod(self):
    mock_args = ['20', 100]
    with mock.patch('builtins.input', side_effect=mock_args):
        res = mymethod()
    self.assertEqual(res, 120)

As you can see, doing this in particular case means that you won't even need a reference to the mock instance.

jfaccioni
  • 7,099
  • 1
  • 9
  • 25