1

I have found this URL here: python mocking raw input in unittests

and it answers my question somewhat, but what about the case when there is a lot of raw_inputs? something like this...

class MyModel()
    def my_method(self):
        raw_input("do you want to play a game?: ")
        ...do something
        raw_input("Do you want to do something else?: ")
        ...do something
Community
  • 1
  • 1
Joff
  • 11,247
  • 16
  • 60
  • 103

2 Answers2

1

Simple answer: wraps each call to raw_input() in distinct object that you can easily mock.

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
1

If I understand correctly, you wanted to mock each and every raw_input method but set different return value. unittest.mock comes up with side_effect properties. that can be helpful in this case. https://docs.python.org/3/library/unittest.mock.html#quick-guide

Python Mock object with method called multiple times

The key point here is the paramater of the raw_input function.

Example:

from unittest import mock
from unittest import TestCase

class MyTest(TestCase):
    @mock.patch.object(__builtins__, 'raw_input')
    def test_my_method(self, mock_input):
        # If raw_input called thrice in the my_method
        mock_input.side_effect = lambda param: {'First': 'Great', 'Second': 'Good', 'Third':
'Awesome'}.get(param, 'Default return')
        my_class = actual_module.MyModel()
        self.assertEqual(my_class.my_method(), 'GreatGoodAwesome')

Here 'First', 'Second' 'Third' are the actual string of the raw_input used in the method. So the only thing you need to modify is to replace the 'First' with 'do you want to play a game?: ' and so on.

And Assuming my_method returns the concatenation of the response of the raw_input method. Please note that code is not properly tested.

Community
  • 1
  • 1
MaNKuR
  • 2,578
  • 1
  • 19
  • 31
  • i've been reading over those docs and I think that will do the trick for me but I am unsure about how to actually execute it in my example, could you write a simple example if you have time? – Joff Jul 19 '16 at 11:59