Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python mocking raw input in unittests

Suppose I have this python code:

def answer():     ans = raw_input('enter yes or no')     if ans == 'yes':         print 'you entered yes'     if ans == 'no':         print 'you entered no' 

How do I write a unittest for this ? I know i have to use 'Mock' but I don't understand how. Can anyone make some simple example ?

like image 491
user3156971 Avatar asked Jan 10 '14 14:01

user3156971


People also ask

What is mocking in unit testing Python?

New in version 3.3. unittest.mock is a library for testing in Python. It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used. unittest.mock provides a core Mock class removing the need to create a host of stubs throughout your test suite.

How do you take test case input in Python?

You just have to call the get_ints() function in order to take input in this form.

What is assertFalse in Python?

assertFalse() in Python is a unittest library function that is used in unit testing to compare test value with false. This function will take two parameters as input and return a boolean value depending upon the assert condition. If test value is false then assertFalse() will return true else return false.


1 Answers

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+

like image 113
gawel Avatar answered Oct 14 '22 20:10

gawel