How do you use the @patch decorator to patch the built-in input() function?
For example, here\'s a function in question.py that I\'d like to test, which contains a c
For Python 3.8 the accepted answer didn't work for me. It didn't like the positional parameter even though my code was actually utilizing it. What worked for me was simply:
@patch('builtins.input')
Not sure if I am doing something wrong, but here you are.
For Python 2.x:
@patch('__builtin__.input')
worked for me.
Or use Mock's return_value
attribute. I couldn't get it to work as a decorator, but here's how to do it with a context manager:
>>> import unittest.mock
>>> def test_input_mocking():
... with unittest.mock.patch('builtins.input', return_value='y'):
... assert input() == 'y'
...
>>> def test_input_mocking():
... with unittest.mock.patch('builtins.input', return_value='y'):
... assert input() == 'y'
... print('we got here, so the ad hoc test succeeded')
...
>>> test_input_mocking()
we got here, so the ad hoc test succeeded
>>>
__builtin__ module is renamed to builtins in Python 3. Replace as follow:
@patch('builtins.input', lambda *args: 'y')
UPDATE
input
has an optional parameter. updated the code to accept the optional parameter.