Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
package addtion help
#2
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
Reply


Messages In This Thread
package addtion help - by PyMan - Mar-28-2018, 01:13 PM
RE: package addtion help - by Gribouillis - Mar-29-2018, 10:01 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020