python mock input

Solutions on MaxInterview for python mock input by the best coders in the world

showing results for - "python mock input"
Jesús
08 Nov 2019
1from io import StringIO
2
3def enter_name():
4	name = input('Please enter name: ')
5    return 'Hello ' + name
6
7# Suppose we want to mock John as an input for a test
8# All inputs end with a newline character
9mock_input = StringIO('John\n')
10
11# monkeypatch is the parameter passed in test to mock certain values
12def test_enter_name(monkeypatch):
13    # Here 'sys.stdin' is used to specifically mock the standard input
14    # The mock has to be set before the function being tested is run
15  	monkeypatch.setattr('sys.stdin', mock_input)
16    assert enter_name() == 'Hello John'