0

I have a small python 3 CLI application for which I want to write system tests. Part of this application involves an interactive dialog. How can I simulate the user interaction in pytest? Here is a sketch of what I mean below:

app.py

if __name__ == '__main__':
    name = input("What is your name? ")
    user_id = input("What is your user id? ")

    if user_id == "1":
        print(f"hello {name}, you are user 1")
    else:
        raise ValueError("user id isn't valid!")

I want the test to look something like the following:

test_app.py

import os

def test_example_inputs(capsys):
    # run command with inputs "asdf" and "1"
    exit_status = os.system("python app.py")

    captured = capsys.readouterr()
    
    assert exit_status == 0
    assert captured.out == "hello asdf, you are user 1"

But this test has nothing to read from stdin, so I get an error EOFError: EOF when reading a line. I understand that I could write a unit test and write a mock for input, but I would prefer to write a system test if possible.

bad_coder
  • 11,289
  • 20
  • 44
  • 72
  • If anyone can give me some tips on how to pose this question more clearly or accessibly, I'd be grateful. – MachineEpsilon Nov 25 '20 at 01:37
  • Does this answer your question? [How to test a function with input call?](https://stackoverflow.com/questions/35851323/how-to-test-a-function-with-input-call) – bad_coder Nov 26 '20 at 07:18
  • No, I don't think this answers the question. There are several answers that describe writing a mock for `input` or using `monkeypatch`. That seems more like unit testing the function whereas I would like to write a system test for the app. Is it silly to want to do this? I guess I could write something like `os.system("python app.py < input_file > output_file")` and check `output_file`. – MachineEpsilon Nov 27 '20 at 02:18

0 Answers0