patch python input code example

Example: python mock input

from io import StringIO

def enter_name():
	name = input('Please enter name: ')
    return 'Hello ' + name

# Suppose we want to mock John as an input for a test
# All inputs end with a newline character
mock_input = StringIO('John\n')

# monkeypatch is the parameter passed in test to mock certain values
def test_enter_name(monkeypatch):
    # Here 'sys.stdin' is used to specifically mock the standard input
    # The mock has to be set before the function being tested is run
  	monkeypatch.setattr('sys.stdin', mock_input)
    assert enter_name() == 'Hello John'