How to test function, that has two or more input()'s inside?
<p>I need to test some python 3 code, and I got stuck testing function with few input()'s.</p>

<p>Example:</p>

<pre><code>def two_answers():
    if input("Input 'go' to proceed") != "go":
        return two_answers()
    else:
        while input("Input 'bananas' to proceed") != "bananas":
            print("What?!")
    print("You've just gone bananas!")
</code></pre>

<p>For functions with one input i use:</p>

<pre><code>def test_some_function(self):
    codefile.input = lambda x: 'u'
    codefile.some_function() . . . .
</code></pre>

<p>And then:</p>

<pre><code>def teardown_method(self, method):
    codefile.input = input
</code></pre>

<p>To revert inputs back.</p>

<p>But here it won't work. Help!</p>

<p>I would wrap the input in to a function.</p>

<pre><code>def input_wrap(prompt):
  return input(prompt)
</code></pre>

<p>Then you can inject it.</p>

<pre><code>def two_answers(input_func):
  if input_func('...') != 'go':
    return two_answers(input_func)
  ...
</code></pre>

<p>Now when you want to test it you can inject a fake or a mock:</p>

<pre><code>def test_two_answers(self):
  fake_input = mock.MagicMock()
  fake_input.side_effect = ['go', 'foo', 'bananas']
  two_answers(fake_input) # no assertion for needed since there's no return value
</code></pre>

<p>Later in the code that executes two_answers you call it like this:</p>

<pre><code>two_answers(input_wrap)
</code></pre>

python unit-testing python-3.x python-unittest