1

So I want to write a script to run tests on my codes.

In my python file, I need to take inputs with the input() method, type the input from the terminal, and my program then returns the output to the terminal.

But then I have a folder with testing files, file names like xx.in and sample output for them xx.out.

In my main program, I need to read inputs with input() because it is a rule for my assignments. But in my testing scripts, can I read a file, store the data of that file in a buffer (or a stack?), then feed it to my program (line by line)?

Also, is there a way to write the output from print() which prints to the terminal, but can store it in a file?

At last, the inputs are multi-line, and my program take each line with one input() using a loop, and maybe print() one line of results before it goes to next iteration and read input() again, is there anything I need to take care about that part? Like will the line of input() be included into my output? I don't want it to happen.

Mohanna J
  • 15
  • 3
  • 1
    Look at the `mock` module and the `patch` function. It sounds like you want to `patch` the `input` and `print` functions in your test to map terminal I/O to files. – Samwise Nov 24 '21 at 08:17
  • Does this answer your question? [Using unittest.mock to patch input() in Python 3](https://stackoverflow.com/questions/18161330/using-unittest-mock-to-patch-input-in-python-3) – sytech Nov 24 '21 at 08:53

1 Answers1

0

Solution without mock.

main module like

def main():
    # here your code
    pass

if __name__ == '__main__':
    main()

testing script into directory with main module

from os import listdir, path
import sys
from main import main

def test_all_files(inpdir, outdir):
    files = [f[:-3] for f in listdir(inpdir) if f[-3:] == '.in' and path.isfile(f'{inpdir}\\{f}')]
    for name in files:
        with open(f'{inpdir}\\{name}.in') as inp, open(f'{outdir}\\{name}.out', 'w') as out:
            sys.stdin, sys.stdout = inp, out
            main()

if __name__ == '__main__':
    # here you can write code for read path of folder with test files
    workdir = path.dirname(path.abspath(__file__))
    test_all_files(workdir, workdir)

But if you want to work with testing more, better solution read information about autotest systems like mock

Eugene
  • 345
  • 1
  • 7