Mock standard input - multi line in python 3
<p>I am new to python and have been using python 3 for my learning. I am using python's unit test framework to test my code.</p>

<p>Problem :-</p>

<p>The function that I need to unit test takes inputs in the following manner:-</p>

<pre><code>def compare():
   a, b, c = input().strip().split(' ')
   d, e, f = input().strip().split(' ')
   # other code here
</code></pre>

<p>I am using the following test case to mock the input :-</p>

<pre><code>class TestCompare(unittest.TestCase):

   @patch("builtins.input", lambda: "1 2 3")
   @patch("builtins.input", lambda: "4 5 6")
   def test_compare(self):
      self.assertEqual(compare(), "1 1")
</code></pre>

<p>The problem I am facing is that when the test case is run the variable triplets a,b,c and d,e,f have the same values - 1,2,3</p>

<p>I have been trying to find a way to inject the second set of inputs to run my test but in vain.</p>

<p>Any help regarding the above is greatly appreciated.</p>

<p>Solution environment :- Python 3</p>

<p>You can't patch out your function twice like that. When you are looking to mock the same function, and have it return different values each time it is called, you should use <a href="https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.side_effect" rel="nofollow">side_effect</a>.</p>

<p><code>side_effect</code> takes a list of values, where each value in the list is the return of every time that function is called in your code: </p>

<pre><code>class TestCompare(unittest.TestCase):

    @patch("builtins.input", side_effect=["1 2 3", "4 5 6"])
    def test_compare(self, mock_input):
        self.assertEqual(compare(), "1 1") 
</code></pre>

python unit-testing python-3.x lambda patch