How can I mock user input (from "input" in 3.x, or "raw_input" in 2.x) for a unit test?
mocking, python, unit-testing
Solution
You can't patch input but you can wrap it to use mock.patch(). Here is a solution:
from unittest.mock import patch
from unittest import TestCase
def get_input(text):
return input(text)
def answer():
ans = get_input('enter yes or no')
if ans == 'yes':
return 'you entered yes'
if ans == 'no':
return 'you entered no'
class Test(TestCase):
# get_input will return 'yes' during this test
@patch('yourmodule.get_input', return_value='yes')
def test_answer_yes(self, input):
self.assertEqual(answer(), 'you entered yes')
@patch('yourmodule.get_input', return_value='no')
def test_answer_no(self, input):
self.assertEqual(answer(), 'you entered no')
Keep in mind that this snippet will only work in Python versions 3.3+
Problem
How can I mock the `input` function (`raw_input` in 2.x) for testing purposes? Given this example code - 3.x version: ``` def answer(): ans = input('enter yes or no') if ans == 'yes': print('you entered yes') if ans == 'no': print('you entered no') ``` 2.x version: ``` def answer(): ans = raw_input('enter yes or no') if ans == 'yes': print 'you entered yes' if ans == 'no': print 'you entered no' ``` How can I write a unit test for the code?