Mar-29-2018, 10:01 PM
(This post was last modified: Mar-29-2018, 10:01 PM by Gribouillis.)
I wrote a way to do this by modifying the
input()
builtin function: suppose you have the module# theaddition.py class addition: def add(): a=int(input("Enter the number : ")) b=int(input("Enter the number two : ")) c= a + b print(c)Then you write the following test file
# testaddition.py from fakeinput import fakeinput from theaddition import addition with fakeinput(['12', '19']): obj = addition.add()Then you get the following output
Output:λ python3 testaddition.py
Enter the number : 12
Enter the number two : 19
31
To make this work, you need to save the following file# fakeinput.py import contextlib import sys @contextlib.contextmanager def fakeinput(sequence): inp = MyInput(sequence) try: yield finally: inp.close() class MyInput: def __init__(self, seq): self.seq = ('{}'.format(x) for x in seq) self.old = sys.modules['builtins'].input sys.modules['builtins'].input = self self.closed = False def __call__(self, s): try: v = next(self.seq) except StopIteration: self.close() return input(s) else: print(s, v, sep='') return v def close(self): if not self.closed: sys.modules['builtins'].input = self.old self.closed = True