Skip to content

Instantly share code, notes, and snippets.

@gbzarelli
Last active December 6, 2023 19:20
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gbzarelli/9e1ae8e44de0fe982c0d7d037a78c1c0 to your computer and use it in GitHub Desktop.
Save gbzarelli/9e1ae8e44de0fe982c0d7d037a78c1c0 to your computer and use it in GitHub Desktop.
Python - Mock input() method
from unittest.mock import patch
@patch('builtins.input', lambda _: 'y') # <- value to be returned by input method
def test_should_be_the_correct_value(self):
# replace with your class or method to be tested:
value = input('enter with a value')
assert value == 'y'
# Other way to make the same mock:
class MockInputFunction:
def __init__(self, return_value=None):
self.return_value = return_value
self._orig_input_fn = __builtins__['input']
def _mock_input_fn(self, prompt):
print(prompt + str(self.return_value))
return self.return_value
def __enter__(self):
__builtins__['input'] = self._mock_input_fn
def __exit__(self, type, value, traceback):
__builtins__['input'] = self._orig_input_fn
def test_should_be_the_correct_value(self):
with MockInputFunction('y'): # <- value to be returned by input method
# replace with your class or method to be tested:
value = input('enter with a value')
assert value == 'y'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment