2

I have a function in my code that asks the user for input:

def function_1():
 ...
 x = input('Please provide input')
 ...
 return something

I want to be able to run my code, and when the program eventually reaches function_1 and asks the user for input, automatically provide it with some specified input. When unittesting, I can use the mock library to simulate keyboard input as below

@mock.patch('builtins.input', side_effects=[1,2,3])
function_1()
function_1()
function_1()

This calls the function three times and provides the inputs {1, 2, 3}. I'm wondering if there is a way to do the same thing outside of unittesting.

I'm aware that I can rewrite the code, or use pipe in terminal. But I'm more curious about whether this can be solved in the manner described above.

asked Jan 10, 2020 at 15:15
0

2 Answers 2

2

One way is to overwrite sys.stdin:

import sys
from io import StringIO
oldstdin = sys.stdin
sys.stdin = StringIO("1\n2\n3\n")
assert input() == "1"
assert input() == "2"
assert input() == "3"
sys.stdin = oldstdin
answered Jan 10, 2020 at 15:23
Sign up to request clarification or add additional context in comments.

Comments

1

The great thing about Python is that you can override just about any function, even built-ins.

def override():
 from itertools import count
 counter = count()
 return lambda *args, **kwargs: next(counter)
input = override()
def x():
 return input("Testing123")
print(x()) # 1
print(x()) # 2 
print(x()) # 3

Though, this has to be done before your functions are called.

answered Jan 10, 2020 at 15:34

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.