1

I'm trying to write a test (using unittest) for a simple Python program. It is an interactive program, specifcally it will be a text-based game, for now basically a port of World of Zuul to Python.

So now I want to do good test-driven development and write a test and make sure that when the user inputs command x, that y results happen. Example: when the user inputs "quit", I want the program to end. I want to ensure that behavior. The only problem is, I can't seem to think of a way to give my own program input without actually typing that input into the shell, so I can't think of how to write a test for this.

Currently, I have embedded the program in its own thread... I was thinking this would allow me to asynchronously give it input, but I still don't see how this can be done.

Is there a way to programmatically and dynamically give my own program input? ... Like, using stdin or something? If so I am thoroughly confused, and would appreciate an example.

Finally, if I am on the wrong track here, please tell me, because I am new to both Python and test-driven development, and I would appreciate any suggestions.

1 Answer 1

1

You can set up tests that run the program's main function and read the input that the user would provide from a file (or from a string) if you set up the code like this:

def main(inp):
    # play game

if __name__ == '__main__':
    main(sys.stdin)

Then the test involves setting up an input stream (perhaps a StringIO), feeding that to main, and monitoring the output. If you think the program might hang, you can run it in a separate thread and give it a timeout.

If you want to get fancy, you can even use a pty to simulate terminal input.

Sign up to request clarification or add additional context in comments.

3 Comments

I think I see what you're getting at. Feeding from a file would be a super-smart way to do this. But I feel I need to stare down Python docs on I/O for another hour before I actually understand what I need to write inside my test.
In essence, I need to have two separate ways to feed my "main" program. One that works under the "if name == 'main'" conditional, for when it is run as a script, and one that I can automate, with a file or a StringIO. Is that what you're saying?
@Bepetersn: yes, that's what I'm saying. Unit tests are supposed to test small units of the program (usually a class or function), so to use them effectively, you have to set up your program in testable units. Otherwise, you may have to look into other kinds of testing.

Your Answer

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.