Last active
December 6, 2023 19:20
-
-
Save gbzarelli/9e1ae8e44de0fe982c0d7d037a78c1c0 to your computer and use it in GitHub Desktop.
Python - Mock input() method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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